Android-前台在Oreo中不起作用。操作系统在一段时间后终止了服务
我有一个应用程序,它在后台每隔5分钟使用一次定位服务。我们正在前台服务中使用Fusedlocationproviderclient。当应用程序处于打开状态时,它工作正常 当我将应用程序放在后台或从后台滑动以终止时,android 8.0及更高版本上的操作系统会自动终止前台服务 我们在三星note 8、one plus 5t和red mi设备中面临问题 请让我知道如何实现与所有设备兼容的服务 这是我的定位服务课Android-前台在Oreo中不起作用。操作系统在一段时间后终止了服务,android,background-service,locationlistener,foreground-service,google-location-services,Android,Background Service,Locationlistener,Foreground Service,Google Location Services,我有一个应用程序,它在后台每隔5分钟使用一次定位服务。我们正在前台服务中使用Fusedlocationproviderclient。当应用程序处于打开状态时,它工作正常 当我将应用程序放在后台或从后台滑动以终止时,android 8.0及更高版本上的操作系统会自动终止前台服务 我们在三星note 8、one plus 5t和red mi设备中面临问题 请让我知道如何实现与所有设备兼容的服务 这是我的定位服务课 public class TrackingForgroundService e
public class TrackingForgroundService extends Service {
private final long UPDATE_INTERVAL = (long) 2000;
private static final long FASTEST_INTERVAL = 2000;
public BookingTrackingForgroundService() {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
}
}
return START_STICKY;
}
private class TimerTaskToGetLocation extends TimerTask {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
// Call webservice evry 5 minute
}
});
}
}
private void startForegroundService() {
Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.");
context = this;
startLocationUpdates();
notify_interval1 = Prefs.with(this).readLong("notify_interval1", 5000);
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTaskToGetLocation(), 15000, notify_interval1);
mTimer.scheduleAtFixedRate(new TimerTaskToSendCsvFile(), 60000, 1200000);
prefsPrivate = getSharedPreferences(Constants.prefsKeys.PREFS_PRIVATE, Context.MODE_PRIVATE);
internet = new NetConnectionService(context);
Intent notificationIntent = new Intent(this, ActTherapistDashboard.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Geolocation is running")
.setTicker("Geolocation").setSmallIcon(R.drawable.app_small_icon_white)
.setContentIntent(pendingIntent);
Notification notification = builder.build();
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESCRIPTION);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
startForeground(SERVICE_ID, notification);
}
private void stopForegroundService() {
stopLocationUpdates();
Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
if (mTimer != null) {
mTimer.cancel();
} else {
mTimer = null;
}
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
public static boolean isServiceRunningInForeground(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
if (service.foreground) {
return true;
}
}
}
return false;
}
private void startLocationUpdates() {
// create location request object
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// initialize location setting request builder object
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// initialize location service object
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(locationSettingsRequest);
task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
registerLocationListner();
}
});
}
private void registerLocationListner() {
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
onLocationChanged(locationResult.getLastLocation());
}
};
//location permission
LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, locationCallback, null);
}
private void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latitudeTemp = latitude;
longitudeTemp = longitude;
}
}
}
公共类TrackingForgroundService扩展了服务{
私有最终长更新间隔=(长)2000;
专用静态最终长最快_间隔=2000;
公共预订跟踪ForGroundService(){
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
if(intent!=null){
String action=intent.getAction();
开关(动作){
案例行动\启动\前台\服务:
startForegroundService();
打破
案例行动\停止\前台\服务:
stopForegroundService();
打破
}
}
返回开始时间;
}
私有类TimerTaskToGetLocation扩展了TimerTask{
@凌驾
公开募捐{
mHandler.post(新Runnable(){
@凌驾
公开募捐{
//每5分钟给webservice打一次电话
}
});
}
}
私有void startForegroundService(){
Log.d(标记前台服务,“启动前台服务”);
上下文=这个;
startLocationUpdates();
notify_interval1=带(this).readLong的前缀(“notify_interval1”,5000);
mTimer=新计时器();
mTimer.scheduleAtFixedRate(新的TimerTaskToGetLocation(),15000,通知间隔1);
mTimer.scheduleAtFixedRate(新的TimerTaskToSendCsvFile(),60000120000);
prefsPrivate=getSharedReferences(Constants.prefskys.PREFS_PRIVATE,Context.MODE_PRIVATE);
internet=新的NetConnectionService(上下文);
Intent notificationIntent=新意图(此,ActTherapistDashboard.class);
notificationIntent.setFlags(Intent.FLAG_活动_清除_任务| Intent.FLAG_活动_新任务);
PendingEvent PendingEvent=PendingEvent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder=新建NotificationCompat.Builder(此,通道ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(“地理定位正在运行”)
.setTicker(“地理定位”).setSmallIcon(R.drawable.app\u small\u icon\u white)
.setContentIntent(挂起内容);
通知通知=builder.build();
如果(Build.VERSION.SDK_INT>=26){
NotificationChannel=new NotificationChannel(频道ID、频道名称、NotificationManager.IMPORTANCE\u默认值);
channel.setDescription(通道描述);
NotificationManager NotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION\u服务);
notificationManager.createNotificationChannel(频道);
}
startForeground(服务ID、通知);
}
私有void stopForegroundService(){
stopLocationUpdates();
Log.d(标记前台服务,“停止前台服务”);
如果(mTimer!=null){
mTimer.cancel();
}否则{
mTimer=null;
}
//停止前台服务并删除通知。
停止前景(真);
//停止前台服务。
stopSelf();
}
公共静态布尔值IsServiceRunningForeground(上下文上下文,类serviceClass){
ActivityManager=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
对于(ActivityManager.RunningServiceInfo服务:manager.getRunningServices(Integer.MAX_值)){
if(serviceClass.getName().equals(service.service.getClassName())){
if(服务前台){
返回true;
}
}
}
返回false;
}
private void startLocationUpdates(){
//创建位置请求对象
mLocationRequest=LocationRequest.create();
mLocationRequest.setPriority(位置请求.优先级高精度);
mLocationRequest.setInterval(更新间隔);
mLocationRequest.SetFastTestInterval(最快间隔);
//初始化位置设置请求生成器对象
LocationSettingsRequest.Builder=新建LocationSettingsRequest.Builder();
builder.addLocationRequest(mlLocationRequest);
LocationSettingsRequest LocationSettingsRequest=builder.build();
//初始化位置服务对象
SettingsClient SettingsClient=LocationServices.getSettingsClient(此);
任务任务=设置客户端。检查位置设置(位置设置请求);
task.addOnSuccessListener(新的OnSuccessListener(){
@凌驾
成功时公共无效(位置设置响应位置设置响应){
registerLocationListner();
}
});
}
私有无效注册表LocationListner(){
locationCallback=新locationCallback(){
@凌驾
public void onLocationResult(LocationResult LocationResult){
super.onLocationResult(定位结果);
onLocationChanged(locationResult.getLastLo