gpt4 book ai didi

java - 修复 Android 8+ 上的 'background service' 问题

转载 作者:行者123 更新时间:2023-12-02 11:01:40 25 4
gpt4 key购买 nike

我有在幕后运行服务的代码。当我们将文本复制到手机时,它被设置为运行。此代码在 Android 8 以下运行良好但问题是当我在 Android 8 及更高版本上运行该应用程序时

在搜索中,我意识到我必须使用 FOREGROUND_SERVICE 并授予对该项目的特定访问权限。

您现在建议什么解决方案?

服务等级:

public class AutoDownloadService extends Service {

private ClipboardManager mClipboardManager;
public static final String CHANNEL_ID = "ForegroundServiceChannel";

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

mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(mOnPrimaryClipChangedListener);
}

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

String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, SettingsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();

startForeground(1, notification);
// stopSelf();
return START_NOT_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(mOnPrimaryClipChangedListener);
}
}

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

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);

NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}

private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
ClipData clip = mClipboardManager.getPrimaryClip();
String textClipBoard = clip.getItemAt(0).getText().toString();
Toast.makeText(AutoDownloadService.this, textClipBoard, Toast.LENGTH_SHORT).show();
}
};
}

list

<service
android:name=".services.AutoDownloadService"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" />
  • 最后添加使用权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

最佳答案

我认为你应该使用Intent Service而不是service。您可以做的是,如果系统关闭您的服务,您可以在使用警报管理器一段时间后再次触发它。

关于java - 修复 Android 8+ 上的 'background service' 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58698595/

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