2016-02-28 52 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%活跃,请使用前台服务。无论如何,前台服务需要始终显示的通知。