Android 当应用程序不在前台时服务停止工作
Android Service stops working, when app isn't on the foreground
我有一个小问题:
我从服务接收到 LocationListener 给出的速度值。但是当我关闭我的应用程序的 ui 时,locationlistener 停止发送更新。有谁知道该怎么做?我需要它来继续更新,即使该应用程序未在使用中...
这是我的代码:
public class BackroundService extends Service {
//initializing the Location Manager and Listener
LocationManager locationManager;
LocationListener locationListener;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Instantiating the device manager an listener
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
return START_STICKY;
}
}
class MyLocationListener extends Service implements LocationListener
{
public float speed;
public void onLocationChanged(final Location location)
{
//when the location changed
Log.d("Location", ""+location);
Log.d("Float Location", ""+ location.getLongitude() + " " + location.getLatitude());
Log.d("Speed", " "+location.getSpeed());
//initializing the variable speed with the speed number given by the LocationListener
speed = location.getSpeed();
//creating a broadcast reciever
Intent intent = new Intent("speed_update");
intent.putExtra("speed", speed);
//sending speed to main activity
sendBroadcast(intent);
//checking if speed is in walking range
if (speed < 4.0 && speed > 0.4){
Log.d("######Checker######", "++++++++++turn off+++++++++++");
//Toast.makeText(MyLocationListener.this, "turn off", Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
从奥利奥开始,android后台政策发生了重大变化,请参阅此https://developer.android.com/about/versions/oreo/background了解更多详情,
为了避免您的服务被 android 杀死,您必须 运行 它作为前台服务
第 1 步:向清单文件添加权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
这里有关于此权限的更多详细信息https://developer.android.com/reference/android/Manifest.permission#FOREGROUND_SERVICE
第 2 步:创建服务,我为您分享示例代码
public class DemoService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SSB Log", "onStartCommand");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// For foreground service
Intent notificationIntent = new Intent(this, DemoService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// Creating channel for notification
String id = DemoService.class.getSimpleName();
String name = DemoService.class.getSimpleName();
NotificationChannel notificationChannel = new NotificationChannel(id,
name, NotificationManager.IMPORTANCE_NONE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(notificationChannel);
// Foreground notification
Notification notification = new Notification.Builder(this, id)
.setContentTitle(getText(R.string.app_name))
.setContentText("Show service running reason to user")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker("Ticker text")
.build();
startForeground(9, notification);
}
// Service logic here
return Service.START_NOT_STICKY;
}
}
第 3 步:在清单中声明服务
<service android:name=".DemoService" />
第 4 步:从 activity
开始服务
Intent startDemoService = new Intent(this,DemoService.class);
startService(startDemoService);
我有一个小问题: 我从服务接收到 LocationListener 给出的速度值。但是当我关闭我的应用程序的 ui 时,locationlistener 停止发送更新。有谁知道该怎么做?我需要它来继续更新,即使该应用程序未在使用中...
这是我的代码:
public class BackroundService extends Service {
//initializing the Location Manager and Listener
LocationManager locationManager;
LocationListener locationListener;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Instantiating the device manager an listener
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
return START_STICKY;
}
}
class MyLocationListener extends Service implements LocationListener
{
public float speed;
public void onLocationChanged(final Location location)
{
//when the location changed
Log.d("Location", ""+location);
Log.d("Float Location", ""+ location.getLongitude() + " " + location.getLatitude());
Log.d("Speed", " "+location.getSpeed());
//initializing the variable speed with the speed number given by the LocationListener
speed = location.getSpeed();
//creating a broadcast reciever
Intent intent = new Intent("speed_update");
intent.putExtra("speed", speed);
//sending speed to main activity
sendBroadcast(intent);
//checking if speed is in walking range
if (speed < 4.0 && speed > 0.4){
Log.d("######Checker######", "++++++++++turn off+++++++++++");
//Toast.makeText(MyLocationListener.this, "turn off", Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
从奥利奥开始,android后台政策发生了重大变化,请参阅此https://developer.android.com/about/versions/oreo/background了解更多详情, 为了避免您的服务被 android 杀死,您必须 运行 它作为前台服务
第 1 步:向清单文件添加权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
这里有关于此权限的更多详细信息https://developer.android.com/reference/android/Manifest.permission#FOREGROUND_SERVICE
第 2 步:创建服务,我为您分享示例代码
public class DemoService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SSB Log", "onStartCommand");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// For foreground service
Intent notificationIntent = new Intent(this, DemoService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// Creating channel for notification
String id = DemoService.class.getSimpleName();
String name = DemoService.class.getSimpleName();
NotificationChannel notificationChannel = new NotificationChannel(id,
name, NotificationManager.IMPORTANCE_NONE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(notificationChannel);
// Foreground notification
Notification notification = new Notification.Builder(this, id)
.setContentTitle(getText(R.string.app_name))
.setContentText("Show service running reason to user")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker("Ticker text")
.build();
startForeground(9, notification);
}
// Service logic here
return Service.START_NOT_STICKY;
}
}
第 3 步:在清单中声明服务
<service android:name=".DemoService" />
第 4 步:从 activity
开始服务Intent startDemoService = new Intent(this,DemoService.class);
startService(startDemoService);