Intent 应用详解

来源:互联网 发布:windows界面停止工作 编辑:程序博客网 时间:2024/05/13 20:06
 Intent 是什么?
  Intent是一种运行时绑定(runtime binding)机制,它能在程序运行的过程中连接两个不同的组件。通过Intent,你的程序可以向Android表达某种请求或者意愿,Android会根据意愿的内容选择适当的组件来请求。我们就来看一下几个常见的操作:

启动一个Activity:Context.startActivity(Intent intent);

启动一个Service:Context.startService(Intent service);

绑定一个Service:Context.bindService(Intent service, ServiceConnection conn, int flags);

发送一个Broadcast:Context.sendBroadcast(Intent intent);

    Intent有几个重要的属性,下面我们将会逐一介绍:
1.action,要执行的动作
   对于有如下声明的Activity:   
<activity android:name=".TargetActivity">      <intent-filter>          <action android:name="com.scott.intent.action.TARGET"/>          <category android:name="android.intent.category.DEFAULT"/>      </intent-filter>  </activity>  
  TargetActivity在其<intent-filter>中声明了<action>,即目标action,如果我们需要做一个跳转的动作,就需要在Intent中指定目标的action,如下:
public void gotoTargetActivity(View view) {      Intent intent = new Intent("com.scott.intent.action.TARGET");      startActivity(intent);  }  
 当我们为Intent指定相应的action,然后调用startActivity方法后,系统会根据action跳转到对应的Activity。
2.data和extras,即执行动作要操作的数据和传递到目标的附加信息 
//打开指定网页public void invokeWebBrowser(View view) {      Intent intent = new Intent(Intent.ACTION_VIEW);      intent.setData(Uri.parse("http://www.google.com.hk"));      startActivity(intent);  } //打电话public void call(View view) {      Intent intent = new Intent(Intent.ACTION_CALL);      intent.setData(Uri.parse("tel:12345678"));      startActivity(intent);  }  
 action分别是Intent.ACTION_VIEW和Intent.ACTION_CALL,在打开网页时,为Intent指定一个data属性,这其实是指定要操作的数据,是一个URI的形式,我们可以将一个指定前缀的字符串转换成特定的URI类型,如:“http:”或“https:”表示网络地址类型,“tel:”表示电话号码类型,“mailto:”表示邮件地址类型,等等。
    那么我们如何知道目标是否接受这种前缀呢?这就需要看一下目标中<data/>元素的匹配规则了。

在目标<data/>标签中包含了以下几种子元素,他们定义了url的匹配规则:

android:scheme 匹配url中的前缀,除了“http”、“https”、“tel”...之外,我们可以定义自己的前缀

android:host 匹配url中的主机名部分,如“google.com”,如果定义为“*”则表示任意主机名

android:port 匹配url中的端口

android:path 匹配url中的路径

我们改动一下TargetActivity的声明信息:
<activity android:name=".TargetActivity">      <intent-filter>          <action android:name="com.scott.intent.action.TARGET"/>          <category android:name="android.intent.category.DEFAULT"/>          <data android:scheme="scott" android:host="com.scott.intent.data" android:port="7788" android:path="/target"/>      </intent-filter>  </activity>  
这个时候如果只指定action就不够了,我们需要为其设置data值,如下:
public void gotoTargetActivity(View view) {      Intent intent = new Intent("com.scott.intent.action.TARGET");      intent.setData(Uri.parse("scott://com.scott.intent.data:7788/target"));      startActivity(intent);  }  
 此时,url中的每个部分和TargetActivity配置信息中全部一致才能跳转成功,否则就被系统拒绝。
     Bundle和Intent有着密不可分的关系,主要负责为Intent保存附加参数信息,它实现了android.os.Paracelable接口,内部维护一个Map类型的属性,用于以键值对的形式存放附加参数信息。在我们使用Intent的putExtra方法放置附加信息时,该方法会检查默认的Bundle实例为不为空,如果为空,则新创建一个Bundle实例,然后将具体的参数信息放置到Bundle实例中。我们也可以自己创建Bundle对象,然后为Intent指定这个Bundle即可,
