如何检查服务是不是正在运行[重复]
Posted
技术标签:
【中文标题】如何检查服务是不是正在运行[重复]【英文标题】:how to check if service is running or not [duplicate]如何检查服务是否正在运行[重复] 【发布时间】:2013-04-07 09:18:52 【问题描述】:我想显示服务状态,如果它正在运行或停止。我正在使用下面的代码,但它在开始服务之前显示“已停止”。当服务启动时,它显示“正在运行”。当它再次停止时,它只显示“正在运行”。我在设置 sharedPreference 状态时是否犯了任何错误。 在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();
【问题讨论】:
查看***.com/questions/600207/… 【参考方案1】: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
【讨论】:
【参考方案2】: 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
【讨论】:
【参考方案3】: 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;
【讨论】:
我猜这是为了检查互联网连接以上是关于如何检查服务是不是正在运行[重复]的主要内容,如果未能解决你的问题,请参考以下文章
我如何检查运行我的应用程序的 Android 设备是不是在 4.2.2 及更低版本上运行 [重复]