Intent 是一种消息传递机制,用于组件之间的数据交换和发送播送音讯
应用程序有多个 Activity,Intent 能够实现不同 Activity 之间的切换和数据传递
显示启动
Intent intent = new Intent(IntentDemoActivity.this, NewActivity.class);
startActivity(intent);
隐式启动:升高组件之间的耦合度
用 intent 启动一个网页
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("schemodemo://edu.hrbeu/path"));
startActivity(intent);
Intent.ACTION_VIEW 是 Intent 的罕用动作,以 Uri 形式传送数据
获取 Activity 的返回值
先启动的 Activity 称为父 Activity
后启动的 Activity 称为子 Activity
获取子 Activity 的返回值?
-
以 Sub-Activity 的形式启动子 Activity
显示启动int SUBACTIVITY1 = 1; Intent intent = new Intent(ActivityCommunicationActivity.this, SubActivity1.class); startActivityForResult(intent, SUBACTIVITY1);
隐式启动
int SUBACTIVITY2 = 2; Uri uri=Uri.parse("content://contacts/people"); Intent intent = new Intent(Intent.ACTION_PICK,uri); startActivityForResult(intent, SUBACTIVITY2);
-
设置子 Activity 的返回值
在 finish()之前调用 setResult()函数返回数据给父 Activity
第一个参数是状态码
第二个参数是返回值,它被封装在 Intent 中
调用 Intent 的 putExtra()办法增加额定信息String uriString = editText.getText().toString(); Uri data = Uri.parse(uriString); Intent result = new Intent(null, data); result.putExtra("name","xyy"); setResult(RESULT_OK, result); finish();
-
在父 Activity 中获取返回值
protected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data); switch(requestCode){ case SUBACTIVITY1: if (resultCode == RESULT_OK){Uri uriData = data.getData(); textView.setText(uriData.toString()); } break; case SUBACTIVITY2: if (resultCode == RESULT_OK){Uri uriData = data.getData(); } break; } }
Intent 过滤器
它是依据 Intent 中的动作 action, 类别 category, 数据 data 等内容,对承受该 Intent 的组件进行匹配和筛选机制
<activity
android:label="@string/app_name"
android:name=".WebViewIntentDemoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="schemodemo" android:host="edu.hrbeu" />
</intent-filter>
</activity>
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("schemodemo://edu.hrbeu/path"));
startActivity(intent);
播送音讯
用 Intent 发送播送音讯
- 创立一个 intent
-
调用 sendBroadcast()函数
Intent intent = new Intent("edu.hrbeu.BroadcastReceiverDemo"); intent.putExtra("message", entryText.getText().toString()); sendBroadcast(intent);
监听播送音讯用 BroadcastReceiver
申明 BroadcastReceiver 能够接管的播送音讯类型<receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="edu.hrbeu.BroadcastReceiverDemo" /> </intent-filter> </receiver>
public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {String msg = intent.getStringExtra("message"); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();}