public void gotoTargetActivity(View view) {      Intent intent = new Intent("com.scott.intent.action.TARGET");      Bundle bundle = new Bundle();      bundle.putInt("id", 0);      bundle.putString("name", "scott");      intent.putExtras(bundle);      startActivity(intent);  }  
  需要注意的是,在使用putExtras方法设置Bundle对象之后,系统进行的不是引用操作,而是复制操作,所以如果设置完之后再更改bundle实例中的数据,将不会影响Intent内部的附加信息。那我们如何获取设置在Intent中的附加信息呢?与之对应的是,我们要从Intent中获取到Bundle实例,然后再从中取出对应的键值信息:
Bundle bundle = intent.getExtras();int id = bundle.getInt("id");String name = bundle.getString("name");
3.category,要执行动作的目标所具有的特质或行为归类
例如:在我们的应用主界面Activity通常有如下配置:    
<category android:name="android.intent.category.LAUNCHER" />  
代表该目标Activity是该应用所在task中的初始Activity并且出现在系统launcher的应用列表中。

几个常见的category如下:

Intent.CATEGORY_DEFAULT(android.intent.category.DEFAULT) 默认的category

Intent.CATEGORY_PREFERENCE(android.intent.category.PREFERENCE) 表示该目标Activity是一个首选项界面;

Intent.CATEGORY_BROWSABLE(android.intent.category.BROWSABLE)指定了此category后,在网页上点击图片或链接时,系统会考虑将此目标Activity列入可选列表,供用户选择以打开图片或链接。

在为Intent设置category时,应使用addCategory(String category)方法向Intent中添加指定的类别信息,来匹配声明了此类别的目标Activity。

4.type:要执行动作的目标Activity所能处理的MIME数据类型
例如:一个可以处理图片的目标Activity在其声明中包含这样的mimeType:
<data android:mimeType="image/*" />  
在使用Intent进行匹配时,我们可以使用setType(String type)或者setDataAndType(Uri data, String type)来设置mimeType。
5.component,目标组件的包或类名称
在使用component进行匹配时,一般采用以下几种形式
intent.setComponent(new ComponentName(getApplicationContext(), TargetActivity.class));  intent.setComponent(new ComponentName(getApplicationContext(), "com.scott.intent.TargetActivity"));  intent.setComponent(new ComponentName("com.scott.other", "com.scott.other.TargetActivity"));  
其中,前两种是用于匹配同一包内的目标,第三种是用于匹配其他包内的目标。需要注意的是,如果我们在Intent中指定了component属性,系统将不会再对action、data/type、category进行匹配。

Intent-Filter的定义
一些属性设置的例子:
<action android:name="com.example.project.SHOW_CURRENT" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="video/mpeg" android:scheme="http" . . . /> <data android:mimeType="image/*" /><data android:scheme="http" android:type="video/*" />
完整的实例:
<activity android:name="NotesList" android:label="@string/title_notes_list">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <intent-filter>                <action android:name="android.intent.action.VIEW" />                <action android:name="android.intent.action.EDIT" />                <action android:name="android.intent.action.PICK" />                <category android:name="android.intent.category.DEFAULT" />                <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />            </intent-filter>            <intent-filter>                <action android:name="android.intent.action.GET_CONTENT" />                <category android:name="android.intent.category.DEFAULT" />                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />            </intent-filter>        </activity>
Intent用法实例
2.向下一个Activity传递数据(使用Bundle和Intent.putExtras)

Intent it = new Intent(Activity.Main.this, Activity2.class);Bundle bundle=new Bundle();bundle.putString("name", "This is from MainActivity!");it.putExtras(bundle);       // it.putExtra(“test”, "shuju”);startActivity(it);            // startActivityForResult(it,REQUEST_CODE);
对于数据的获取可以采用:
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");
3.向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动的Activity)
        Intent intent=getIntent();
        Bundle bundle2=new Bundle();
        bundle2.putString("name", "This is from ShowMsg!");
        intent.putExtras(bundle2);
        setResult(RESULT_OK, intent);
