onHandle完成后,带有位置更新的Android前台服务将被终止

时间:2017-06-18 12:12:04

标签: android service

我想显示持久性通知我的位置牵引服务,但是一旦onHandleIndent完成,服务就会被杀死,有一个定时获取位置的时间,

我的问题是, 如果onStartCommand没有返回START_STICKY,它的工作正常。但在这种情况下,通知没有出现。

我希望我的服务能够通过持久性通知永远运行。

这是我的班级

public class TrackLocation extends IntentService {

    public static final String START_TRACKING = "START_TRACKING";
    public static final String STOP_TRACKING = "STOP_TRACKING";
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; 
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 10000;
    double totalDistance = 0;
    Location locationFirstOld;
    protected LocationManager locationManager;
    static double n = 0;
    Long s1, r1;
    double plat, plon, clat, clon, dis;
    Thread t1;
    EditText e1;
    boolean bool = true;
    private String booking_id;
    private FusedLocationProviderClient mFusedLocationClient;
    public static boolean  isTrackingEnabled;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     */
    public TrackLocation() {
        super("Distance tracking service");

    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String action = intent.getAction();

        if (action.equals(START_TRACKING)) {
            isTrackingEnabled = true;
             booking_id = intent.getStringExtra("booking_id");
            startTracking();
        } else {
            isTrackingEnabled = false;
        }
    }
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        super.onStartCommand(intent, startId, startId);

        return START_STICKY;
    }


    private void startTracking() {
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (isTrackingEnabled) {
                    Log.d("tracking", "run: " + new Date().toString());
                    getLocation();
                } else {
                    timer.cancel();

                }
            }
        };
        timer.schedule(timerTask,0,5000);
        Intent notificationIntent = new Intent(this, PickaupActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,
                notificationIntent, 0);

        Notification notification = new Notification.Builder(this)
                .setContentTitle("On going trip")
                .setContentText("Active trips")
                .setSmallIcon(R.drawable.ic_notification_auto_request)
                .setContentIntent(pendingIntent)
                .setTicker("Trip started")
                .build();

        startForeground(1337, notification);

    }

    private void getLocation() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mFusedLocationClient.getLastLocation().addOnSuccessListener( new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {

                    Log.d("", "onSuccess: " + location.getLatitude());
                    submitData(location);
                }
            }
        });
    }

    private void submitData(Location location) {
        if (locationFirstOld == null) {
            locationFirstOld = location;
            return;
        }
//        sendMyLocation(location);

//        double distance = getDistance(locationFirstOld.getLatitude(), locationFirstOld.getLongitude(), location.getLatitude(), location.getLongitude());
        double distance = locationFirstOld.distanceTo(location);
        Log.d("distance", "submitData: " + String.valueOf(distance));
        locationFirstOld = location;

        sendMessageToActivity(totalDistance);

        totalDistance += distance;



    }



    public double getDistance(double lat1, double lon1, double lat2, double lon2) {
        double latA = Math.toRadians(lat1);
        double lonA = Math.toRadians(lon1);
        double latB = Math.toRadians(lat2);
        double lonB = Math.toRadians(lon2);
        double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
                (Math.sin(latA) * Math.sin(latB));
        double ang = Math.acos(cosAng);
        double dist = ang *6371;
        return dist;
    }
    private  void sendMessageToActivity(double distance) {
        Intent intent = new Intent("DISTANCE_UPDATE");
        // You can also include some extra data.
        intent.putExtra("distance", distance);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    private void sendMyLocation(Location location) {
        Intent intent = new Intent();
        intent.putExtra("lat", location.getLatitude());
        intent.putExtra("lat", location.getLongitude());
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    }

2 个答案:

答案 0 :(得分:0)

  

一旦onHandleIndent完成

,服务就会被杀死

这是IntentService的标准行为 - IntentServicestopSelf()返回时调用onHandleIntent(),如果没有更多的排队命令。

请勿在此方案中使用IntentService。使用您自己的线程模型创建自己的服务,当您不再需要该服务时调用stopSelf()

答案 1 :(得分:0)

当IntentService执行任何操作时都会停止。

使用服务,服务类型不会停止,直到系统,用户或应用程序停止它