2016-06-28 33 views
0

我的應用程序中有以下設計:我有一個設置重複鬧鐘的活動,啓動啓動我的服務的接收器。每一分鐘。在我的服務中,我設置了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; 
} 

任何想法如何解決這個問題?

回答

0

您很可能看到與電源管理和警報的交互。從API 19開始,所有報警默認爲不確切,因此它們將與其他報警進行比較。此外,一旦設備進入較低功率狀態,則警報將被傳送到BroadcastReceivers,並且只要接收機正在執行其方法,設備就保證保持清醒。一旦它從該方法返回(以及與警報運行相關的任何其他BroadcastReceiver),設備將立即再次進入低功率狀態。由於您的應用程序之前已被殺害,Service不再運行,並且不會獲得CPU時間。

解決此問題的方法是使用WakefulReceiver,它在運行時需要喚醒鎖定onReceive(),開始處理ServiceService將在完成處理後釋放喚醒鎖。本文將給你一個很好的解釋:http://po.st/7UpipA

請注意,每分鐘醒來都會嚴重降低設備的電池壽命,所以你應該考慮支持這一點。

+0

非常感謝。但是,我認爲我使用AlarmManager.setExact()解決了這個問題,因此每次在OnStartCommand中啓動服務時都會設置警報 – Traabefi

+0

如果您沒有按照說明管理喚醒鎖,則最終還是會遇到電源管理問題。 –

+0

獲取服務中的喚醒鎖和BroadcastReceiver有什麼區別嗎? – Traabefi