Intent详解

    
 
2015/04/20            Intent的深入学习
  
 什么是Intent?
Intent顾名思义是意图,在开发当中个个组件或功能的纽带,Intent的中文意思是目的。在Android中也是“目的”的意思。就是我们要去哪里,从这个activity要前往另一个Activity就需要用到Intent。

示例代码一:

   1: //定义一个Intent
   2: Intent intent = new Intent(IntentDemo.this, AnotherActivity2.class);
   3: //启动Activity
   4: startActivity(intent);

以上示例代码的作用是从IntentDemo这个activity切换到AnotherActivity2。这是Intent其中一种构造方法,指定两个Activity。为什么需要指定两个活动呢?因为在Android中有一个活动栈,这样的构造方式才能确保正确的将前一个活动压入栈中,才能在触发返回键的时候活动能够正确出栈。

注意:所有的Activity都必须先在AndroidManifest.xml里面配置声明。一下为本文用到的程序配置文件

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   3:     package="com.halzhang.android.intent" android:versionCode="1"
   4:     android:versionName="1.0">
   5:     <application android:icon="@drawable/icon" android:label="@string/app_name">
   6:         <activity android:name=".IntentDemo" android:label="@string/app_name">
   7:             <intent-filter>
   8:                 <action android:name="android.intent.action.MAIN" />
   9:                 <category android:name="android.intent.category.LAUNCHER" />
  10:             </intent-filter>
  11:         </activity>
  12:         <activity android:name=".AnotherActivity" android:label="another">
  13:             <intent-filter>
  14:                 <action android:name="android.intent.action.EDIT" />
  15:                 <!-- category一定要配置,否则报错:找不到Activity -->
  16:                 <category android:name="android.intent.category.DEFAULT" />
  17:             </intent-filter>
  18:         </activity>
  19:  
  20:         <activity android:name=".AnotherActivity2" android:label="another2">
  21:             <intent-filter>
  22:                 <action android:name="android.intent.action.EDIT" />
  23:                 <category android:name="android.intent.category.DEFAULT" />
  24:             </intent-filter>
  25:         </activity>
  26:     </application>
  27:     <uses-sdk android:minSdkVersion="3" />
  28:     <!-- 
  29:         上面配置的两个activity具有相同的action类型,都为“android.intent.action.EDIT”
  30:         当Intent的action属性为Intent.ACTION_EDIT时,系统不知道转向哪个Activity时,
  31:         就会弹出一个Dialog列出所有action为“android.intent.action.EDIT”的
  32:         Activity供用户选择
  33:      -->
  34: </manifest> 

二、Intent的构造函数

公共构造函数:

1、Intent() 空构造函数

2、Intent(Intent o) 拷贝构造函数

3、Intent(String action) 指定action类型的构造函数

4、Intent(String action, Uri uri) 指定Action类型和Uri的构造函数,URI主要是结合程序之间的数据共享ContentProvider

5、Intent(Context packageContext, Class<?> cls) 传入组件的构造函数,也就是上文提到的

6、Intent(String action, Uri uri, Context packageContext, Class<?> cls) 前两种结合体

Intent有六种构造函数,3、4、5是最常用的,并不是其他没用!

Intent(String action, Uri uri)  的action就是对应在AndroidMainfest.xml中的action节点的name属性值。在Intent类中定义了很多的Action和Category常量。

示例代码二:

   1: Intent intent = new Intent(Intent.ACTION_EDIT, null);
   2: startActivity(intent);

示例代码二是用了第四种构造函数,只是uri参数为null。执行此代码的时候,系统就会在程序主配置文件AndroidMainfest.xml中寻找

<action android:name="android.intent.action.EDIT" />对应的Activity,如果对应为多个activity具有<action android:name="android.intent.action.EDIT" />此时就会弹出一个dailog选择Activity,如下图:

device 如果是用示例代码一那种方式进行发送则不会有这种情况。

三、利用Intent在Activity之间传递数据

在Main中执行如下代码:

   1: Bundle bundle = new Bundle();
   2: bundle.putStringArray("NAMEARR", nameArr);
   3: Intent intent = new Intent(Main.this, CountList.class);
   4: intent.putExtras(bundle);
   5: startActivity(intent);

在CountList中,代码如下:

   1: Bundle bundle = this.getIntent().getExtras();
   2: String[] arrName = bundle.getStringArray("NAMEARR");

以上代码就实现了Activity之间的数据传递!

