进程间通信,广播接收者,这个我们经常会用到,比如检测网络变化,这个还是比较实用的,但是如何实现,其实很简单,那我们就开始吧。
借助于之前activity 通信的demo 我们继续。Activity 跨进程通信
这个比较简单我们一切从简,如果还有不懂后边会贴出代码下载地址
1.新建项目,接收Activity (ReceiveActivity)中自定类继承自BroadcastReceiver 并且注册,设置action
class MyReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null) {
String str = intent.getAction();
Toast.makeText(getApplicationContext(), intent.getAction() + intent.getStringExtra("info"), Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "onReceive: onReceive is Null");
Toast.makeText(getApplicationContext(), "onReceive is Null", Toast.LENGTH_SHORT).show();
}
}
}
注册广播并且自定义action标签,这个发送时要用到
broadcastReceiver = new MyReceive();
intentFilter = new IntentFilter();
intentFilter.addAction("com.test.receiver");
registerReceiver(broadcastReceiver, intentFilter);
现在用于接收的项目完毕了。
public class ReceiveActivity extends AppCompatActivity {
private static final String TAG = "ReceiveActivity";
/**
* Hello World!
*/
private TextView mTest;
BroadcastReceiver broadcastReceiver;
private IntentFilter intentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
broadcastReceiver = new MyReceive();
intentFilter = new IntentFilter();
intentFilter.addAction("com.test.receiver");
registerReceiver(broadcastReceiver, intentFilter);
}
class MyReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null) {
String str = intent.getAction();
Toast.makeText(getApplicationContext(), intent.getAction() + intent.getStringExtra("info"), Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "onReceive: onReceive is Null");
Toast.makeText(getApplicationContext(), "onReceive is Null", Toast.LENGTH_SHORT).show();
}
}
}
}
2.现在新建项目,用于发送广播消息
Intent intent1 = new Intent();
intent1.setAction("com.test.receiver");
intent1.putExtra("info", "内容");
sendBroadcast(intent1);
就这么多,功能完成。