4.回调上一个Activity的结果处理函数(onActivityResult)
@Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        // TODO Auto-generated method stub        super.onActivityResult(requestCode, resultCode, data);        if (requestCode==REQUEST_CODE){            if(resultCode==RESULT_CANCELED)                  setTitle("cancle");            else if (resultCode==RESULT_OK) {                 String temp=null;                 Bundle bundle=data.getExtras();                 if(bundle!=null)   temp=bundle.getString("name");                 setTitle(temp);            }        }    }
下面是转载来的其他的一些Intent用法实例
显示网页
Uri uri = Uri.parse("http://google.com");     Intent it = new Intent(Intent.ACTION_VIEW, uri);     startActivity(it);
显示地图   
Uri uri = Uri.parse("geo:38.899533,-77.036476");  Intent it = new Intent(Intent.ACTION_VIEW, uri);   startActivity(it);   //其他 geo URI 範例  //geo:latitude,longitude  //geo:latitude,longitude?z=zoom  //geo:0,0?q=my+street+address  //geo:0,0?q=business+near+city  //google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom
路径规划
 Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");   Intent it = new Intent(Intent.ACTION_VIEW, uri);   startActivity(it);   //where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456 
打电话
    //叫出拨号程序    Uri uri = Uri.parse("tel:0800000123");     Intent it = new Intent(Intent.ACTION_DIAL, uri);     startActivity(it);     //直接打电话出去     Uri uri = Uri.parse("tel:0800000123");     Intent it = new Intent(Intent.ACTION_CALL, uri);     startActivity(it);     //用這個,要在 AndroidManifest.xml 中,加上      //<uses-permission id="android.permission.CALL_PHONE" /> 
传送SMS/MMS  
    //调用短信程序     Intent it = new Intent(Intent.ACTION_VIEW, uri);      it.putExtra("sms_body", "The SMS text");       it.setType("vnd.android-dir/mms-sms");      startActivity(it);     //传送消息     Uri uri = Uri.parse("smsto://0800000123");      Intent it = new Intent(Intent.ACTION_SENDTO, uri);      it.putExtra("sms_body", "The SMS text");      startActivity(it);     //传送 MMS      Uri uri = Uri.parse("content://media/external/images/media/23");      Intent it = new Intent(Intent.ACTION_SEND);       it.putExtra("sms_body", "some text");       it.putExtra(Intent.EXTRA_STREAM, uri);      it.setType("image/png");       startActivity(it); 
传送 Email
    Uri uri = Uri.parse("mailto:xxx@abc.com");      Intent it = new Intent(Intent.ACTION_SENDTO, uri);      startActivity(it);     Intent it = new Intent(Intent.ACTION_SEND);      it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");      it.putExtra(Intent.EXTRA_TEXT, "The email body text");      it.setType("text/plain");      startActivity(Intent.createChooser(it, "Choose Email Client"));     Intent it=new Intent(Intent.ACTION_SEND);        String[] tos={"me@abc.com"};        String[] ccs={"you@abc.com"};        it.putExtra(Intent.EXTRA_EMAIL, tos);        it.putExtra(Intent.EXTRA_CC, ccs);        it.putExtra(Intent.EXTRA_TEXT, "The email body text");        it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");        it.setType("message/rfc822");        startActivity(Intent.createChooser(it, "Choose Email Client"));    //传送附件    Intent it = new Intent(Intent.ACTION_SEND);      it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");      it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");      sendIntent.setType("audio/mp3");      startActivity(Intent.createChooser(it, "Choose Email Client"));
播放多媒体      
 Uri uri = Uri.parse("file:///sdcard/song.mp3");         Intent it = new Intent(Intent.ACTION_VIEW, uri);         it.setType("audio/mp3");         startActivity(it);        Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");         Intent it = new Intent(Intent.ACTION_VIEW, uri);         startActivity(it);
Market 相关
        //寻找某个应用         Uri uri = Uri.parse("market://search?q=pname:pkg_name");         Intent it = new Intent(Intent.ACTION_VIEW, uri);          startActivity(it);          //where pkg_name is the full package path for an application         //显示某个应用的相关信息         Uri uri = Uri.parse("market://details?id=app_id");          Intent it = new Intent(Intent.ACTION_VIEW, uri);         startActivity(it);          //where app_id is the application ID, find the ID           //by clicking on your application on Market home           //page, and notice the ID from the address bar
Uninstall 应用程序
        Uri uri = Uri.fromParts("package", strPackageName, null);         Intent it = new Intent(Intent.ACTION_DELETE, uri);           startActivity(it); 





0 0