Android: Check if service is running via. bindService

前端 未结 7 1457
心在旅途
心在旅途 2021-02-18 15:28

What would be the best way to check if an Android Service is running? I am aware of the ActivityManager API, but it seems like the use of the API is not advised for

相关标签:
7条回答
  • 2021-02-18 16:34

    Use a shared preference to save service running flag.

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int res = super.onStartCommand(intent, flags, startId);
        setRunning(true);
        return res;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        setRunning(false);
    }
    
    private void setRunning(boolean running) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pref.edit();
    
        editor.putBoolean(PREF_IS_RUNNING, running);
        editor.apply();
    }
    
    public static boolean isRunning(Context ctx) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
        return pref.getBoolean(PREF_IS_RUNNING, false);
    }
    
    0 讨论(0)
提交回复
热议问题