Java Context.startForgroundService()随后未调用Service.Forground
如果设备操作系统是Android 9(Pie),我已经调用了Context.startForgroundService(),但有时它会抛出类似“Context.startForgroundService()然后没有调用Service.forgfround”的错误,我还为forgfround服务Android.permission授予了权限。前台服务的问题仍然没有得到解决Java Context.startForgroundService()随后未调用Service.Forground,java,android,service,Java,Android,Service,如果设备操作系统是Android 9(Pie),我已经调用了Context.startForgroundService(),但有时它会抛出类似“Context.startForgroundService()然后没有调用Service.forgfround”的错误,我还为forgfround服务Android.permission授予了权限。前台服务的问题仍然没有得到解决 if (!isMyServiceRunning(Service.class)){ startServi
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();
}
前台服务的问题是它应该在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);
}
}
看见
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
}
...
}