在Android9.0中會默認禁止後臺繼續執行任務操作,例如 Android 9 設備用戶有鎖屏後採集音頻或視頻的需求,可以在鎖屏或退至後臺前起一個 Service,並在退出鎖屏或返回前臺前終止 Service
具體代碼如下
public class KeepAppLifeService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private NotificationManager notificationManager;
private String notificationId = "keepapplifeid";
private String notificationName = "keepapplifename";
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//創建NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
startForeground(1, getNotification());
}
private Notification getNotification() {
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("招商銀行")
.setContentText("後臺運行中");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(notificationId);
}
return builder.build();
}
}