Android通过intent传递消息代码示例
时间: 2023-05-24 22:02:47 浏览: 75
A:
发送方代码:
```
Intent intent = new Intent();
intent.setAction("com.example.ACTION_SEND_MESSAGE");
intent.putExtra("MESSAGE", "Hello world!");
startActivity(intent);
```
接收方代码:
```
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.example.ACTION_SEND_MESSAGE")) {
String message = intent.getStringExtra("MESSAGE");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
```
需要在AndroidManifest.xml中注册接收方:
```
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.ACTION_SEND_MESSAGE" />
</intent-filter>
</receiver>
```