Intent组件

来源:互联网 发布:自由网络联盟翻墙软件 编辑:程序博客网 时间:2024/06/10 07:53

Intent是Android中的重要组件,可以被认为是不同组件之间通信的“媒介”或者“信使”。使用它可以启动Activity,Service还可以发起一个广播(Broadcast)。Intent对象由Action、Data、Category、Component和Extra组成。下面就以上属性进行分析说明。


1. Component

  在使用Intent显式的启动目标组件时,需要指定组件的名称(ComponentName)。Intent的组件名称对象由ComponentName类来封装。代码如下:

 

  1. // 实例化组件名称  
  2.             ComponentName cn = new ComponentName(MainActivity.this, "com.amaker.ch06.app1.MyActivity");  
  3.             // 实例化Intent  
  4.             Intent intent = new Intent();  
  5.             // 为Intent设置组件名称属性  
  6.             intent.setComponent(cn);  
  7.             // 启动Activity  
  8.             startActivity(intent); 


  同时,在目标组件中,可以获得传过来的Intent的属性。如下:


  1. // 获得Intent  
  2. Intent intent = this.getIntent();  
  3. // 获得组件名称对象  
  4. ComponentName cn = intent.getComponent();  
  5. // 获得包名称  
  6. String packageName = cn.getPackageName();  
  7. // 获得类名称  
  8. String className = cn.getClassName();  
  9. // 实例化TextView  
  10. tv = (TextView)findViewById(R.id.TextView01);  
  11. // 显示  
  12. tv.setText("组件包名称:"+packageName+"\n"+"组件类名称:"+className);  
  除了使用setComponent() 之外,还可以使用setClass(),setClassName()来显式指定目标组件。

2. Action

  Action规定了Intent要完成的动作,是一个字符串常量。使用setAction()来设置Action属性,使用getAction()来获得Action属性。既可以使用系统内置的Action,也可以自己定义。
  自定义Action:

 

  1. public static final String MY_ACTION="com.amaker.ch07.app.MY_ACTION";  
  2. ......  
  3. Intent intent = new Intent();  
  4. // 为Intent设置Action属性  
  5. intent.setAction(MY_ACTION);  
  6. // 启动Activity  
  7. startActivity(intent);  
  对于使用自定义的Action的隐式发送组件的过程中,需要在目标组件的AndroidManifest.xml中声明过滤器规则,将Action加入其中。如下:

 

  1. <intent-filter> 
  2. <action android:name="com.amaker.ch06.app.MY_ACTION" /> 
  3. <category android:name="android.intent.category.DEFAULT" /> 
  4. </intent-filter> 
  访问系统的Action方法同上,区别在于无需自定义Action字符串,直接使用系统内部的就可以,此处不再赘述。

3. Intent的Data和Type属性

  不同的动作伴随着不同种类的数据规格。setData()方法指定数据只能为一个URI,setType()指定它只能是一个MIME类型, 而setDataAndType()指定它同时为URI和MIME类型。URI通过getData()读取,类型则通过getType()。
  当匹配一个意图到一个能处理数据的组件时,除了它的URI外,通常需要知道数据类型(它的MIME类型)。 比如,一个能显示图片的组件不应该被要求去播放一个声音文件。如下:

 

  1. <data android:type="video/mpeg" android:scheme="http" . . . />  
  2.      <data android:type="audio/mpeg" android:scheme="http" . . . />  
  下面代码是开启打电话界面的程序片段:

 

  1. data="content://contacts/people/1";  
  2. uri=Uri.parse(data);  
  3. intent=new Intent();  
  4. intent.setData(uri);  
  5. intent.setAction(Intent.ACTION_VIEW);  
  6. startActivity(intent);  

  下面的代码是Type类型的数据的访问:

 

 

  1. Intent intent=new Intent();  
  2.                     intent.setType("vnd.android.cursor.item/phone");  
  3.                     intent.setAction(Intent.ACTION_GET_CONTENT);  
  4.                     startActivity(intent);  
  5.                     break;   

 

4. Category

  该属性是一个执行Action的附件信息。可以看作是设置一些特性的设置。
 

常量

含义

CATEGORY_BROWSABLE 

目标活动可以被浏览器安全的唤起来显示被一个链接所引用的数据-比如,一张图片或一条e-mail消息。

CATEGORY_GADGET 

这个活动可以被嵌入到充当配件宿主的另外的活动里面。

CATEGORY_HOME 

这个活动将显示桌面,也就是用户开机后看到的第一个屏幕或者按HOME键时看到的屏幕。

CATEGORY_LAUNCHER 

这个活动可以是一个任务的初始活动并被列在应用程序启动器的顶层。

CATEGORY_PREFERENCE 

目标活动是一个选择面板。

 

