1

我正在开发一个需要通过 GPS 跟踪用户的应用程序。我正在使用服务来控制位置,但是当我关闭应用程序并杀死它时,服务停止。我尝试使用通知栏连接服务,但问题仍然存在。我已经尝试了很多我在几篇文章中阅读过的解决方案,但我无法根据需要保持它的活力。我的目的是让服务一直运行,即使应用程序被终止。我不知道这是否可能。

在 mainActivity 我正在启动服务:

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

位置服务类:

 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;
}
}
4

0 回答 0