即使应用程序被杀,也要继续跟踪前台服务

时间:2016-10-04 14:50:51

标签: android service kill-process foreground-service

我正在开发一款应用,我需要通过GPS跟踪用户。我正在使用服务来控制位置,但是当我关闭应用程序并将其杀死时,服务就会停止。我试图将服务与通知栏连接,但问题仍然存在。我已经尝试了很多我在几篇文章中读过的解决方案,但我不能保持活着,因为我需要。我的目的是让服务始终保持运行,即使应用程序被杀死也是如此。我不知道这是否可能。

在mainActivity中,我正在启动服务:

 private void iniciarServicioGPS() {
        Intent service = new Intent(this, LocationService.class);
        startService(service);
}

LocationService.class:

 public class LocationService extends Service {
 Intent intent;
@Override
public void onCreate() {
    super.onCreate();
    Log.i("GPS", "onCreate");
    intent = new Intent(BROADCAST_ACTION);
}
@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void start (Intent intent, int startId){
    Log.i("GPS", "onStart antes location manager");
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();        
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}

 public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("gps", "Received Start Foreground Intent ");
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.drawable.amu_bubble_mask);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("ELE")
            .setTicker("ELE")
            .setContentText("Servicio de tracking activo")
            .setSmallIcon(R.drawable.amu_bubble_mask)
            .setLargeIcon(
                    Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build();

    startForeground(Notification.FLAG_ONGOING_EVENT,notification);

    return START_REDELIVER_INTENT;
}
}

0 个答案:

没有答案