意图——学习笔记总结

来源:互联网 发布:斯普特尼克恋人 知乎 编辑:程序博客网 时间:2024/06/09 17:00



Intent意图

   Intent负责对应用中一次操作的动作、动作涉及数据、附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组件,将 Intent传递给调用的组件,并完成组件的调用。因此,Intent在这里起着一个媒体中介的作用,专门提供组件互相调用的相关信息,实现调用者与被调用者之间的解耦。

Intent表现形式

   * 调用Activity: startActivity(intent),startActivityForResult(Intent)

   * 调用Service:服务startService(intent) \bindService(intent)绑定服务

   * 发送广播 :sendBroadcast(intent)发送无序广播

sendOrderedBroadcast(Intent)发送有序广播

Intnet属性设置

  * setAction: 设置动作

ACTION_MAIN、ACTION_VIEW、ACTION_GET_CONTENT、ACTION_EDIT

    *setData: 设置数据  :Uri格式的数据,标准数据

 该函数的参数是uri,所以要将数据通过该函数传递时,记得要把数据转化为uri,如Uri.fromFile(new File("/mnt/sdcard/"))。

    *setType:设置数据的类型 :MIME(image/*,video/* ,text/plain)

* addCateGory: 添加你要调用的组件的类别

  CATEGORY_LAUNCHER   CATEGORY_HOME 

CATEGORY_BROWSABLE CATEGORY_DEFAULT

注:同时设置data和type的话,只能用函数setDataandType

案列:

//浏览百度网站       Intent intent=new Intent();//创建意图       intent.setAction(Intent.ACTION_MAIN);//设置意图动作        //设置要传递的数据       intent.setData(Uri.parse("http://www.baidu.com"));       //添加目标组件的类别       intent.addCategory(Intent.CATEGORY_BROWSABLE);       //执行意图       startActivity(intent);

显式意图与隐式意图

    * 显示调用是直接指定类名,Android不用再去解析intent

    * 隐式调用需要设置action、data、category、type,再有Android解析你的意图

显式调用:

<span style="white-space:pre"></span>Intent intent=new Intent();/**显示调用第三方应用的Activity * 参数1:packageName 包名 * 参数2:className   类名 */intent.setClassName("cn.itcast.sharedpreference","cn.itcast.sharedpreference.LoginActivity");startActivity(intent);

Intent附带数据

 * 两种写法 :

&通过Intent.putExtra(key,value)添加

&通过bundle添加

 * 添加额外数据

//添加附加数据 通过putExtra()intent.putExtra("name", "千王之王");//附加字符串数据intent.putExtra("price", 50);//附加整形数据//通过Bundle附加数据Bundle bundle=new Bundle();bundle.putString("info", "长大后,我就成了人");bundle.putString("news", "凤姐,不是一般的姐");//把bundle添加到intent中intent.putExtras(bundle);//执行意图startActivity(intent);

* 在目标组件中获取上一个组件传递过来的额外数据

//获得从上一次组件中传过来的附加数据Intent intent=getIntent();String name=intent.getStringExtra("name");int price=intent.getIntExtra("price", 0);String info=intent.getStringExtra("info");Bundle bundle=intent.getExtras();//取得传过来的bundleToast.makeText(this, info+bundle.getString("info")+bundle.getString("news"),Toast.LENGTH_LONG).show();








0 0
原创粉丝点击