Служба определения местоположения работает на эмуляторе, но не на телефоне. Что я делаю не так? - PullRequest
0 голосов
/ 26 мая 2020

В телефоне установлена ​​более поздняя версия ОС, которая является android 10 эмулятором android 9, я запускаю внешнее уведомление, и у меня есть необходимые разрешения, однако onStart никогда не вызывается? onCreate делает.

public class LocationService extends Service implements Serializable {

    public static final String TAG = "LocationService";
    private LocationListener locationListener;
    private LocationManager locationManager;
    private static TCLocationEvent tcLocationEvent = new TCLocationEvent();


    @SuppressLint("MissingPermission")
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        startMyOwnForeground();

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onLocationChanged(Location location) {
                buildLocationEvent(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };

        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);


        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, locationListener);


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        return START_STICKY;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startMyOwnForeground() {

        String NOTIFICATION_CHANNEL_ID = "com.waymap.app.traceandroid";
        String channelName = "LocationService";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.GREEN);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(3, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(locationManager != null){
            locationManager.removeUpdates(locationListener);
        }
    }

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



    //mystuff
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void buildLocationEvent(Location location){
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        double[] coordinate = {latLng.latitude, latLng.longitude};
        Log.d("Location", "In location Lat Long: "+ latLng.latitude +" " + latLng.longitude);
        tcLocationEvent.setCoordinate(coordinate);
        tcLocationEvent.setAltitude(location.getAltitude());
        tcLocationEvent.setHorizontalAccuracy(location.getAccuracy());
        tcLocationEvent.setVerticalAccuracy(location.getVerticalAccuracyMeters());
        tcLocationEvent.setTimestamp(location.getTime());

        sendLocationToTraceManager(tcLocationEvent);
    }

    private void sendLocationToTraceManager(TCLocationEvent tcLocationEvent){
        Intent intent = new Intent("locationCreated");
        sendLocalBroadcastEvent(intent, tcLocationEvent);
    }

    private void sendLocalBroadcastEvent(Intent intent, TCLocationEvent tcLocationEvent){
        //Log.d(TAG, "in broadcast "+ tcLocationEvent.getTimestamp());
        intent.putExtra("locationevent", tcLocationEvent);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

}

Я запускаю службу в AsyncTask, вызывая этот метод:

    public void startUpdatingLocation(){
        //Start sensor service
        Intent locationIntent = new Intent(MyApplication.getAppContext(), LocationService.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            MyApplication.getAppContext().startForegroundService(locationIntent);
        } else {
            MyApplication.getAppContext().startService(locationIntent);
        }

    }

И он вызывается так:

        AsyncTask.execute(() -> {
            startUpdatingLocation();
        });

Я правда нужно понять, почему это происходит и как решить проблему?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...