5. Extra属性

  该属性是添加一些组件的附加信息。代码如下:

 

  1. Uri uri = Uri.parse("smsto://10086");   
  2. Intent intent = new Intent(Intent.ACTION_SENDTO, uri);   
  3. intent.putExtra("sms_body", "测试短信");   
  4. startActivity(Intent.createChooser(intent, "发送短信"));  
  以上程序片是发送短信的页面出现,在其中的联系人和文本信息框中出现的是10086和“测试短信”。另外,使用Extra属性也可以向自定的其他组件发送数据。在目标组件中可以接收。代码如下:

 

  1. Intent intent=getIntent();  
  2. int user=intent.getIntExtra("userId",0);   

6. Intent Filter

  在不指定目标组件名称的时候,需要使用隐式寻找目标组件的方法。,这就需要通过Intent Filter来实现。目标Intent在AndroidManifest.xml中的Intent Filter标签中指定Action,Data和Category。然后源Activity通过查找已经注册在AndroidManifest.xml中的所有Intent,最终找到匹配的Intent。声明方法如下:

 

  1. <activity android:name="TestActivity" > 
  2. <intent-filter> 
  3. <action android:name="com.amaker.ch06.app.TEST_ACTION1"/> 
  4. <action android:name="com.amaker.ch06.app.TEST_ACTION2"/> 
  5. <action android:name="com.amaker.ch06.app.TEST_ACTION3"/> 
  6.  
  7. <action android:name="android.intent.action.VIEW"/> 
  8.  
  9. //Type和data属性都在这个标签中设置。URI被拆分成两个部分,scheme和path。
  10. <data android:scheme="content" android:path="com.amaker.ch07.app/abc"/> 
  11. <data android:scheme="http" android:path="www.google.com" /> 
  12.  //这行必须添加
  13. <category android:name="android.intent.category.DEFAULT"/> 
  14. <category android:name="android.intent.category.BROWSABLE" /> 
  15. <category android:name="com.amaker.ch07.app.CATEGORY1"/> 
  16.  
  17. </intent-filter> 
  18. </activity> 
  19.  
 

 在过滤器中,如下几点需要注意:
  a. 如果Intent指定了Action,则目标组件中的过滤器Action列表中必须包含这个Action,否则不能匹配。如果Intent没有指定,则自动通过。
  b. android.intent.category.DEFAULT属性是启动Activity默认的属性,这个必须添加。
  c. 如果有多个Intent过滤规则相同,那么会自动提示使用哪个。
  d. 如果一个组件没有任何的意图过滤器,那它只能接收显式意图。一个带过滤器的组件可以同时接收显式和隐式意图。


1 intent中调用电话本
  1.   Intent intent = new Intent();
  2.         // 设置Intent Action属性
  3.         intent.setAction(Intent.ACTION_GET_CONTENT);
  4.         // 设置Intent Type 属性
  5.         intent.setType("vnd.android.cursor.item/phone");
  6.         // 启动Activity
  7.         startActivity(intent);
复制代码
2 Intent回到home界面
  1. // 实例化Intent
  2. Intent i = new Intent();
  3. // 添加Action属性
  4. i.setAction(Intent.ACTION_MAIN);
  5. // 添加Category属性
  6. i.addCategory(Intent.CATEGORY_HOME);
  7. // 启动Activity
  8. startActivity(i);
复制代码

3 常见的intent的解析
    1) 查看_id 为1的用户电话信息
  1. data = "content://contacts/people/1";
  2. uri = Uri.parse(data);
  3. intent.setAction(Intent.ACTION_VIEW);
  4. intent.setData(uri);
  5. startActivity(intent);
复制代码

2) 编辑_id 为1的用户电话信息
  1. data = "content://contacts/people/1";
  2. uri = Uri.parse(data);
  3. intent.setAction(Intent.ACTION_EDIT);
  4. intent.setData(uri);
  5. startActivity(intent);
复制代码

  3) 显示拨打电话界面
  1. data = "tel:13800138000";
  2. uri = Uri.parse(data);
  3. intent.setAction(Intent.ACTION_DIAL);
  4. intent.setData(uri);
  5. startActivity(intent);
复制代码

4) 直接打电话
  1. data = "tel:13800138000";
  2. uri = Uri.parse(data);
  3. intent.setAction(Intent.ACTION_CALL);
  4. intent.setData(uri);
复制代码

  5) 访问浏览器
  1. data = "http://www.google.com";
  2. uri = Uri.parse(data);
  3. intent.setAction(Intent.ACTION_VIEW);
  4. intent.setData(uri);
复制代码

6)  访问地图
  1. data = "geo:39.92,116.46";
  2. uri = Uri.parse(data);
  3. intent = new Intent(Intent.ACTION_VIEW,uri);
  4. startActivity(intent);
