[英]Background Service for update location in background
它會殺死后台服務,要解決您的問題,您應該使用前台服務。
我的后台粘性服務在奧利奧和更高的設備上被殺死 任何用於在 Activity 處於后台時獲取后台服務位置的解決方案
由於行為發生變化,您將無法在 Oreo 中長時間運行后台服務,現在 Oreo 可以優化系統內存、電池等,它會終止后台服務,為了解決您的問題,您應該使用前台服務。
看看后台執行限制https://developer.android.com/about/versions/oreo/android-8.0-changes
我的一個建議,如果你可以使用 FCM,那就去吧,因為像微信、Facebook 這樣的應用程序使用它來發送通知,他們不會遇到任何問題。
由於客戶端要求運行在后台更新位置的服務,我選擇了不使用 FCM 的替代解決方案。 以下是以下步驟:-
希望你們多做一些研發工作。 我分享了我的經驗和我在后台運行服務的過程。
這是因為 Android Oreo 的后台執行行為發生了變化。 建議的替代方案是
1)前台服務。
如果您在嘗試使用 Location API 檢索位置時可以向用戶顯示通知,請使用此選項。 這將是可靠的,並在文檔中建議。
文檔中的示例應用程序:GitHub 上的LocationUpdatesForegroundService項目
一個應用程序示例,該應用程序允許應用程序繼續執行用戶啟動的操作,而無需請求始終訪問后台位置。
References
https://developer.android.com/training/location/receive-location-updates
2) 工作經理
這種方法不太可靠,因為您將無法控制何時確切地調用它,但是如果您根本不想向用戶顯示通知,則可以使用它。
您必須顯示 ForegroundService 的通知
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.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_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
並添加權限
<uses-permissionandroid:name=”android.permission.FOREGROUND_SERVICE” />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.