2016-02-28 31 views
-1

我想製作一個應用程序,其中我的音頻配置文件模式根據位置發生更改。爲此我總是需要在背景中檢查位置。我如何在後臺執行此操作?在什麼地方我的實際位置獲取和服務類中的比較代碼以及何時啓動我的服務類?想了解Android的服務等級

+0

使用IntentService並在特定的時間段後設置PendingIntent。然後,您可以像在活動中那樣請求位置更新,獲取經度和緯度,並將其保存到SharedPreferences中。然後,從您的活動訪問SharedPreferences並根據需要執行任何操作。 –

+0

我怎樣才能設置pendingIntent? –

+0

如果我使用IntentService,則Service類的行爲在完成定義任務後停止。我想在不停止服務的情況下檢查位置 –

回答

0

下面是一個IntentService示例,每5分鐘重新啓動一次。

public class MyIntentService extends IntentService { 

    int updateVal; 

    public MyIntentService() { 
     super("MyIntentService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

    // your code here. Request location updates here. 

    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onDestroy() { 

     //minutes after which the service should restart 
     updateVal = 5; 

     AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE); 

     //This is to incorporate Doze Mode compatibility on Android M and above. 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
      alarm.setAndAllowWhileIdle(
        alarm.RTC_WAKEUP, 
        System.currentTimeMillis() + (1000 * 60 * updateVal), 
        PendingIntent.getService(this, 0, new Intent(this, MyIntentService.class), 0) 
      ); 

     //For all other versions. 
     else 
      alarm.set(
        alarm.RTC_WAKEUP, 
        System.currentTimeMillis() + (1000 * 60 * updateVal), 
        PendingIntent.getService(this, 0, new Intent(this, MyIntentService.class), 0) 
      ); 
    } 
} 

在您的主要活動中,鍵入此代碼以啓動該服務。

startService(new Intent(this, MyIntentService.class)); 

您必須實現LocationListener並獲取我沒有添加到代碼中的位置更新。

如果您確實希望啓動永不停止的服務,則需要擴展Service類而不是IntentService類。在Android開發者指南中有很好的解釋:http://developer.android.com/guide/components/services.html

+0

感謝提供示例... :-) –

+0

謝謝,它適用於我... –

0

使用在onStartCommand()函數中返回「START_STICKY」的服務。您的服務在被系統殺死後會再次重新啓動。但有時候,它不會重新啓動。要使您的服務100%活躍,請使用前臺服務。無論如何,前臺服務需要始終顯示的通知。