讲解Intent中的四个重要属性——Action、Data、Category、Extras

来源:互联网 发布:linux查看文件个数命令 编辑:程序博客网 时间:2024/05/16 10:10

1 前言

Intent作为联系各Activity之间的纽带,其作用并不仅仅只限于简单的数据传递。通过其自带的属性,其实可以方便的完成很多较为复杂的操作。例如直接调用拨号功能、直接自动调用合适的程序打开不同类型的文件等等。诸如此类,都可以通过设置Intent属性来完成。

 Intent主要有以下四个重要属性,它们分别为:

    Action:Action属性的值为一个字符串,它代表了系统中已经定义了一系列常用的动作。通过setAction()方法或在清单文件AndroidManifest.xml中设置。默认为:DEFAULT。    Data:Data通常是URI格式定义的操作数据。例如:tel:// 。通过setData()方法设置。    Category:Category属性用于指定当前动作(Action)被执行的环境。通过addCategory()方法或在清单文件AndroidManifest.xml中设置。默认为:CATEGORY_DEFAULT。    Extras:Extras属性主要用于传递目标组件所需要的额外的数据。通过putExtras()方法设置。

2 Action:action表示该activity可以执行的动作。

用法1 自定义action,匹配Activity的功能:

当intent启动Activity的时候会拿着action到menifest中查找是否有activity的acitoin和我相同,如果匹配成功(即intent中的action和中的action相同)就跳转到该actvitiy.

举例说明:
a.menifest中注册的Activity

<activity   android:name=".StudyActivity">   <intent-filter>       <action android:name="com.czh.study" />   </intent-filter></activity>

b.启动activity

Intent intent = new Intent("com.czh.study");startActivity(intent);

看到上面的例子相信大家明白了,intent中的action和中的action是一样的,因为匹配到StudyActivity,所以StudyActivity会启动起来。(如果匹配的2个activity的话,系统会给你一个选择框让你选择启动那么activity)

用法2 利用系统action,调用系统UI

Action常用的值如下:

  ACTION_MAIN:Android Application的入口,每个Android应用必须且只能包含一个此类型的Action声明。     ACTION_VIEW:系统根据不同的Data类型,通过已注册的对应Application显示数据。    ACTION_EDIT:系统根据不同的Data类型,通过已注册的对应Application编辑示数据。     ACTION_DIAL:打开系统默认的拨号程序,如果Data中设置了电话号码,则自动在拨号程序中输入此号码。     ACTION_CALL:直接呼叫Data中所带的号码。     ACTION_ANSWER:接听来电。     ACTION_SEND:由用户指定发送方式进行数据发送操作。    ACTION_SENDTO:系统根据不同的Data类型,通过已注册的对应Application进行数据发送操作。     ACTION_BOOT_COMPLETED:Android系统在启动完毕后发出带有此Action的广播(Broadcast)。     ACTION_TIME_CHANGED:Android系统的时间发生改变后发出带有此Action的广播(Broadcast)。     ACTION_PACKAGE_ADDED:Android系统安装了新的Application之后发出带有此Action的广播(Broadcast)。     ACTION_PACKAGE_CHANGED:Android系统中已存在的Application发生改变之后(如应用更新操作)发出带有此Action的广播

举例说明

