BroadcastReceiver简单应用实例
BroadcastReceiver是android四大组件之一,主要用于接收广播,它的简单实现方法如下:
1、定义继承BroadcastReceiver的MyReceiver类:
/**
* Created by Haoye on 2016/3/7.
* Copyright © 2016 Haoye All Rights Reserved
*/
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "MyReceiver";
@Override
public void onReceive(Context context, Intent intent) {
//...
}
}
2、在清单文件中注册广播接收器:
<receiver android:name=".MyReceiver"/>
3、用sendBroadcast()函数发送广播:
Intent intent = new Intent(MainActivity.this, MyReceiver.class);
intent.setAction("music.play");
sendBroadcast(intent);
4、在onReceive()函数中接收广播:
修改 onReceive()函数:
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
if ("music.play".equalsIgnoreCase(intent.getAction())) {
Log.e(TAG, "getAction");
}
}
5.运行测试:
......