在此记录安卓常用组件广播接收器的学习知识。
广播(Broadcast Receivers):
- 一些系统发出的广播:时区改变、电池量低、照片已被拍、改变语言习惯
- 自己应用发出广播:自定义
标准广播:
- 采用异步方式并行发送广播,同时发送多个广播
- sendBroadcast()发送标准广播
有序广播:
- 采用同步方式串行发送广播,同意时刻只能接收一个广播
- sendOrderedBroadcast()发送有序广播
广播接收器是为后台短时间、少量处理功能设计,它的响应处理时间很短,而服务是处理大量功能设计的,响应时间很长,一般还有多线程处理。一般广播接收器接收一个广播后,再启动一个服务,由服务进行处理。
编写一个广播接收器:
Public class MyBroadcastReceiver extends BroadcastReceiver{
Public void onReceive(Context context , Intent intent){
Toast.makeText(context,”XXX”,Toast.LENGTH_LONG).show();
}
}
广播接收器的内部类:
Private BroadcastReceiver mReceiver = new BroadcastReceiver (){
Public void onReceiver(Context context,Intent intent){
Toast.makeText(context,”XXX”,Toast.LENGTH_LONG).show();
//访问当前组件中成员变量
}
};
注册广播接收器:
静态注册:
<receiver android:name="com.a51work6.brsample.MyBroadcastReceiver">
<intent-filter>
<action android:name="com.a51work6.brsample.MyBroadcastReceiver" />
</intent-filter>
</receiver>
动态注册:
- registerReceiver()方法注册 onResume()方法注册 onCreate()方法注册
- unregisterReceiver()方法注销 onPause()方法注销 onDestory()方法注销
动态注册代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction(ACTION_APP_BROADCAST);
sendBroadcast(intent);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_APP_INNER_BROADCAST);
registerReceiver(mReceiver, filter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "您的内部广播接收器接收了广播",
Toast.LENGTH_LONG).show();
//TODO访问当前组件中成员变量
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
系统广播:
系统广播动作:Intent.ACTION_TIME_TICK 时间改变时候发出的广播
实例:Downloader
注册表:
<!--服务-->
<service android:name="com.a51work6.downloader.DownloadService" />
接收器
<receiver android:name="com.a51work6.downloader.SystemReceiver">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
DownLoader代码:
SystemReceiver
// 广播接收器
public class SystemReceiver extends BroadcastReceiver {
private final static String TAG = "SystemReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "SystemBootReceiver...");
// 接收到系统广播
Intent it = new Intent(context, DownloadService.class);
context.startService(it);
}
}
DownloadService
//下载服务
public class DownloadService extends IntentService {
private final static String TAG = "DownloadService";
private boolean isRunning = true;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
while (isRunning) {
try {
Thread.sleep(1000 * 5);//休眠5秒
// 如果Wifi网络可用开下载
if (isConnected(ConnectivityManager.TYPE_WIFI)) {
Log.i(TAG, "Download thread start...");
//TODO下载任务处理,任务处理完成isRunning设置为false停止任务。
}
} catch (InterruptedException e1) {
Log.i(TAG, "Download thread start failure...");
continue;
}
}
}
//判断是否WIFI打开
private boolean isConnected(int type) {
ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connMgr.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connMgr.getNetworkInfo(mNetwork);
if (networkInfo != null
&& networkInfo.getType() == type
&& networkInfo.isConnected()) {
return true;
}
}
return false;
}
}
本地广播:在自己的应用内部发送接收广播
本地广播API:通过LocalBroadcastManager管理发送、注册、注销广播,全局广播通过上下文对象发送、注册、注销广播。
LocalBroadcastManager常用方法:
- boolean sendBroadcast(Intent intent) //发送广播
- Void registerReceiver(BroadcastReceiver recevier , IntentFilter filter) //注册广播
- Void unregisterReceiver(BroadcastReceiver recevier) //注销广播
全局广播:
- 通过上下文对象的sendBroadcast() 发送
- 通过上下文对象的registerReceiver() 注册
- 通过上下文对象的unregisterReceiver() 注销
发送本地广播:
public class MainActivity extends AppCompatActivity {
private static String ACTION_LOCAL_BROADCAST = "com.a51work6.brsample.MyBroadcastReceiver";
private LocalBroadcastManager mLocalBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获得本地广播管理器实例
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
//注册本地广播接收器
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_LOCAL_BROADCAST);
mLocalBroadcastManager.registerReceiver(mReceiver, filter);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(ACTION_LOCAL_BROADCAST);
//发送本地广播
mLocalBroadcastManager.sendBroadcast(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//注销本地广播接收器
mLocalBroadcastManager.unregisterReceiver(mReceiver);
}
// 本地广播接收器
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "您接收了本地广播",
Toast.LENGTH_LONG).show();
}
};
}
通知:
普通通知:
public class MainActivity extends AppCompatActivity {
private static final int NOTIFY_ME_ID = 12345;
//Timer是一个定时器:它可以定时调度任务TimerTask
//实现任务某一时间执行一次或多次
private Timer timer = new Timer();
//通知管理器
private NotificationManager mNotificationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.notify);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TimerTask task = new TimerTask() {//创建调度任务TimeTask
public void run() { //抽象类实现Runnable接口
notifyMe();
}
};
//延时3秒发送(执行任务)
timer.schedule(task, 3000);
}
});
Button button2 = (Button) findViewById(R.id.cancel);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// 取消显示在通知列表中的指定通知
mNotificationManager.cancel(NOTIFY_ME_ID);
}
});
//获得通知管理器
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
}
private void notifyMe()
//(意图)设置单击通知后所打开的详细界面
//getActivity getBroadcast getService静态方法获得PendingIntent对象
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, NotificationActivity.class), 0);
//获得res对于的资源对象
Resources res = this.getResources();
//创建通知对象
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setContentTitle("通知发送人")
.setContentText("我是详细的通知")
.setContentIntent(pendingIntent).build();
//发送通知
mNotificationManager.notify(NOTIFY_ME_ID, notification);
}
}
其他形式的Notification,除文本形式显示状态栏之外,还有:LED灯、震动、播放音乐形式
闪烁的LED灯:
- Notification定义属性设置LED
- ledARGB属性:用于设置LED的颜色
- ledOffMS属性:LED灯不亮的时间
- ledOnMS属性:LED灯亮的毫秒时间
一旦设置LED,必须为flags添加.FLAG_SHOW_LIGHTS标志位
notification.ledARGB = Color.RED;
notification.ledOffMS = 0;
notification.ledOnMS = 1;
Notification.flags = notification.flags|Notification.FLAG_SHOW_LIGHTS
震动通知:
执行效果:T1,Z2,T1,Z1,T1,Z1
long vibrate =new long[]{1000,2000,1000,1000,1000,1000};
Notification.vibrate = vibrate;
播放声音通知:
一个Notification到来时,发出声音。
给sound属性设置一个位置URI
URI ringURI = URi.fromFile(new File(“/system/media/audio/ringtones/ring.mp3”));
Notification.sound = ringURI;