1 从google搜索内容 Intent intent = new Intent(); intent.setAction(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY,"searchString") startActivity(intent); 2 浏览网页 Uri uri = Uri.parse("http://www.google.com"); Intent it  = new Intent(Intent.ACTION_VIEW,uri); startActivity(it); 3 显示地图 Uri uri = Uri.parse("geo:38.899533,-77.036476"); Intent it = new Intent(Intent.Action_VIEW,uri); startActivity(it); 4 路径规划 Uri uri = Uri.parse("http://maps.google.com/maps?f=dsaddr=startLat%20startLng&daddr=endLat%20endLng&hl=en"); Intent it = new Intent(Intent.ACTION_VIEW,URI); startActivity(it); 5 拨打电话 Uri uri = Uri.parse("tel:xxxxxx"); Intent it = new Intent(Intent.ACTION_DIAL, uri);   startActivity(it); 6 调用发短信的程序 Intent it = new Intent(Intent.ACTION_VIEW);    it.putExtra("sms_body", "The SMS text");    it.setType("vnd.android-dir/mms-sms");    startActivity(it); 7 发送短信 Uri uri = Uri.parse("smsto:0800000123");    Intent it = new Intent(Intent.ACTION_SENDTO, uri);    it.putExtra("sms_body", "The SMS text");    startActivity(it); String body="this is sms demo"; Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", number, null)); mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body); mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true); mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true); startActivity(mmsintent); 8 播放多媒体   Intent it = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse("file:///sdcard/song.mp3"); it.setDataAndType(uri, "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); 9 uninstall apk Uri uri = Uri.fromParts("package", strPackageName, null);    Intent it = new Intent(Intent.ACTION_DELETE, uri);    startActivity(it); 10 install apk Uri installUri = Uri.fromParts("package", "xxx", null); returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri); 11 打开照相机     <1>Intent i = new Intent(Intent.ACTION_CAMERA_BUTTON, null);            this.sendBroadcast(i);      <2>long dateTaken = System.currentTimeMillis();             String name = createName(dateTaken) + ".jpg";             fileName = folder + name;             ContentValues values = new ContentValues();             values.put(Images.Media.TITLE, fileName);             values.put("_data", fileName);             values.put(Images.Media.PICASA_ID, fileName);             values.put(Images.Media.DISPLAY_NAME, fileName);             values.put(Images.Media.DESCRIPTION, fileName);             values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileName);             Uri photoUri = getContentResolver().insert(                     MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);             Intent inttPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);             inttPhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);             startActivityForResult(inttPhoto, 10); 12 从gallery选取图片   Intent i = new Intent();             i.setType("image/*");             i.setAction(Intent.ACTION_GET_CONTENT);             startActivityForResult(i, 11); 13 打开录音机    Intent mi = new Intent(Media.RECORD_SOUND_ACTION);             startActivity(mi); 14 显示应用详细列表       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      刚才找app id未果,结果发现用package name也可以 Uri uri = Uri.parse("market://details?id=<packagename>"); 这个简单多了 15 寻找应用       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       16 打开联系人列表             <1>                       Intent i = new Intent();            i.setAction(Intent.ACTION_GET_CONTENT);            i.setType("vnd.android.cursor.item/phone");            startActivityForResult(i, REQUEST_TEXT);             <2>             Uri uri = Uri.parse("content://contacts/people");             Intent it = new Intent(Intent.ACTION_PICK, uri);             startActivityForResult(it, REQUEST_TEXT); 17 打开另一程序 Intent i = new Intent();             ComponentName cn = new ComponentName("com.yellowbook.android2",                     "com.yellowbook.android2.AndroidSearch");             i.setComponent(cn);             i.setAction("android.intent.action.MAIN");             startActivityForResult(i, RESULT_OK); 28 调用系统编辑添加联系人(高版本SDK有效):Intent it = newIntent(Intent.ACTION_INSERT_OR_EDIT);               it.setType("vnd.android.cursor.item/contact");                //it.setType(Contacts.CONTENT_ITEM_TYPE);                it.putExtra("name","myName");               it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY,  "organization");               it.putExtra(android.provider.Contacts.Intents.Insert.EMAIL,"email");                it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone");                it.putExtra(android.provider.Contacts.Intents.Insert.SECONDARY_PHONE,                               "mobilePhone");                it.putExtra(  android.provider.Contacts.Intents.Insert.TERTIARY_PHONE,                               "workPhone");               it.putExtra(android.provider.Contacts.Intents.Insert.JOB_TITLE,"title");                startActivity(it);19 调用系统编辑添加联系人(全有效):Intent intent = newIntent(Intent.ACTION_INSERT_OR_EDIT);           intent.setType(People.CONTENT_ITEM_TYPE);           intent.putExtra(Contacts.Intents.Insert.NAME, "My Name");           intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890");           intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE,Contacts.PhonesColumns.TYPE_MOBILE);           intent.putExtra(Contacts.Intents.Insert.EMAIL, "com@com.com");           intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE,                    Contacts.ContactMethodsColumns.TYPE_WORK);           startActivity(intent);

系统给我们提供了非常多的action,这里只是拿出几个举例,大家可以尝试一下。

3 category

Category属性用于指定当前动作(Action)被执行的环境。category和action用法差不多,也是分2种:

用法1 自定义category ,匹配Activity的功能:

如果2个activity有相同的action,那么我们可以用不同的category来区分。
举例说明:
a.menifest中注册的Activity

    <activity  android:name=".StudyActivity">       <intent-filter>          <action android:name="com.czh.study" />          <category android:name="com.czh.category.study" />          <category android:name="android.intent.category.DEFAULT" />       </intent-filter>   </activity>

