我知道可能永远不会调用Service的onDestroy()方法,但是有人可以告诉我何时会出现这种情况?我特别感兴趣的是服务是否可能被杀死,但它的VM将继续运行.
我问,因为我有一个服务在服务的onStartCommand()方法中注册ContentObservers并取消注册它们onDestroy().如果从未调用过该服务的onDestroy()方法,因为整个虚拟机(以及它创建的观察者)都被杀死了.但我不知道是否有可能为一个服务"走开"没有的onDestroy()被调用,而它创造的观察员将生活和继续得到改变.
我想显示服务状态,如果它正在运行或停止.我使用下面的代码,但它在启动服务之前显示"已停止".当服务启动时,它显示"正在运行".当它再次停止时,它只显示"正在运行".我在设置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();
}
Run Code Online (Sandbox Code Playgroud)