Android: Check if service is running via. bindServ

2019-04-03 07:57发布

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 the scenarios similar to mine (source). I am also aware of the possibility of using global/persistent variables to maintain the state of a service.

I have tried to use bindService with flags set to 0, but I got the same problems as the person on the source link (the only exception was, I was trying the bindService with a local service).

The following call

getApplicationContext().bindService(new Intent(getApplicationContext(),
        MyService.class), mServiceConnection, 0);

always returns true, but does not get connected. Is this the expected behaviour? It seems to me bindService should return false if the service is not already running (it is not, I have checked that) or if the BIND_AUTO_CREATE flag is not set (again, it is not).

7条回答
Summer. ? 凉城
2楼-- · 2019-04-03 08:24

in your activity u can simply check it by using instance of your service in my case i done it using

  button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent=new Intent(MainActivity.this, MyService.class);
            //startService(intent);
            bindService(intent,serviceConnection,BIND_AUTO_CREATE);
            if (myService!=null)
            {
                myService.RecData(editText.getText().toString());
            }
        }
    });
}

ServiceConnection serviceConnection=new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Toast.makeText(MainActivity.this,"onServiceConnected called",Toast.LENGTH_SHORT).show();
        MyService.MyBinder myBinder= (MyService.MyBinder) iBinder;
        myService= myBinder.getServiceInstant();
        myService.SetActivity(MainActivity.this);
        myService.RecData(editText.getText().toString());
    }
查看更多
神经病院院长
3楼-- · 2019-04-03 08:35

What do you plan on doing if the service is running/not running? Why not just call startService(). That will create it if it's not running, and if it is it will call its onStart() method.

查看更多
乱世女痞
4楼-- · 2019-04-03 08:39

I have the same issue; seems the best known solution is to create a public static boolean in WhateverService, set to true during onCreate (or onStartCommand, your choice) and false during onDestroy. You can then access it from any other class in the same apk. This may be racey though. There is no API within Android to check if a service is running (without side effects): See http://groups.google.com/group/android-developers/browse_thread/thread/8c4bd731681b8331/bf3ae8ef79cad75d

I suppose the race condition comes from the fact that the OS may kill a remote service (in another process) at any time. Checking a local service (same process), as suggested above, seems race-free to me -- if the OS kills the service, it kills whatever checked its status too.

查看更多
在下西门庆
6楼-- · 2019-04-03 08:41

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);
}
查看更多
戒情不戒烟
7楼-- · 2019-04-03 08:44

Another method:

public static boolean isServiceRunning(Context ctx, String serviceClassName) {
    ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (TrackingService.class.getName().equals(serviceClassName)) {
            return true;
        }
    }
    return false;
}
查看更多
登录 后发表回答