b.启动activity

Intent intent = new Intent("com.czh.study");intent.addCategory("com.czh.category.study")startActivity(intent);

解释:

1.这里的category起到了匹配的作用,系统先匹配action,如果action,再匹配cagegory,如果有相同就跳转。2.有一点大家需要注意:<category android:name="android.intent.category.DEFAULT" />隐式启动中你必须要加上这一条。但是也有例外:<intent-filter>  <action android:name="android.intent.action.MAIN" />      <category android:name="android.intent.category.LAUNCHER" />  </intent-filter>这一个就不需要要。  

用法2 利用系统category

cagegory常用的值如下:

 CATEGORY_DEFAULT:Android系统中默认的执行方式,按照普通Activity的执行方式执行。  CATEGORY_BROWSABLE:设置该组件可以使用浏览器启动。 CATEGORY_TAB:指定该Activity作为TabActivity的Tab页  CATEGORY_LAUNCHER:设置该组件为在当前应用程序启动器中优先级最高的Activity,通常为入口ACTION_MAIN配合使用。  CATEGORY_HOME:设置该组件为Home Activity。 CATEGORY_PREFERENCE:设置该组件为Preference。  CATEGORY_GADGET:设置该组件可以内嵌到另外的Activity中。 CATEGORY_TEST:该Activity是一个测试 CATEGORY_CAR_MODE:设置该Activity可在车载环境下使用   CATEGORY_CAR_DOCK:指定手机被插入汽车底座(硬件)时运行该Activity CATEGORY_DESK_DOCK:指定手机被插入桌面底座(硬件)时运行该Activity

4 extras

extras属性主要用于传递目标组件所需要的额外的数据。通过putExtras()方法设置。
常用的系统extras

EXTRA_BCC:存放邮件密送人地址的字符串数组。EXTRA_CC:存放邮件抄送人地址的字符串数组。EXTRA_EMAIL:存放邮件地址的字符串数组。EXTRA_SUBJECT:存放邮件主题字符串。EXTRA_TEXT:存放邮件内容。EXTRA_KEY_EVENT:以KeyEvent对象方式存放触发Intent的按键。EXTRA_PHONE_NUMBER:存放调用ACTION_CALL时的电话号码。

举例说明:

Intent intent  = new Intent("com.czh.study");                intent.putExtra("key", "value");                startActivity(intent);String value = getIntent().getStringExtra("key");

5 data

什么是uri:

我们先得弄明白uri是什么,才能向下讲。
通用资源标志符(Universal Resource Identifier, 简称”URI”)。
Uri代表要操作的数据,Android上可用的每种资源 - 图像、视频片段等都可以用Uri来表示。换句话说:android系统中任何可用的资源(图像、视频、文件)都可以用uri表示。

uri讲解:

1.uri属性有以下4部分组成:android:scheme、android:host、android:port、android:path其中host和port2个统称为authority。2.要使authority(host和port)有意义,必须指定scheme;要使path有意义,必须使scheme和authority(host和port)有意义

举例说明:
URI为: file://com.android.jony.test:520/mnt/sdcard,我们拆分如下:
scheme–>file:
host–>com.android.jony.test
port–>520
path–>mnt/sdcard
authority–>com.android.jony.test:520

图片uri: content://media/external/images/media/62026

tel://:号码数据格式,后跟电话号码。 mailto://:邮件数据格式,后跟邮件收件人地址。smsto://:短息数据格式,后跟短信接收号码。content://:内容数据格式,后跟需要读取的内容。 file://:文件数据格式,后跟文件路径。market://search?q=pname:pkgname:市场数据格式,在Google Market里搜索包名为pkgname的应用。geo://latitude,longitude:经纬数据格式,在地图上显示经纬度指定的位置。

在intent-filter中指定data属性的实际目的是:要求接收的Intent中的data必须符合intent-filter中指定的data属性,这样达到反向限定Intent的作用。
举例说明:
在AndroidManifest.xml 中进行如下设置:

<activity android:name=".TestActivity">      <intent-filter>           <action android:name="com.jony.test"/>           <data android:scheme="file"/>      </intent-filter>  </activity>  

启动该Activity的Intent必须进行如下设置:

Intent intent = new Intent();  Uri uri = Uri.parse("file://com.android.test:520/mnt/sdcard");  intent.setData(uri);

