关闭手机并重新启动时。我想在我的共享偏好上存储一些数据。我想在我的服务onDestroy上做这个。但是当我重新启动手机或将其关闭再打开时,它似乎没有存储。这是我如何做到的。同样,这是一项服务。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
preferences = getSharedPreferences(pref_data, Context.MODE_PRIVATE);
driverPassword = preferences.getString("driverPassword","");
carrierId = preferences.getString("carrierId","");
cctid = preferences.getString("CCTID","");
shipment = preferences.getString("shipment","");
try
{
JSONObject shipmentObject = new JSONObject(shipment);
shipmentID = shipmentObject.getString("ShipmentId");
}
catch(Exception e)
{
}
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
handler.removeCallbacks(sendWakeLock);
handler.postDelayed(sendWakeLock, 1000); // 1 second
Log.w("onStart", "onStart");
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy(){
super.onDestroy();
Log.w("onDestroy", "onDestroy");
handler.removeCallbacks(sendWakeLock);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("isDriverLogin", "True");
editor.putString("driverPassword", driverPassword);
editor.putString("carrierId", carrierId);
editor.putString("CCTID", cctid);
editor.putString("shipment", shipment);
editor.putString("isAccepted", "");
editor.putString("newshipment", "");
editor.putString("isRemoved", "True");
editor.commit();
}
注意:我的活动onDestroy方法还有其他重要活动,我不想使用它。如果手机重新启动,我想利用我服务中发生的事件。我还设置了Service.START_NOT_STICKY;希望当手机重启或关闭时,它会执行我的onDestroy。关于在重新启动手机时我应该如何在我的服务上捕获事件或在我重新启动手机时停止服务的任何想法?
答案 0 :(得分:0)
在较新的版本中,服务将触发以下事件:
onCreate()
Followed by...
int onStartCommand(Intent intent, int flags, int startid)
//确定我的某个服务当前是否正在运行
public static boolean isMyServiceRunning(Context context, String servicename) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (servicename.equals(service.service.getClassName())) {
return true;
}
}
return false;
}