Intent的跳转方式:     

        解Intent的关键之一是理解清楚Intent的两种基本用法:一种是显式的Intent,即在构造Intent对象时就指定接收者;另一种是隐式的Intent,即Intent的发送者在构造Intent对象时,并不知道也不关心接收者是谁,有利于降低发送者和接收者之间的耦合。

        对于显式Intent,Android不需要去做解析,因为目标组件已经很明确,Android需要解析的是那些隐式Intent,通过解析,将 Intent映射给可以处理此Intent的Activity、IntentReceiver或Service。  

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/*" />

完整的实例

<activityandroid:name="NotesList"android:label="@string/title_notes_list">
            <intent-filter>
                <actionandroid:name="android.intent.action.MAIN"/>
                <categoryandroid:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <actionandroid:name="android.intent.action.VIEW"/>
                <actionandroid:name="android.intent.action.EDIT"/>
                <actionandroid:name="android.intent.action.PICK"/>
                <categoryandroid:name="android.intent.category.DEFAULT"/>
                <dataandroid:mimeType="vnd.android.cursor.dir/vnd.google.note"/>
            </intent-filter>
            <intent-filter>
                <actionandroid:name="android.intent.action.GET_CONTENT"/>
                <categoryandroid:name="android.intent.category.DEFAULT"/>
                <dataandroid:mimeType="vnd.android.cursor.item/vnd.google.note"/>
            </intent-filter>
        </activity>
 
一个应用程序可以有多个Activity,每个Activity是同级别的,那么在启动程序时,最先启动哪个Activity呢?有些程序可能需要显示在程序列表里,有些不需要。怎么定义呢?android.intent.action.MAIN决定应用程序最先启动的Activity ,android.intent.category.LAUNCHER决定应用程序是否显示在程序列表里。Main和LAUNCHER同时设定才有意义,
 

如果有多个同级的Activity都有过滤器

<intent-filter>

 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

则只有最前面的Activity的 <action android:name="android.intent.action.MAIN" /> 有效,启动该程序时,执行的是该Activity。且在程序列表中有多个图标,这些Activity都在程序列表中显示,该Application有多个入口,执行不同的Activity,但是整个程序的主入口(整个程序最先运行的那个activity)只有最先定义的那个Activity。

 
如 果一个应用没有LAUNCHER则该apk仍能安装到设备上,但是在主程序图中看不到。如果给那个Activity 设定了LAUNCHER,且同时设定了Main,则这个Activity就可出现在程序图中;如果没有Main,则不知启动哪个Activity,故也不会有图标出现。

转 http://hi.baidu.com/designhouse/blog/item/ae5638dbe4873179d1164e52.html

      

例2:Activity

Android中,Activity是所有程序的根本,所有程序的流程都运行在Activity之中,Activity具有自己的生命周期(见http://www.cnblogs.com/feisky/archive/2010/01/01/1637427.html,由系统控制生命周期,程序无法改变,但可以用onSaveInstanceState保存其状态)。

对于Activity,关键是其生命周期的把握(如下图),其次就是状态的保存和恢复(onSaveInstanceState onRestoreInstanceState),以及Activity之间的跳转和数据传输(intent)。

activity_lifecycle

Activity中常用的函数有SetContentView()   findViewById()    finish()   startActivity(),其生命周期涉及的函数有:

void onCreate(Bundle savedInstanceState)
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()

注意的是,Activity的使用需要在Manifest文件中添加相应的<Activity>,并设置其属性和intent-filter。

Intent

Android中提供了Intent机制来协助应用间的交互与通讯,Intent负责对应用中一次操作的动作、动作涉及数据、附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组件,将 Intent传递给调用的组件,并完成组件的调用。Intent不仅可用于应用程序之间,也可用于应用程序内部的Activity/Service之间的交互。因此,Intent在这里起着一个媒体中介的作用,专门提供组件互相调用的相关信息,实现调用者与被调用者之间的解耦。在SDK中给出了Intent作用的表现形式为:

Intent属性的设置,包括以下几点:(以下为XML中定义,当然也可以通过Intent类的方法来获取和设置)

(1)Action,也就是要执行的动作

SDk中定义了一些标准的动作,包括

onstantTarget componentAction
ACTION_CALL activity Initiate a phone call.
ACTION_EDIT activity Display data for the user to edit.
ACTION_MAIN activity Start up as the initial activity of a task, with no data input and no returned output.
ACTION_SYNC activity Synchronize data on a server with data on the mobile device.
ACTION_BATTERY_LOW broadcast receiver A warning that the battery is low.
ACTION_HEADSET_PLUG broadcast receiver A headset has been plugged into the device, or unplugged from it.
ACTION_SCREEN_ON broadcast receiver The screen has been turned on.
ACTION_TIMEZONE_CHANGED broadcast receiver The setting for the time zone has changed.

 

当然,也可以自定义动作(自定义的动作在使用时,需要加上包名作为前缀,如"com.example.project.SHOW_COLOR”),并可定义相应的Activity来处理我们的自定义动作。

(2)Data,也就是执行动作要操作的数据

Android中采用指向数据的一个URI来表示,如在联系人应用中,一个指向某联系人的URI可能为:content://contacts/1。对于不同的动作,其URI数据的类型是不同的(可以设置type属性指定特定类型数据),如ACTION_EDIT指定Data为文件URI,打电话为tel:URI,访问网络为http:URI,而由content provider提供的数据则为content: URIs。

(3)type(数据类型),显式指定Intent的数据类型(MIME)。一般Intent的数据类型能够根据数据本身进行判定,但是通过设置这个属性,可以强制采用显式指定的类型而不再进行推导。

(4)category(类别),被执行动作的附加信息。例如 LAUNCHER_CATEGORY 表示Intent 的接受者应该在Launcher中作为顶级应用出现;而ALTERNATIVE_CATEGORY表示当前的Intent是一系列的可选动作中的一个,这些动作可以在同一块数据上执行。还有其他的为

ConstantMeaning
CATEGORY_BROWSABLE The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message.
CATEGORY_GADGET The activity can be embedded inside of another activity that hosts gadgets.
CATEGORY_HOME The activity displays the home screen, the first screen the user sees when the device is turned on or when the HOME key is pressed.
CATEGORY_LAUNCHER The activity can be the initial activity of a task and is listed in the top-level application launcher.
CATEGORY_PREFERENCE The target activity is a preference panel.

 

(5)component(组件),指定Intent的的目标组件的类名称。通常 Android会根据Intent 中包含的其它属性的信息,比如action、data/type、category进行查找,最终找到一个与之匹配的目标组件。但是,如果 component这个属性有指定的话,将直接使用它指定的组件,而不再执行上述查找过程。指定了这个属性以后,Intent的其它所有属性都是可选的。

(6)extras(附加信息),是其它所有附加信息的集合。使用extras可以为组件提供扩展信息,比如,如果要执行“发送电子邮件”这个动作,可以将电子邮件的标题、正文等保存在extras里,传给电子邮件发送组件。

理解Intent的关键之一是理解清楚Intent的两种基本用法:一种是显式的Intent,即在构造Intent对象时就指定接收者;另一种是隐式的Intent,即Intent的发送者在构造Intent对象时,并不知道也不关心接收者是谁,有利于降低发送者和接收者之间的耦合。

对于显式Intent,Android不需要去做解析,因为目标组件已经很明确,Android需要解析的是那些隐式Intent,通过解析,将 Intent映射给可以处理此Intent的Activity、IntentReceiver或Service。        

Intent解析机制主要是通过查找已注册在AndroidManifest.xml中的所有IntentFilter及其中定义的Intent,最终找到匹配的Intent。在这个解析过程中,Android是通过Intent的action、type、category这三个属性来进行判断的,判断方法如下:

  • 如果Intent指明定了action,则目标组件的IntentFilter的action列表中就必须包含有这个action,否则不能匹配;
  • 如果Intent没有提供type,系统将从data中得到数据类型。和action一样,目标组件的数据类型列表中必须包含Intent的数据类型,否则不能匹配。
  • 如果Intent中的数据不是content: 类型的URI,而且Intent也没有明确指定它的type,将根据Intent中数据的scheme (比如 http: 或者mailto:) 进行匹配。同上,Intent 的scheme必须出现在目标组件的scheme列表中。
  • 如果Intent指定了一个或多个category,这些类别必须全部出现在组建的类别列表中。比如Intent中包含了两个类别:LAUNCHER_CATEGORY 和 ALTERNATIVE_CATEGORY,解析得到的目标组件必须至少包含这两个类别。

 

Intent用法实例

1.无参数Activity跳转

Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);   

 

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
    protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_CODE){
            if(resultCode==RESULT_CANCELED)
                  setTitle("cancle");
            elseif (resultCode==RESULT_OK) {
                 String temp=null;
                 Bundle bundle=data.getExtras();
                 if(bundle!=null)   temp=bundle.getString("name");
                 setTitle(temp);
            }
        }
    }

下面是转载来的其他的一些Intent用法实例(转自javaeye)

显示网页
   1. Uri uri = Uri.parse("http://google.com");  
   2. Intent it = new Intent(Intent.ACTION_VIEW, uri);  
   3. startActivity(it);

显示地图
   1. Uri uri = Uri.parse("geo:38.899533,-77.036476");  
   2. Intent it = new Intent(Intent.ACTION_VIEW, uri);   
   3. startActivity(it);   
   4. //其他 geo URI 範例  
   5. //geo:latitude,longitude  
   6. //geo:latitude,longitude?z=zoom  
   7. //geo:0,0?q=my+street+address  
   8. //geo:0,0?q=business+near+city  
   9. //google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom

路径规划
   1. Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");  
   2. Intent it = new Intent(Intent.ACTION_VIEW, uri);  
   3. startActivity(it);  
   4. //where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456 

打电话
   1. //叫出拨号程序 
   2. Uri uri = Uri.parse("tel:0800000123");  
   3. Intent it = new Intent(Intent.ACTION_DIAL, uri);  
   4. startActivity(it);  
   1. //直接打电话出去  
   2. Uri uri = Uri.parse("tel:0800000123");  
   3. Intent it = new Intent(Intent.ACTION_CALL, uri);  
   4. startActivity(it);  
   5. //用這個,要在 AndroidManifest.xml 中,加上  
   6. //<uses-permission id="android.permission.CALL_PHONE" /> 

传送SMS/MMS
   1. //调用短信程序 
   2. Intent it = new Intent(Intent.ACTION_VIEW, uri);  
   3. it.putExtra("sms_body", "The SMS text");   
   4. it.setType("vnd.android-dir/mms-sms");  
   5. startActivity(it); 
   1. //传送消息 
   2. Uri uri = Uri.parse("smsto://0800000123");  
   3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);  
   4. it.putExtra("sms_body", "The SMS text");  
   5. startActivity(it); 
   1. //传送 MMS  
   2. Uri uri = Uri.parse("content://media/external/images/media/23");  
   3. Intent it = new Intent(Intent.ACTION_SEND);   
   4. it.putExtra("sms_body", "some text");   
   5. it.putExtra(Intent.EXTRA_STREAM, uri);  
   6. it.setType("image/png");   
   7. startActivity(it); 

传送 Email
   1. Uri uri = Uri.parse("mailto:xxx@abc.com");  
   2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);  
   3. startActivity(it); 


   1. Intent it = new Intent(Intent.ACTION_SEND);  
   2. it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");  
   3. it.putExtra(Intent.EXTRA_TEXT, "The email body text");  
   4. it.setType("text/plain");  
   5. startActivity(Intent.createChooser(it, "Choose Email Client")); 


   1. Intent it=new Intent(Intent.ACTION_SEND);    
   2. String[] tos={"me@abc.com"};    
   3. String[] ccs={"you@abc.com"};    
   4. it.putExtra(Intent.EXTRA_EMAIL, tos);    
   5. it.putExtra(Intent.EXTRA_CC, ccs);    
   6. it.putExtra(Intent.EXTRA_TEXT, "The email body text");    
   7. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");    
   8. it.setType("message/rfc822");    
   9. startActivity(Intent.createChooser(it, "Choose Email Client"));


   1. //传送附件
   2. Intent it = new Intent(Intent.ACTION_SEND);  
   3. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");  
   4. it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");  
   5. sendIntent.setType("audio/mp3");  
   6. 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 相关
1.        //寻找某个应用 
2.        Uri uri = Uri.parse("market://search?q=pname:pkg_name"); 
3.        Intent it = new Intent(Intent.ACTION_VIEW, uri);  
4.        startActivity(it);  
5.        //where pkg_name is the full package path for an application 
1.        //显示某个应用的相关信息 
2.        Uri uri = Uri.parse("market://details?id=app_id");  
3.        Intent it = new Intent(Intent.ACTION_VIEW, uri); 
4.        startActivity(it);  
5.        //where app_id is the application ID, find the ID   
6.        //by clicking on your application on Market home   
7.        //page, and notice the ID from the address bar

Uninstall 应用程序
1.        Uri uri = Uri.fromParts("package", strPackageName, null); 
2.        Intent it = new Intent(Intent.ACTION_DELETE, uri);   
3.        startActivity(it); 

例3:

 


今天要给大家讲一下Android中Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcelable(Key, Object);当然这些Object是有一定的条件的,前者是实现了Serializable接口,而后者是实现了Parcelable接口,为了让大家更容易理解我还是照常写了一个简单的Demo,大家就一步一步跟我来吧!

第一步:新建一个Android工程命名为ObjectTranDemo(类比较多哦!)目录结构如下图:

第二步:修改main.xml布局文件(这里我增加了两个按钮)代码如下

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="Welcome to Mr wei's blog."  
  11.     />  
  12. <Button  
  13.     android:id="@+id/button1"  
  14.     android:layout_width="fill_parent"  
  15.     android:layout_height="wrap_content"  
  16.     android:text="Serializable"  
  17. />  
  18. <Button  
  19.     android:id="@+id/button2"  
  20.     android:layout_width="fill_parent"  
  21.     android:layout_height="wrap_content"  
  22.     android:text="Parcelable"  
  23. />  
  24. </LinearLayout>   

 

第三步:新建两个类一个是Person.java实现Serializable接口,另一个Book.java实现Parcelable接口,代码分别如下:

Person.java:

 

  1. package com.tutor.objecttran;  
  2. import java.io.Serializable;  
  3. public class Person implements Serializable {  
  4.     private static final long serialVersionUID = -7060210544600464481L;   
  5.     private String name;  
  6.     private int age;  
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public int getAge() {  
  14.         return age;  
  15.     }  
  16.     public void setAge(int age) {  
  17.         this.age = age;  
  18.     }  
  19.       
  20. }  

 

Book.java:

 

  1. package com.tutor.objecttran;  
  2. import android.os.Parcel;  
  3. import android.os.Parcelable;  
  4. public class Book implements Parcelable {  
  5.     private String bookName;  
  6.     private String author;  
  7.     private int publishTime;  
  8.       
  9.     public String getBookName() {  
  10.         return bookName;  
  11.     }  
  12.     public void setBookName(String bookName) {  
  13.         this.bookName = bookName;  
  14.     }  
  15.     public String getAuthor() {  
  16.         return author;  
  17.     }  
  18.     public void setAuthor(String author) {  
  19.         this.author = author;  
  20.     }  
  21.     public int getPublishTime() {  
  22.         return publishTime;  
  23.     }  
  24.     public void setPublishTime(int publishTime) {  
  25.         this.publishTime = publishTime;  
  26.     }  
  27.       
  28.     public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {  
  29.         public Book createFromParcel(Parcel source) {  
  30.             Book mBook = new Book();  
  31.             mBook.bookName = source.readString();  
  32.             mBook.author = source.readString();  
  33.             mBook.publishTime = source.readInt();  
  34.             return mBook;  
  35.         }  
  36.         public Book[] newArray(int size) {  
  37.             return new Book[size];  
  38.         }  
  39.     };  
  40.       
  41.     public int describeContents() {  
  42.         return 0;  
  43.     }  
  44.     public void writeToParcel(Parcel parcel, int flags) {  
  45.         parcel.writeString(bookName);  
  46.         parcel.writeString(author);  
  47.         parcel.writeInt(publishTime);  
  48.     }  
  49. }  

 

第四步:修改ObjectTranDemo.java,并且新建两个Activity,一个是ObjectTranDemo1.java,别一个是ObjectTranDemo2.java.分别用来显示Person对像数据,和Book对象数据:,代码分别如下:

ObjectTranDemo.java:

 

  1. package com.tutor.objecttran;  
  2. import android.app.Activity;  
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. public class ObjectTranDemo extends Activity implements OnClickListener {  
  9.       
  10.     private Button sButton,pButton;  
  11.     public  final static String SER_KEY = "com.tutor.objecttran.ser";  
  12.     public  final static String PAR_KEY = "com.tutor.objecttran.par";  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);     
  16.         setupViews();  
  17.           
  18.     }  
  19.       
  20.     //我的一贯作风呵呵  
  21.     public void setupViews(){  
  22.         sButton = (Button)findViewById(R.id.button1);  
  23.         pButton = (Button)findViewById(R.id.button2);  
  24.         sButton.setOnClickListener(this);  
  25.         pButton.setOnClickListener(this);  
  26.     }  
  27.     //Serializeable传递对象的方法  
  28.     public void SerializeMethod(){  
  29.         Person mPerson = new Person();  
  30.         mPerson.setName("frankie");  
  31.         mPerson.setAge(25);  
  32.         Intent mIntent = new Intent(this,ObjectTranDemo1.class);  
  33.         Bundle mBundle = new Bundle();  
  34.         mBundle.putSerializable(SER_KEY,mPerson);  
  35.         mIntent.putExtras(mBundle);  
  36.           
  37.         startActivity(mIntent);  
  38.     }  
  39.     //Pacelable传递对象方法  
  40.     public void PacelableMethod(){  
  41.         Book mBook = new Book();  
  42.         mBook.setBookName("Android Tutor");  
  43.         mBook.setAuthor("Frankie");  
  44.         mBook.setPublishTime(2010);  
  45.         Intent mIntent = new Intent(this,ObjectTranDemo2.class);  
  46.         Bundle mBundle = new Bundle();  
  47.         mBundle.putParcelable(PAR_KEY, mBook);  
  48.         mIntent.putExtras(mBundle);  
  49.           
  50.         startActivity(mIntent);  
  51.     }  
  52.     //铵钮点击事件响应  
  53.     public void onClick(View v) {  
  54.         if(v == sButton){  
  55.             SerializeMethod();  
  56.         }else{  
  57.             PacelableMethod();  
  58.         }  
  59.     }  
  60. }  

 

ObjectTranDemo1.java:

 

  1. package com.tutor.objecttran;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.widget.TextView;  
  5. public class ObjectTranDemo1 extends Activity {  
  6.     @Override  
  7.     public void onCreate(Bundle savedInstanceState) {  
  8.         super.onCreate(savedInstanceState);  
  9.           
  10.         TextView mTextView = new TextView(this);  
  11.         Person mPerson = (Person)getIntent().getSerializableExtra(ObjectTranDemo.SER_KEY);  
  12.         mTextView.setText("You name is: " + mPerson.getName() + "/n"+  
  13.                 "You age is: " + mPerson.getAge());  
  14.           
  15.         setContentView(mTextView);  
  16.     }  
  17. }  

 

ObjectTranDemo2.java:

 

  1. package com.tutor.objecttran;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.widget.TextView;  
  5. public class ObjectTranDemo2 extends Activity {  
  6.    
  7.     public void onCreate(Bundle savedInstanceState) {  
  8.         super.onCreate(savedInstanceState);  
  9.         TextView mTextView = new TextView(this);  
  10.         Book mBook = (Book)getIntent().getParcelableExtra(ObjectTranDemo.PAR_KEY);  
  11.         mTextView.setText("Book name is: " + mBook.getBookName()+"/n"+  
  12.                           "Author is: " + mBook.getAuthor() + "/n" +  
  13.                           "PublishTime is: " + mBook.getPublishTime());  
  14.         setContentView(mTextView);  
  15.     }  
  16. }  

 

第五步:比较重要的一步啦,修改AndroidManifest.xml文件(将两个新增的Activity,ObjectTranDemo1,ObjectTranDemo2)申明一下代码如下(第14,15行):

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.tutor.objecttran"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".ObjectTranDemo"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.         <activity android:name=".ObjectTranDemo1"></activity>  
  15.         <activity android:name=".ObjectTranDemo2"></activity>  
  16.     </application>  
  17.     <uses-sdk android:minSdkVersion="7" />  
  18. </manifest>   

 

第六步:运行上述工程查看效果图啦:

效果1:首界面:

效果2:点击Serializable按钮

效果3:点击Parcelable按钮:


Intent显式跳转和隐式跳转(转)

(2014-08-09 18:05:19)
转载
标签:

intent

分类: Android

来源:http://blog.csdn.net/wulianghuan/article/details/8508848

 

 

显式 Intent 调用

1     //创建一个显式的 Intent 对象(方法一:在构造函数中指定)

 2      Intent intent = new Intent(Intent_Demo1.this, Intent_Demo1_Result1.class);

 3     

 4      Bundle bundle = new Bundle();

 5      bundle.putString("id", strID);

 6      intent.putExtras(bundle);

 7     

 8      intent.putExtra("name", "bbb");

 9      intent.putExtra("userInfo", new UserInfo(1, "name"));

10      startActivity(intent);

11     

12      //创建一个显式的 Intent 对象(方法二:用 setClass 方法)

13      Intent intent = new Intent();

14      Bundle bundle = new Bundle();

15      bundle.putString("id", strID);

16      intent.setClass(Intent_Demo1.this, Intent_Demo1_Result1.class);

17      intent.putExtras(bundle);

18      startActivity(intent);

19     

20      //创建一个显式的 Intent 对象(方法三:用 setClass 方法)

21      Intent intent = new Intent();

22      Bundle bundle = new Bundle();

23      bundle.putString("id", strID);

24      intent.setClassName(Intent_Demo1.this, "com.great.activity_intent.Intent_Demo1_Result1");

25      intent.putExtras(bundle);

26      startActivity(intent);

27     

28      //创建一个显式的 Intent 对象(方法四:用 setComponent 方法)

29      Intent intent = new Intent();

30      Bundle bundle = new Bundle();

31      bundle.putString("id", strID);

32      //setComponent方法的参数:ComponentName

33      intent.setComponent(new ComponentName(Intent_Demo1.this, Intent_Demo1_Result1.class));

34      intent.putExtras(bundle);

35      startActivity(intent);

 

 

Intent隐式跳转 Action

 

 

 1     //创建一个隐式的 Intent 对象:Action 动作

 2    

 7     Intent intent = new Intent();

 8     //设置 Intent 的动作

 9     intent.setAction("com.great.activity_intent.Intent_Demo1_Result3");

10     Bundle bundle = new Bundle();

11     bundle.putString("id", strID);

12     intent.putExtras(bundle);

13     startActivity(intent);

AndroidManifest.xml

 

 

1    < activity android:name="Intent_Demo1_Result3"

2                   android:label="Intent_Demo1_Result3">

3             < intent-filter>

4                 < action android:name="com.great.activity_intent.Intent_Demo1_Result3" />

5                 < category android:name="android.intent.category.DEFAULT" />

6             < /intent-filter>

7         < /activity>

 

 

Category 类别

 

 

 1 //创建一个隐式的 Intent 对象:Category 类别

 2 Intent intent = new Intent();

 3 intent.setAction("com.great.activity_intent.Intent_Demo1_Result33");

 4

 8 intent.addCategory(Intent.CATEGORY_INFO);

 9 intent.addCategory(Intent.CATEGORY_DEFAULT);

10 Bundle bundle = new Bundle();

11 bundle.putString("id", strID);

12 intent.putExtras(bundle);

13 startActivity(intent);

AndroidManifest.xml

 

 

  < activity android:name="Intent_Demo1_Result2"

                  android:label="Intent_Demo1_Result2">

            < intent-filter>

               

                < category android:name="android.intent.category.INFO" />

                < category android:name="android.intent.category.BROWSABLE" />

                < category android:name="android.intent.category.DEFAULT" />

               

            < /intent-filter>

        < /activity>

Date 数据 跳转

 

 

 1 //创建一个隐式的 Intent 对象,方法四:Date 数据

 2 Intent intent = new Intent();

 3 Uri uri = Uri.parse("http://www.great.org:8080/folder/subfolder/etc/abc.pdf");

 4

 5 //注:setData、setDataAndType、setType 这三种方法只能单独使用,不可共用               

 6 //要么单独以 setData 方法设置 URI

 7 //intent.setData(uri);

 8 //要么单独以 setDataAndType 方法设置 URI 及 mime type

 9 intent.setDataAndType(uri, "text/plain");

10 //要么单独以 setDataAndType 方法设置 Type

11 //intent.setType("text/plain");

12

13

17 Bundle bundle = new Bundle();

18 bundle.putString("id", strID);

19 intent.putExtras(bundle);

20 startActivity(intent);

AndroidManifest.xml

 

 

 1         < activity android:name="Intent_Demo1_Result2"

 2                   android:label="Intent_Demo1_Result2">

 3             < intent-filter>

 4                 < category android:name="android.intent.category.DEFAULT" />

 5                 < data

 6                     android:scheme="http"

 7                     android:host="www.great.org"

 8                     android:port="8080"

 9                     android:pathPattern=".*pdf"

10                     android:mimeType="text/plain"/>

11             < /intent-filter>

12         < /activity>

13        

 

 

 调用系统的的组件

 

 

 

 

    //web浏览器

    Uri uri= Uri.parse("http://www.baidu.com:8080/image/a.jpg");

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);

    startActivity(intent);

   

    //地图(要在 Android 手机上才能测试)

    Uri uri = Uri.parse("geo:38.899533,-77.036476");

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);

    startActivity(intent);

   

    //路径规划

    Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat startLng&daddr=endLat endLng&hl=en");

    Intent it = new Intent(Intent.ACTION_VIEW, uri);

    startActivity(it);

   

    //拨打电话-调用拨号程序

    Uri uri = Uri.parse("tel:15980665805");

    Intent intent = new Intent(Intent.ACTION_DIAL, uri);

    startActivity(intent);

   

    //拨打电话-直接拨打电话

    //要使用这个必须在配置文件中加入< uses-permission android:name="android.permission.CALL_PHONE"/>

    Uri uri = Uri.parse("tel:15980665805");

    Intent intent = new Intent(Intent.ACTION_CALL, uri);

    startActivity(intent);

 

    //调用发送短信程序(方法一)

    Uri uri = Uri.parse("smsto:15980665805");

    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);

    intent.putExtra("sms_body", "The SMS text");

    startActivity(intent);

   

    //调用发送短信程序(方法二)

    Intent intent = new Intent(Intent.ACTION_VIEW);    

    intent.putExtra("sms_body", "The SMS text");    

    intent.setType("vnd.android-dir/mms-sms");    

    startActivity(intent);

   

    //发送彩信

    Uri uri = Uri.parse("content://media/external/images/media/23");

    Intent intent = new Intent(Intent.ACTION_SEND);

    intent.putExtra("sms_body", "some text");

    intent.putExtra(Intent.EXTRA_STREAM, uri);

    intent.setType("image/png");

    startActivity(intent);

   

    //发送Email(方法一)(要在 Android 手机上才能测试)

    Uri uri = Uri.parse("mailto:zhangsan@gmail.com");

    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);

    startActivity(intent);

   

    //发送Email(方法二)(要在 Android 手机上才能测试)

    Intent intent = new Intent(Intent.ACTION_SENDTO); 

    intent.setData(Uri.parse("mailto:zhangsan@gmail.com")); 

    intent.putExtra(Intent.EXTRA_SUBJECT, "这是标题"); 

    intent.putExtra(Intent.EXTRA_TEXT, "这是内容"); 

    startActivity(intent);

   

    //发送Email(方法三)(要在 Android 手机上才能测试)

    Intent intent = new Intent(Intent.ACTION_SEND);

    intent.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");

    intent.putExtra(Intent.EXTRA_SUBJECT, "这是标题"); 

    intent.putExtra(Intent.EXTRA_TEXT, "这是内容");

    intent.setType("text/plain");

    //选择一个邮件客户端

    startActivity(Intent.createChooser(intent, "Choose Email Client")); 

   

    //发送Email(方法四)(要在 Android 手机上才能测试)

    Intent intent = new Intent(Intent.ACTION_SEND);

    //收件人

    String[] tos = {"to1@abc.com", "to2@abc.com"};

    //抄送人

    String[] ccs = {"cc1@abc.com", "cc2@abc.com"};

    //密送人

    String[] bcc = {"bcc1@abc.com", "bcc2@abc.com"};

    intent.putExtra(Intent.EXTRA_EMAIL, tos);   

    intent.putExtra(Intent.EXTRA_CC, ccs);

    intent.putExtra(Intent.EXTRA_BCC, bcc);

    intent.putExtra(Intent.EXTRA_SUBJECT, "这是标题");

    intent.putExtra(Intent.EXTRA_TEXT, "这是内容");   

    intent.setType("message/rfc822");   

    startActivity(Intent.createChooser(intent, "Choose Email Client"));

   

    //发送Email且发送附件(要在 Android 手机上才能测试)

    Intent intent = new Intent(Intent.ACTION_SEND);   

    intent.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");   

    intent.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mp3/醉红颜.mp3");   

    intent.setType("audio/mp3");   

    startActivity(Intent.createChooser(intent, "Choose Email Client"));

   

    //播放媒体文件(android 对中文名的文件支持不好)

    Intent intent = new Intent(Intent.ACTION_VIEW);

    //Uri uri = Uri.parse("file:///sdcard/zhy.mp3");

    Uri uri = Uri.parse("file:///sdcard/a.mp3");

    intent.setDataAndType(uri, "audio/mp3");

    startActivity(intent);

   

    Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");    

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);    

    startActivity(intent);

   

    //音乐选择器

    //它使用了Intent.ACTION_GET_CONTENT 和 MIME 类型来查找支持 audio/* 的所有 Data Picker,允许用户选择其中之一

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

    intent.setType("audio/*");

    //Intent.createChooser:应用选择器,这个方法创建一个 ACTION_CHOOSER Intent

    startActivity(Intent.createChooser(intent, "选择音乐"));

   

    Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);

    intent1.setType("audio/*");

   

    Intent intent2 = new Intent(Intent.ACTION_CHOOSER);

    intent2.putExtra(Intent.EXTRA_INTENT, intent1);

    intent2.putExtra(Intent.EXTRA_TITLE, "aaaa");

    startActivity(intent2);

   

   

//                //设置壁纸

//                Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER); 

//                startActivity(Intent.createChooser(intent, "设置壁纸")); 

   

    //卸载APK

    //fromParts方法

    //参数1:URI 的 scheme

    //参数2:包路径

    //参数3:

    Uri uri = Uri.fromParts("package", "com.great.activity_intent", null);   

    Intent intent = new Intent(Intent.ACTION_DELETE, uri);    

    startActivity(intent);

   

    //安装APK(???)

    Uri uri = Uri.fromParts("package", "com.great.activity_intent", null); 

    Intent intent = new Intent(Intent.ACTION_PACKAGE_ADDED, uri);

    startActivity(intent);

   

    //调用搜索

    Intent intent = new Intent(); 

    intent.setAction(Intent.ACTION_WEB_SEARCH); 

    intent.putExtra(SearchManager.QUERY, "android"); 

    startActivity(intent);


 鸣谢资源:http://blog.sina.com.cn/s/blog_5d2e69770102v0ra.html

 
 
 
posted @ 2015-04-28 12:32  摸摸淡  阅读(684)  评论(0编辑  收藏  举报