Android:如何在重新启动应用时检测后台服务?

时间:2016-01-30 19:29:42

标签: android service background

我有一个应用程序,可以创建一个永无止境的后台服务。该应用程序启动时启动该服务。当应用程序被杀死时(例如,由用户),该服务发送广播请求,该请求将在被杀死后重新启动它。 问题是:当我重新启动应用程序时,如何知道该服务是否已在运行? 天真的我以为通过在重新启动应用程序时重新启动服务,它会停止现有服务,但这不会发生。下面的代码显示,如果我这样做,有两个服务同时运行(计时器中的打印输出从每秒钟移动到每半秒一次)。 非常感谢

public class MainActivity extends AppCompatActivity {
        static Intent mServiceIntent;
        private SensorService mSensorService;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ctx=this;
            setContentView(R.layout.activity_main);
            mSensorService= new SensorService(getCtx());
            mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
            startService(mServiceIntent);
        }

        Context ctx;

        public Context getCtx() {
            return ctx;
        }



        @Override
        protected void onDestroy() {
            stopService(mServiceIntent);
            Log.i("MAINACT", "onDestroy!");
            super.onDestroy();

        }
    }

public class SensorService extends Service {

    public int counter=0;

    public SensorService(Context applicationContext) {
        super();
        Log.i("HERE", "here I am!");

    }

    public SensorService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        startTimer();
        return START_STICKY;
    }


    private Timer timer;
    private TimerTask timerTask;

    long oldTime=0;

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to check if the service is there in 25s
        timer.schedule(timerTask, 1000, 1000); //
    }

    /**
     * it sets the timer to check in x seconds if the sensorsService is active. If not it will start the service
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                long time= System.currentTimeMillis();
               Log.i("in timer", "in timer ++ "+(time-oldTime)+" ++  "+ (counter++));
                oldTime= time;
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "ondestroy!");
        Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
        stoptimertask();
    }

        @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");

        context.startService(new Intent(context, SensorService.class));;
    }

}

1 个答案:

答案 0 :(得分:3)

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

然后使用

isMyServiceRunning(MyService.class)

Credit