gpt4 book ai didi

java - 前台服务在 Android 9 (API 28) 中不起作用

转载 作者:行者123 更新时间:2023-12-01 23:46:43 25 4
gpt4 key购买 nike

我想要一个前台服务,我编写了代码。但问题是该应用程序在 API 26 及更低版本上运行良好,但在 API 28 上运行不佳。API 28 中的问题是它作为后台服务运行,如果您关闭应用程序,服务也会关闭。这是我的代码:我的服务:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.widget.Toast;

public class MyService extends Service {

private Context context = null;
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "ChargeScreenService";

private Looper serviceLooper;
private ServiceHandler serviceHandler;
private BatteryBroadCast batteryBroadCast;
private NotificationManager notificationManager;
private Notification notification;

// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
batteryBroadCast = new BatteryBroadCast(MyService.this);
batteryBroadCast.chargingChanges();
}
});
thread.start();
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
//stopSelf(msg.arg1);
}
}

@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work doesn't disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);

thread.start();

// Get the HandlerThread's Looper and use it for our Handler
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

createNotificationChannel();

Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Hi")
.setContentText("Hello")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.setTicker("HI")
.setOngoing(true)
.build();

notificationManager.notify(NOTIFICATION_ID, notification);
} else {
notification = new Notification.Builder(this)
.setContentTitle("Hi")
.setContentText("Hello")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.setTicker("HI")
.setOngoing(true)
.build();
}

startForeground(1, notification);

Message msg = serviceHandler.obtainMessage();
msg.arg1 = startId;
serviceHandler.sendMessage(msg);

// If we get killed, after returning from here, restart
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}

@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
super.onDestroy();
}

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ChargeScreenService";
String description = "Service";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}

主要 Activity :

...
startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}

}
});
...

最后,我在AndroidManifest文件中添加了权限。 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />并定义了我的服务。

<service
android:name=".MyService"
android:enabled="true" />

测试设备:三星 Galaxy J7 Pro(型号:SM-J730F)(真实设备)虚拟设备:Genymotion Android 6

最佳答案

如果您的应用面向 API 级别 26 或更高级别,则当应用本身不在前台时,系统会对运行后台服务施加限制。在大多数情况下,您的应用应该使用计划作业。

关于java - 前台服务在 Android 9 (API 28) 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com