我的應用程序中有以下設計:我有一個設置重複鬧鐘的活動,啓動啓動我的服務的接收器。每一分鐘。在我的服務中,我設置了Start Sticky,但是一旦Android決定終止我的服務,我無法重新啓動它。這是Android 4.4.2你能幫我嗎?這裏是我的代碼:不斷的服務設計android
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, i1, PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, 0, 60 * 1000, pi);
}
這裏是接收器
public void onReceive(Context arg0, Intent arg1) {
// For our recurring task, we'll just display a message
Log.d(Constants.TAG, "Starting Service");
Intent intent = new Intent(arg0, MyLocationService.class);
arg0.startService(intent);
}
和服務:
private static PowerManager.WakeLock wl;
private static OkHttpClient client;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Constants.TAG, "Service onStartCommand");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
wl.acquire();
client = new OkHttpClient();
new GetLocation(MyLocationService.this).execute();
return START_STICKY;
}
任何想法如何解決這個問題?
非常感謝。但是,我認爲我使用AlarmManager.setExact()解決了這個問題,因此每次在OnStartCommand中啓動服務時都會設置警報 – Traabefi
如果您沒有按照說明管理喚醒鎖,則最終還是會遇到電源管理問題。 –
獲取服務中的喚醒鎖和BroadcastReceiver有什麼區別嗎? – Traabefi