Context.startForgroundService () тогда не вызывал Service.Forground - PullRequest
0 голосов
/ 15 октября 2019

Я вызвал Context.startForgroundService (), если os устройства - это Android 9 (Pie), но иногда выдает ошибку типа " Context.startForgroundService (), тогда не вызывал Service.Forground ", у меня также естьдать разрешение на наземное обслуживание android.permission.FOREGROUND_SERVICE проблема по-прежнему не решена.

if (!isMyServiceRunning(Service.class)){
            startService();
        }

private void startService() {
        System.out.println("Start Service");
        Thread t = new Thread("StartService") {
            public void run() {
                Intent serviceIntent = new Intent("com.demo.demo.start_service");
                serviceIntent.setPackage("com.demo.demo");
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        getApplicationContext().startForegroundService(serviceIntent);

                    } else {
                        getApplicationContext().startService(serviceIntent);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        };
        t.start();
    }

Ответы [ 2 ]

0 голосов
/ 15 октября 2019
Android Oreo 8.0 Documentation properly somewhere in here, you might not have posted this question here.

Step 1: Make sure you start a service as a foreground Service as given in below code

ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), 
GpsServices.class));
 ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), 
BluetoothService.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), 
BackgroundApiService.class));
Step 2: Use notification to show that your service is running. Add below line of code 
in onCreate method of Service.

@Override
public void onCreate() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForeground(NOTIFICATION_ID, notification);
}
...
}
Step 3: Remove the notification when the service is stopped or destroyed.

@Override
public void onDestroy() {
...
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      stopForeground(true); //true will remove notification
}
...
}
0 голосов
/ 15 октября 2019

проблема с сервисом переднего плана состоит в том, что он должен запуститься в течение 5 секунд, иначе вы обнаружите эту ошибку. Теперь я поделился с вами этим методом, который я использую в своем методе класса обслуживания ONCREATE. Я надеюсь, что вы найдете это полезным.

void CheckOSversion()
    {
        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("")
                    .build();

            startForeground(002, notification);
        }

    }
...