如何检查服务是否正在运行

6

我希望能显示服务的状态,无论是运行还是停止。我使用下面的代码,但它在启动服务之前就显示“已停止”。当服务开始运行时,它会显示“正在运行”。再次停止服务时,它仍然只显示“正在运行”。请问我在设置共享偏好状态方面有任何错误吗? 在MainActivity中

  onCreate()
  {
   checkServiceStatus() ;
  }

  private void checkServiceStatus() 
{
    Toast.makeText(getApplicationContext(),"in enableControls", Toast.LENGTH_LONG).show();
    boolean isServiceRunning = AppSettings.getServiceRunning(this);     
    if (isServiceRunning)
    {
        Toast.makeText(getApplicationContext(),"service running", Toast.LENGTH_LONG).show();    
    } 
    else 
    {   
        Toast.makeText(getApplicationContext(),"service stopped", Toast.LENGTH_LONG).show();        
    }
}


  public class AppSettings 
  {
 public static final String SERVICE_STATE = "isServiceRunning";
 public static boolean getServiceRunning(Context context){
         SharedPreferences pref = context.getSharedPreferences(GPSLOGGER_PREF_NAME, 0);

         return pref.getBoolean(SERVICE_STATE, false);
 }

 public static void setServiceRunning(Context context, boolean isRunning){
         SharedPreferences pref = context.getSharedPreferences(GPSLOGGER_PREF_NAME, 0);
         SharedPreferences.Editor editor = pref.edit();

         editor.putBoolean(SERVICE_STATE, isRunning);
         editor.commit();
 }

检查这个链接 https://dev59.com/LHRB5IYBdhLWcg3wgXhV - user2125834
3个回答

10
public class Receiver extends BroadcastReceiver {       
    @Override
    public void onReceive(Context context, Intent intent) {    
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (YourService.class.getName().equals(service.service.getClassName())) {
                //your service is running
            }
        }
        //your service is not running
    }
}

3
 ActivityManager manager = (ActivityManager)context.   getSystemService(Context.ACTIVITY_SERVICE);//use context received in broadcastreceiver

for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
 {

     if (MyService.class.getName().equals(service.service.getClassName())) {
                         //running 
        }
    else{
          //not running 
        }

 }

-4
 public static boolean CheckServiceConnectivity(Context mContext) 
     {
        ConnectivityManager connec = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
                || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)
            return true;

        return false;

    }

5
我猜这是用于检查网络连接。 - Manasi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接