我想显示服务状态,如果它正在运行或停止。我正在使用下面的代码,但它在开始服务之前显示“已停止”。当服务启动时,它显示“正在运行”。当它再次停止时,它只显示“正在运行”。我在设置 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();
}