data讲解:

1.data属性有以下5部分组成:android:scheme、android:host、android:port、android:path、android:mimeTypedata的前四个属性构成了URI的组成部分,mimeType设置了数据的类型2.data元素组成的URI模型如下:scheme://host:port/path

URI和intent-filter匹配:

Intent中URI和intent-filter进行比较的时候只会进行部分的比较:
(1)当intent-filter中只设置了scheme,只会比较URI的scheme部分;
(2)当intent-filter中只设置了scheme和authority,那么只会匹配URI中的scheme和authority;
(3)当intent-filter中设置了scheme、authority和path,那么只会匹配URI中的scheme、authority、path;(path可以使用通配符进行匹配)
(4)当intent-filter中设置了mimeType,还会进行数据类型的匹配。

uri应用举例

所有联系人的Uri: content://contacts/people某个联系人的Uri: content://contacts/people/5所有图片Uri: content://media/external某个图片的Uri:content://media/external/images/media/41.显示网页:Uri uri = Uri.parse("http://www.google.com");Intent it = new Intent(Intent.ACTION_VIEW,uri);startActivity(it);2.显示地图:Uri uri = Uri.parse("geo:38.899533,-77.036476");Intent it = new Intent(Intent.Action_VIEW,uri);startActivity(it);3.路径规划: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);4.拨打电话:调用拨号程序Uri uri = Uri.parse("tel:xxxxxx");Intent it = new Intent(Intent.ACTION_DIAL, uri);   startActivity(it);   Uri uri = Uri.parse("tel.xxxxxx");Intent it =new Intent(Intent.ACTION_CALL,uri);要使用这个必须在配置文件中加入<uses-permission id="Android.permission.CALL_PHONE" />5.发送SMS/MMS调用发送短信的程序Intent it = new Intent(Intent.ACTION_VIEW);it.putExtra("sms_body", "The SMS text");it.setType("vnd.android-dir/mms-sms");startActivity(it);   6.发送短信Uri uri = Uri.parse("smsto:0800000123");Intent it = new Intent(Intent.ACTION_SENDTO, uri);it.putExtra("sms_body", "The SMS text");startActivity(it);   7.发送彩信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);8.发送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"));9.添加附件  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"));10.播放多媒体     Intent it = new Intent(Intent.ACTION_VIEW);  Uri uri = Uri.parse("file:///sdcard/song.mp3");  it.setDataAndType(uri, "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);   11.Uninstall 程序  Uri uri = Uri.fromParts("package", strPackageName, null);  Intent it = new Intent(Intent.ACTION_DELETE, uri);  startActivity(it);12.调用相册public static final String MIME_TYPE_IMAGE_JPEG = "image/*";public static final int ACTIVITY_GET_IMAGE = 0;Intent getImage = new Intent(Intent.ACTION_GET_CONTENT); getImage.addCategory(Intent.CATEGORY_OPENABLE); getImage.setType(MIME_TYPE_IMAGE_JPEG);startActivityForResult(getImage, ACTIVITY_GET_IMAGE);13.调用系统相机应用程序,并存储拍下来的照片Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); time = Calendar.getInstance().getTimeInMillis();intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/tucue", time + ".jpg")));startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE);14.uninstall apk/**未测试Uri uninstallUri = Uri.fromParts("package", "xxx", null);returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);*/Uri packageURI = Uri.parse("package:"+wistatmap);   Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);   startActivity(uninstallIntent);15.install apkUri installUri = Uri.fromParts("package", "xxx", null);returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);play audioUri playUri = Uri.parse("file:///sdcard/download/everything.mp3");returnIt = new Intent(Intent.ACTION_VIEW, playUri);16.发送附件Intent it = new Intent(Intent.ACTION_SEND);   it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");   it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3");   sendIntent.setType("audio/mp3");   startActivity(Intent.createChooser(it, "Choose Email Client"));17.搜索应用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 application18.进入联系人页面Intent intent = new Intent();intent.setAction(Intent.ACTION_VIEW);intent.setData(People.CONTENT_URI);startActivity(intent);19.查看指定联系人Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, info.id);//info.id联系人IDIntent intent = new Intent();intent.setAction(Intent.ACTION_VIEW);intent.setData(personUri);startActivity(intent);

6 结尾

好了就讲到这里吧,希望对大家有所帮助

0 0
原创粉丝点击