zoukankan      html  css  js  c++  java
  • 防止服务被杀死的方法

    //注册Intent.ACTION_TIME_TICK过滤器的接收器,每分钟接收一次
    IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
    NoKillReceiver receiver = new NoKillReceiver();
    registerReceiver(receiver, filter);
    MainActivity.startActivity=this;

    //接收器代码,接收一次就判断需要打开的服务是否还在运行,如果已经被关闭折再次启动

    package com.caicai.receiver;
    
    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;
    
    import com.caicai.service.PushService;
    
    public class NoKillReceiver extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { 
                boolean isServiceRunning = false; 
                ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); 
                for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) { 
                if("com.caicai.service.caiPushService".equals(service.service.getClassName())) { 
                isServiceRunning = true; 
                }   
                 } 
                Intent i = new Intent(context, PushService.class); 
                context.startService(i); 
                if (!isServiceRunning) { 
        
                }else{
                     Log.i("tt", "166666666666666666666666");
                } 
                } 
        }
    
    }

    //需要启动的服务

    package com.caicai.service;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    import android.util.Log;
    
    public class PushService extends Service{
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
         @Override
            public void onStart(Intent intent, int startId) {
             Log.i("tt", "15555555555555555555555555555555555555555555555555555");
            }
    }
  • 相关阅读:
    Java实现水仙花数
    CSS3属性选择器
    Word快捷键
    Java实现百钱买百鸡
    某专业人士给中国计算机专业学生的建议
    经典名言警句
    面试问题和思路
    情商
    Java注意的地方
    唯大英雄能真本色——Leo鉴书34
  • 原文地址:https://www.cnblogs.com/clarence/p/3571072.html
Copyright © 2011-2022 走看看