
(b).静态注册
需要在manifest中进行注册(在安卓8.0后系统废除了大部分静态广播,最好使用动态注册)。
(a).系统广播
系统中已经定义的广播,此类广播只能由系统发出,并且需要在intent-filter中加上系统已经写的action。
(b).自定义广播
顾名思义,是用户自己定义的广播。
(a)我们首先需要一个广播接收类
(b)其次注册动态广播
(c)最后需要通过send方法发送一个广播供广播接收者接受
另外还有有序广播和无序广播,这篇博客写的比较详细,供大家参考: Android的有序广播和无序广播(解决安卓8.0版本之后有序广播的接收问题) - ming3 - 博客园 (cnblogs.com)
在Service中的onStartCommand中动态注册广播。如下代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK)//注册IntentFilter
filter.setPriority(Integer.MAX_VALUE)//设置级别
receiver = new AppReceiver()//本地服务
registerReceiver(receiver, filter)//注册广播
return START_STICKY
}
广播代码:
package com.sevencolorbox.sdk.service
import java.util.List
import android.app.ActivityManager
import android.app.ActivityManager.RunningServiceInfo
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
public class AppReceiver extends BroadcastReceiver{
private boolean isServiceRunning = false
private String serviceName = "com.sevencolorbox.sdk.service.SevenColorService"
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)){
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE)
List<RunningServiceInfo>infos = am.getRunningServices(Integer.MAX_VALUE)
for (RunningServiceInfo info : infos) {
if (info.service.getClassName().equals(serviceName)) {
isServiceRunning = true
}
}
if (!isServiceRunning) {
Log.i("ss", "本地服务未开启")
Intent tIntent = new Intent(context,SevenColorService.class)
context.startService(tIntent)
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)