Почему фоновая служба не работает, когда приложение закрывается ниже версий oreo? - PullRequest
0 голосов
/ 18 февраля 2019

В моем коде я создал класс обслуживания для обновления местоположения пользователя.Если обновленный код местоположения работает нормально в версиях, превышающих Oreo, но в других версиях ниже, чем oreo, мой сервис не работает, когда приложение закрыто.

Вот мой класс обслуживания:

package com.pwt.schoolapp.LocationService;



 public class GpsLocationService extends Service {


SessionManager sm = null;
String token = "";
String id = "";
static final int NOTIFICATION_ID = 543;
public static boolean isServiceRunning = false;
@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        startMyOwnForeground();
    }

    else{
        startServiceWithNotification();
    }

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

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

    String NOTIFICATION_CHANNEL_ID = "my_package_name";
    String channelName = "My Background Service";
    NotificationChannel chan = new 
   NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, 
   NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    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)
            .setSmallIcon(R.drawable.arrow)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    startForeground(2, notification);

}
@TargetApi(Build.VERSION_CODES.ECLAIR)
@RequiresApi(api = Build.VERSION_CODES.ECLAIR)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    sm = new SessionManager(getApplicationContext());
    token = sm.getToken();
    token = sm.getToken();
    id = sm.getVehicle().getId();
    Log.e("sss",""+"ssst");
    if (!currentlyProcessingLocation) {
        currentlyProcessingLocation = true;
        startTracking();
    }
    return START_NOT_STICKY;
}
 private void startServiceWithNotification() {
    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText("App running in background")
            .setSmallIcon(R.drawable.arrow)
            .setOngoing(true)
            .build();
    startForeground(NOTIFICATION_ID, notification);
}
@SuppressLint("MissingPermission")
private void startTracking() {
}

@SuppressLint("MissingPermission")
protected void sendLocationDataToWebsite(Location location) {
}

@Override
public void onDestroy() {
    super.onDestroy();

    stopSelf();
    Log.e("gpsstopsucess",""+"stopsucess");

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
public class GpsListener implements LocationListener
{

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            if(DefaultSetting.isInternetConncted(GpsLocationService.this))
            {




                sendLocationDataToWebsite(location);
                Log.e("tokennull123","" + "notnull");






            }
            else
            {

                //DataSever.saveInFIle(location,GpsLocationService.this,file);
            }
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

}
}

И вот мой класс приемника.С этого момента я запускаю службу

   public class GpsTrackerAlarmReceiver extends WakefulBroadcastReceiver {
    private static final String TAG = "GpsTrackerAlarmReceiver";

    @Override
    public void onReceive(Context context, Intent intent) { 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(new Intent(context, 
       GpsLocationService.class));
                Log.e("start",""+"newgps");
            } else {
                context.startService(new Intent(context, 
       GpsLocationService.class));
                Log.e("start",""+"gps");
            }
  }
}

Служба всегда запускается в версиях 8.0.1 и 9.0.0, но не работает ниже 8.0.1.В чем проблема?

...