Android通过广播调后台Service

来源:互联网 发布:win10专业版网络掉线 编辑:程序博客网 时间:2024/06/16 01:42
Android在3.1(Api Level=12)版本之后给Intent新增两个Flag:FLAG_INCLUDE_STOPPED_PACKAGES:表示包含未启动的App。FLAG_EXCLUDE_STOPPED_PACKAGES:表示不包含未启动的这两个FlAG用来控制Intent是否要对处于停止状态的App起作用。所据说主要目的防止通过广播无意或不必要地开启未启动App的后台服务。如果要强制调起未启动的App,如果我们的项目要通过广播来启动后台运行的服务,又要兼容3.1以下版本,那我们则需要进行相应判断:
//自定义广播MyBroadcastReceiver   public class MyBroadcastReceiver extends BroadcastReceiver {    public static final String MY_ACTION = "COM_LDM_SRATR_SERVER";    @Override    public void onReceive(Context context, Intent intent) {        String action = intent.getAction();        if (intent.getAction().equals(MY_ACTION)) {            //判断要启动的Service是否正在运行            boolean isRunning = serviceRunState(context,                    "com.ldm.server.MyService");            if (!isRunning) {//Service没有运行,则启动服务                Intent in = new Intent(context, MyService.class);                if (android.os.Build.VERSION.SDK_INT >= 12) {                    // 3.1以后设置Intent.FLAG_INCLUDE_STOPPED_PACKAGES                    in.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);                }                context.startService(in);            }        }    }   /**     * 判断指定Service运行的状态     * @param context     * @param className     * @return     */    public static boolean serviceRunState(Context context, String className) {        boolean isRun = false;        ActivityManager activityManager = (ActivityManager) context                .getSystemService(Context.ACTIVITY_SERVICE);        List<ActivityManager.RunningServiceInfo> serviceList = activityManager                .getRunningServices(30);        if (!(serviceList.size() > 0)) {            return false;        }        for (int i = 0; i < serviceList.size(); i++) {            if (serviceList.get(i).service.getClassName().equals(className)) {                isRun = true;                break;            }        }        return isRun;    }}

然后在指定页面中注册我们自定义的广播即可,不要忘记添加相应ACTION哦!

0 0
原创粉丝点击