在更新的Android版本中,为了让Android ForegroundService无限期运行,可以采取以下步骤:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
public class MyForegroundService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Service is running...")
.setSmallIcon(R.drawable.ic_notification)
.build();
startForeground(NOTIFICATION_ID, notification);
}
// 创建通知渠道
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
// 其他服务逻辑...
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
以上是让Android ForegroundService在更新的Android版本中无限期运行的方法。请注意,这些方法适用于大多数Android设备,但并不保证在所有设备上都能完全避免被系统杀死。
云+社区沙龙online[数据工匠]
Elastic 中国开发者大会
DBTalk
云+社区技术沙龙[第11期]
DB・洞见
DB TALK 技术分享会
云+社区技术沙龙[第14期]
企业创新在线学堂
领取专属 10元无门槛券
手把手带您无忧上云