码迷,mamicode.com
首页 > 移动开发 > 详细

android学习——Intent总结

时间:2015-03-11 22:53:00      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

一、什么是Intent?

Intent的中文意思是目的。在Android中也是“目的”的意思。就是我们要去哪里,从这个activity要前往另一个Activity就需要用到Intent。

 

第一种:直接启动一个Activity

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

 

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

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.halzhang.android.intent" android:versionCode="1" android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".IntentDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
         <activity android:name=".AnotherActivity" android:label="another">
             <intent-filter>
                <action android:name="android.intent.action.EDIT" />
               <!-- category一定要配置,否则报错:找不到Activity -->
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
         </activity>
  
         <activity android:name=".AnotherActivity2" android:label="another2">
           <intent-filter>
                 <action android:name="android.intent.action.EDIT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
         </activity>
   </application>
   <uses-sdk android:minSdkVersion="3" />
  <!--上面配置的两个activity具有相同的action类型,都为“android.intent.action.EDIT”
        当Intent的action属性为Intent.ACTION_EDIT时,系统不知道转向哪个Activity时,
         就会弹出一个Dialog列出所有action为“android.intent.action.EDIT”的
        Activity供用户选择 -->
 </manifest> 

 

第二种:启动另一个Activity并返回结果
作用:当从第二个Activity回跳到前一个Activity的时候,就不再需要使用startActivity,也就是说不用两次使用startActivity方法
startActivityForResult(Intent intent, Int requestCode)
intent 传给要跳转的Activity的数据和动作

requestCode >=0就好,随便用于在onActivityResult()区别哪个子模块回传的数据,如果还有C.java ,D甚至E子模块的话,每个区分开不同的requestCode就好。

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            //给按钮添加绑定的事件
            Button myButton = (Button)findViewById(R.id.myButton);
            myButton.setText("我的第一个Button");
            myButton.setOnClickListener(new OnClick());
        }
     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println(requestCode);
        System.out.println(resultCode);
    }

     public class OnClick implements OnClickListener{

            @Override
            public void onClick(View v) {
                //生成一个Intent对象
                Intent intent = new Intent();
                intent.putExtra("testIntent", "testExtra");
                intent.setClass(MainActivity.this,SecondActivity.class);
                //直接启动一个Activity
//                startActivity(intent);
                //启动一个有返回值的Activity
                startActivityForResult(intent, 2);
            }
        }
}

setResut(int resultCode, Intent intent)
resultCode如果跳转的Activity子模块可能有几种不同的结果返回,可以用这个参数予以识别区分。这里还有个特殊的RESULT_OK值,没有特殊情况用它就好了,sdk有说明的。
intent 继续不解释,传回给A的onActivityResult()

 

onActivityResult(int requestCode, int resultCode, Intent intent)
这里三个都不用解释了,与上文对应的东西。如果不对requestCode和resultCode 加以识别区分的话,只要有其他activity setResult到了A  onActivityResult()会无差别处理

public class SecondActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.other);
        Button btn = (Button)findViewById(R.id.otherButton);
        btn.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                setResult(3, intent);
                finish();
            }
        });
    }
}

 

二、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常量。

示例代码二:

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

 

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

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

技术分享 

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

 

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

在Main中执行如下代码:

 Bundle bundle = new Bundle();
 bundle.putStringArray("NAMEARR", nameArr);
 Intent intent = new Intent(Main.this, CountList.class);
 intent.putExtras(bundle);
 startActivity(intent);

在CountList中,代码如下:

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

 

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

 

如何使用自定义的Action属性?

1、定义一个自定义的Action名称——常量

public static final String MY_ACTION = "hb.com.MY_ACTION";

2、使用一个按钮然后给其绑定事件,让它跳转到另一个Activity

myActionBtn.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View v) {
        System.out.println("myActionBtn");
//                    Intent intent = getIntent();
// 这里一定要new一个Intent对象,如果用上面的则打开的是当前的Activity
        Intent intent = new Intent();
        intent.setAction(MY_ACTION);
        startActivity(intent);
    }
});

3、在AndroidManifest.xml配置文件中添加Activity的名称

<activity android:name=".SecondActivity" android:label="@string/secondActivity">
    <intent-filter>
        <action android:name="hb.com.MY_ACTION" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

备注:hb.com.MY_ACTION这个值与intent.setAction(MY_ACTION);值是一样的
activity标签在application标签内部
category这个属性在Intent Filter中必须出现,否则不能测试通过

 

Intent的Data属性是指定动作的URI和MIME类型,不同的Action有不同的Data数据指定
Intent中的Category属性是一个执行Action的附加信息
Intent的Extras属性是添加一些组件的附加信息

 

 Intent 调用大全

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.发送彩信
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);
StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsoluteFile());
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
startActivity(intent);

9.发送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"));

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 apk
Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);

12.install apk
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);

13. 打开照相机
<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);

14.从gallery选取图片
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 11);

15. 打开录音机
Intent mi = new Intent(Media.RECORD_SOUND_ACTION);
startActivity(mi);

16.显示应用详细列表
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>");
这个简单多了

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 application

18.打开联系人列表
<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);

19.打开另一程序
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);
//调用浏览器Uri uri = Uri.parse("");
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);
//显示路径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);
//拨打电话Uri uri = Uri.parse("tel:10086");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);Uri uri = Uri.parse("tel.10086");
Intent it =new Intent(Intent.ACTION_CALL,uri);
需要添加 <uses-permission id="android.permission.CALL_PHONE" /> 这个权限到androidmanifest.xml
//发送短信或彩信Intent it = new Intent(Intent.ACTION_VIEW);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);
//发送短信Uri uri = Uri.parse("smsto:10086");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "cwj");
startActivity(it);
//发送彩信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);
//发送邮件
Uri uri = Uri.parse("mailto:android123@163.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, android123@163.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_VIEW);
Uri uri = Uri.parse("[url=]file:///sdcard/cwj.mp3[/url]");
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);
//卸载APKUri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);
//卸载apk 2
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);
//安装APK
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
//播放音乐Uri playUri = Uri.parse("[url=]/sdcard/download/sth.mp3[/url]");
returnIt = new Intent(Intent.ACTION_VIEW, playUri);
//发送附近Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "[url=]file:///sdcard/cwj.mp3[/url]");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//market上某个应用信,pkg_name就是应用的packageNameUri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//market上某个应用信息,app_id可以通过www网站看下Uri uri = Uri.parse("market://details?id=app_id");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//调用搜索Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"android123")
startActivity(intent);

原文:http://bbs.51cto.com/thread-944255-1.html

 

android学习——Intent总结

标签:

原文地址:http://www.cnblogs.com/guichun/p/4330984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!