关于Android里Intent的使用方法

最近在系统的看android编程,记录一下笔记。Intent的各种用法。

1.显示Intent,SecondActivity不需要任何处理,跳转到SecondActivity。

1 Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
2 StartActivity(intent);
View Code

 2.显示Intent,SecondActivity设置如下:

1 <intent-filter>
2     <action android:name = "com.example.activitytest.ACTION_START"/>
3     <category android:name = "android.intent.category.DEFAULT"/>
4 </intent-filiter>
View Code

FirstActivity发送Intent:

1 Intent intent = new Intent("com.example.activitytest.ACTION_START"/>
2 StartActivity(intent);
View Code

这是隐式Intent的使用方法,这里默认了一个category,也可以自己添加另外的category。上述用于一个APP内的跳转。接下来看看不同应用间的跳转,如下:

1 Intent intent = new Intent(Intent.ACTION_VIEW);
2 intent.setData(Uri.parse("http://www.baidu.com"));
3 StartActivity(intent);
View Code

使用这个可以打开系统默认浏览器,并访问baidu。

接下来列举一下系统的ACTION:这些是从说明文档里看到的各种系统定义的ACTION和CATEGORY。

Standard Activity Actions

These are the current standard actions that Intent defines for launching activities (usually through startActivity(Intent). The most important, and by far most frequently used, are ACTION_MAIN andACTION_EDIT.

Standard Broadcast Actions

These are the current standard actions that Intent defines for receiving broadcasts (usually through registerReceiver(BroadcastReceiver, IntentFilter) or a <receiver> tag in a manifest).

Standard Categories

These are the current standard categories that can be used to further clarify an Intent via addCategory(String).

Standard Extra Data

These are the current standard fields that can be used as extra data via putExtra(String, Bundle).

在接收Intent的过滤器时:一个ACTION,多个CATEGORY,多个DATA。

DATA标签包括:

1. android:scheme
用于指定数据的协议部分,如上例中的 http 部分。
2. android:host
用于指定数据的主机名部分,如上例中的 www.baidu.com 部分。
3. android:port
用于指定数据的端口部分,一般紧随在主机名之后。
4. android:path
用于指定主机名和端口之后的部分,如一段网址中跟在域名之后的内容。
5. android:mimeType
用于指定可以处理的数据类型,允许使用通配符的方式进行指定。

到这里基本的Intent已经介绍完了,接下来是使用Intent来传递数据给下一个Activity.

1 String data = "Hello SecondActivity";
2 Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
3 intent.putExtra("extra_data", data);
4 startActivity(intent);
View Code
1 Intent intent = getIntent();
2 String data = intent.getStringExtra("extra_data");
3 Log.d("SecondActivity", data);
View Code

还有一种就是FirstActivity需要SecondActivity返回数据。

1 Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
2 startActivityForResult(intent, 1);
View Code
1 Intent intent = new Intent();
2 intent.putExtra("data_return", "Hello FirstActivity");
3 setResult(RESULT_OK, intent);
View Code
 1 @Override
 2 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 3 switch (requestCode) {
 4 case 1:
 5 if (resultCode == RESULT_OK) {
 6 String returnedData = data.getStringExtra("data_return");
 7 Log.d("FirstActivity", returnedData);
 8 }
 9 break;
10 default:
11 }
12 }
View Code
原文地址:https://www.cnblogs.com/plmmlp09/p/4221209.html