复制代码

4 preference
    例子保存临时短信
     比如在oncreate中:
        
  1. SharedPreferences pre = getSharedPreferences(TEMP_SMS, MODE_WORLD_READABLE);
  2.         String content = pre.getString("sms_content", "");
  3.         myEditText.setText(content);
复制代码


    onstop比如接电话时:
   
  1. super.onStop();
  2.     SharedPreferences.Editor editor = getSharedPreferences(TEMP_SMS, MODE_WORLD_WRITEABLE).edit();
  3.     editor.putString("sms_content", myEditText.getText().toString());
  4.     editor.commit();
复制代码

  实际上是保存在/data/data/package/shared_prefs/下的XML文件

5 bitmap读网上一个URL的地址,然后
   
  1. String urlStr = "http://xxxxx/zs.jpg";
  2.       try {
  3. URL url = new URL(urlStr);
  4. // 1. 直接使用URL获得输入流
  5. //InputStream in = url.openStream();

  6. // 2. 获得URLconnection
  7. URLConnection conn = url.openConnection();
  8. InputStream in = conn.getInputStream();

  9. // 3. 如果是HTTP协议可以使用HttpURLConnection
  10. //HttpURLConnection httpConn = (HttpsURLConnection)conn;
  11. //in = httpConn.getInputStream();

  12. Bitmap bm = BitmapFactory.decodeStream(in);

  13. imageView.setImageBitmap(bm);

  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
复制代码

6 android中HTTP URL方式访问服务端的工具类及使用
   
   
  1. public class HttpUtil {
  2. // 基础URL
  3. public static final String BASE_URL="http://10.0.2.2:8085/test/";
  4. // 获得Get请求对象request
  5. public static HttpGet getHttpGet(String url){
  6. HttpGet request = new HttpGet(url);
  7. return request;
  8. }
  9. // 获得Post请求对象request
  10. public static HttpPost getHttpPost(String url){
  11. HttpPost request = new HttpPost(url);
  12. return request;
  13. }
  14. // 根据请求获得响应对象response
  15. public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException,

  16. IOException{
  17. HttpResponse response = new DefaultHttpClient().execute(request);
  18. return response;
  19. }
  20. // 根据请求获得响应对象response
  21. public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException,

  22. IOException{
  23. HttpResponse response = new DefaultHttpClient().execute(request);
  24. return response;
  25. }

  26. // 发送Post请求,获得响应查询结果
  27. public static String queryStringForPost(String url){
  28. // 根据url获得HttpPost对象
  29. HttpPost request = HttpUtil.getHttpPost(url);
  30. String result = null;
  31. try {
  32. // 获得响应对象
  33. HttpResponse response = HttpUtil.getHttpResponse(request);
  34. // 判断是否请求成功
  35. if(response.getStatusLine().getStatusCode()==200){
  36. // 获得响应
  37. result = EntityUtils.toString(response.getEntity());
  38. return result;
  39. }
  40. } catch (ClientProtocolException e) {
  41. e.printStackTrace();
  42. result = "网络异常!";
  43. return result;
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. result = "网络异常!";
  47. return result;
  48. }
  49.         return null;
  50.     }
  51. // 获得响应查询结果
  52. public static String queryStringForPost(HttpPost request){
  53. String result = null;
  54. try {
  55. // 获得响应对象
  56. HttpResponse response = HttpUtil.getHttpResponse(request);
  57. // 判断是否请求成功
  58. if(response.getStatusLine().getStatusCode()==200){
  59. // 获得响应
  60. result = EntityUtils.toString(response.getEntity());
  61. return result;
  62. }
  63. } catch (ClientProtocolException e) {
  64. e.printStackTrace();
  65. result = "网络异常!";
  66. return result;
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. result = "网络异常!";
  70. return result;
  71. }
  72.         return null;
  73.     }
  74. // 发送Get请求,获得响应查询结果
  75. public static  String queryStringForGet(String url){
  76. // 获得HttpGet对象
  77. HttpGet request = HttpUtil.getHttpGet(url);
  78. String result = null;
  79. try {
  80. // 获得响应对象
  81. HttpResponse response = HttpUtil.getHttpResponse(request);
  82. // 判断是否请求成功
  83. if(response.getStatusLine().getStatusCode()==200){
  84. // 获得响应
  85. result = EntityUtils.toString(response.getEntity());
  86. return result;
  87. }
  88. } catch (ClientProtocolException e) {
  89. e.printStackTrace();
  90. result = "网络异常!";
  91. return result;
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. result = "网络异常!";
  95. return result;
  96. }
  97.         return null;
  98.     }

  99.    使用:String username = userEditText.getText().toString();
  100. // 获得密码
  101. String pwd = pwdEditText.getText().toString();
  102. // 获得登录结果
  103. String result=query(username,pwd);


  104. // 根据用户名称密码查询
  105. private String query(String account,String password){
  106. // 查询参数
  107. String queryString = "account="+account+"&password="+password;
  108. // url
  109. String url = HttpUtil.BASE_URL+"servlet/LoginServlet?"+queryString;
  110. // 查询返回结果
  111. return HttpUtil.queryStringForPost(url);
  112.             
  113.     将参数提交给服务端:使用apache http client:
  114.      List<NameValuePair> params = new ArrayList<NameValuePair>();
  115. // 添加请求参数
  116. params.add(new BasicNameValuePair("orderTime", orderTime));
  117. params.add(new BasicNameValuePair("userId", userId));
  118. params.add(new BasicNameValuePair("tableId", tableId));
  119. params.add(new BasicNameValuePair("personNum", personNum));
  120. UrlEncodedFormEntity entity1=null;
  121. try {
  122. entity1 =  new UrlEncodedFormEntity(params,HTTP.UTF_8);
  123. } catch (UnsupportedEncodingException e) {
  124. e.printStackTrace();
  125. }
  126. // 请求服务器url
  127. String url = HttpUtil.BASE_URL+"servlet/StartTableServlet";
  128. // 获得请求对象HttpPost
  129. HttpPost request = HttpUtil.getHttpPost(url);
  130. // 设置查询参数
  131. request.setEntity(entity1);
  132. // 获得响应结果
  133. String result= HttpUtil.queryStringForPost(request);
复制代码

1 Intent.ACTION_MAIN

String: android.intent.action.MAIN

标识Activity为一个程序的开始。比较常用。

例如:

1 <activity android:name=".Main" android:label="@string/app_name">
2     <intent-filter>
3         <action android:name="android.intent.action.MAIN" />
4         <category android:name="android.intent.category.LAUNCHER" />
5     </intent-filter>
6 </activity>

2 Intent.Action_CALL

Stirng: android.intent.action.CALL

呼叫指定的电话号码。

Input:电话号码。数据格式为:tel:+phone number 

Intent intent=new Intent();
intent.setAction(Intent.ACTION_CALL);   
intent.setData(Uri.parse(
"tel:1320010001");
startActivity(intent);


3 Intent.Action.DIAL

String: action.intent.action.DIAL

调用拨号面板

Intent intent=new Intent();
intent.setAction(Intent.ACTION_DIAL);   //android.intent.action.DIAL
intent.setData(Uri.parse("tel:1320010001");
startActivity(intent);

Input:电话号码。数据格式为:tel:+phone number 

Output:Nothing

说明:打开Android的拨号UI。如果没有设置数据,则打开一个空的UI,如果设置数据,action.DIAL则通过调用getData()获取电话号码。

但设置电话号码的数据格式为 tel:+phone number.

 

4.Intent.Action.ALL_APPS

String: andriod.intent.action.ALL_APPS

列出所有的应用。

Input:Nothing.

Output:Nothing.

 

5.Intent.ACTION_ANSWER

Stirng:android.intent.action.ANSWER

处理呼入的电话。

Input:Nothing.

Output:Nothing.

 

6 Intent.ACTION_ATTACH_DATA

String: android.action.ATTCH_DATA

别用于指定一些数据应该附属于一些其他的地方,例如,图片数据应该附属于联系人

Input: Data

Output:nothing

 

7 Intent.ACTION_BUG_REPORT

String: android.intent.action.BUG_REPORT

显示Dug报告。

Input:nothing

output:nothing

 

8 Intent.Action_CALL_BUTTON

String: android.action.intent.CALL_BUTTON.

相当于用户按下“拨号”键。经测试显示的是“通话记录”

Input:nothing

Output:nothing

Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
startActivity(intent);

 

 

9 Intent.ACTION_CHOOSER

String: android.intent.action.CHOOSER

 显示一个activity选择器,允许用户在进程之前选择他们想要的,与之对应的是Intent.ACTION_GET_CONTENT.


10. Intent.ACTION_GET_CONTENT

String: android.intent.action.GET_CONTENT

允许用户选择特殊种类的数据,并返回(特殊种类的数据:照一张相片或录一段音)

Input: Type

Output:URI

这个以前用到过,看事例。

选择一个图片:

代码:

int requestCode = 1001;
Intent intent 
= new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
intent.setType("image/*"); // 查看类型,如果是其他类型,比如视频则替换成 video/*,或 */*
Intent wrapperIntent = Intent.createChooser(intent, null);
startActivityForResult(wrapperIntent, requestCode);

可通过重写onActivityResult方法来获取选择的数据内容。