[英]Android service not restarting in lollipop
在我的应用程序中,我在后台使用基于位置的服务。 因此我需要在销毁时重新启动我的服务。
但是我在logcat中收到了这条消息
ProcessRecord的虚假死亡{320afaf6 20614:com.odoo.crm:my_odoo_gps_service / u0a391},curProc for 20614:null
我的服务onTaskRemoved
@Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
Intent restartServiceIntent = new Intent(App.getAppContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent =
PendingIntent.getService(App.getAppContext(), 1, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService =
(AlarmManager) App.getAppContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
}
我的服务onDestroy
@Override
public void onDestroy() {
System.out.println("destroy service");
super.onDestroy();
wakeLock.release();
}
我的服务onStartCommand
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
我不知道错误是什么。 我在google和stackoverflow中都进行了搜索。 所有这些都引用了Service.START_STICKY 。 但我已经用过了。
相同的服务重启在KitKat中有效,但有一些延迟(约5分钟)。
任何帮助表示赞赏。
您可以使用BroadcasteReceiver
重新启动它, BroadcasteReceiver
处理从您的服务的onDestroy()
发送的广播。
这个怎么做:
StickyService.java
public class StickyService extends Service
{
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
sendBroadcast(new Intent("IWillStartAuto"));
}
@Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("IWillStartAuto"));
}
}
RestartServiceReceiver.java
public class RestartServiceReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context.getApplicationContext(), StickyService.class));
}
}
声明清单文件中的组件 :
<service android:name=".StickyService" >
</service>
<receiver android:name=".RestartServiceReceiver" >
<intent-filter>
<action android:name="IWillStartAuto" >
</action>
</intent-filter>
</receiver>
希望这会帮助你。
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import java.io.File;
import java.io.IOException;
import activity.MainActivity;
import activity.R;
import fragment.MainFragment;
public class MyService extends Service {
public static final int NOTIFICATION_CODE = 1;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(NOTIFICATION_CODE, getNotification());
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
stopForeground(true);
super.onDestroy();
}
@Override
public boolean stopService(Intent name) {
return super.stopService(name);
}
/**
* Create and return a simple notification.
*/
private Notification getNotification() {
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setColor(getResources()
.getColor(R.color.material_deep_teal_500))
.setAutoCancel(true);
notification = builder.build();
notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_AUTO_CANCEL;
return notification;
}
}
您可以修改此代码以满足您的需求,但这是启动前台服务的基本结构。 如果被杀,会重新启动。
你如何检查套接字是否连接的issocketalive? 如果生成了sockettimeoutexception,则尝试设置getinputstream和getoutputstream。 其他问题可能是套接字未正确关闭。 所以,如果可能的话,请将套接字代码放在这
这对我有用
在应用程序标记的清单文件中的android:allowBackup =“false”中添加此属性。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="false"
tools:replace="android:allowBackup">
</application>
</manifest>
在Android中让服务始终在后台运行的想法在99%的时候都是错误的。
系统需要“关闭” CPU,并切换到低电池使用情况。
您说您有基于位置的服务。 我假设您正在使用Google Play服务FusedLocationProvider
,如果不是, 您应该使用 。
FusedLocationProvider
允许您使用PendingIntent
注册位置更改。 这意味着您的服务不需要一直运行,只需要注册位置更改,然后在新位置进行时做出反应并执行其操作。
请参阅FusedLocationProviderApi
官方文档 。
开始侦听位置更新
LocationServices.API
API连接到GoogleClient
LocationRequest
(请参阅文档 ) PendingIntent
版本调用requestLocationUpdates()
停止听
LocationServices.API
API连接到GoogleClient
PendingIntent
调用removeLocationUpdates()
您的PendingIntent可以启动另一个服务来处理新位置。
例如,从服务中执行此操作:
public void startMonitoringLocation(Context context) {
GoogleApiClient client = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.build()
ConnectionResult connectionResult = mApiClient.blockingConnect();
if (connectionResult.isSuccess()) {
LocationServices.FusedLocationApi
.requestLocationUpdates(client, buildLocationRequest(), buildPendingIntent(context));
} else {
handleConnectionFailed(context);
}
}
然后服务可以立即停止。
第一次运行此代码将失败。 与谷歌客户端的连接通常要求用户采取一些行动。 如果是这种情况, ConnectionResult.hasResolution()
方法将返回true。 否则原因是别的,你无法从中恢复。 这意味着您唯一能做的就是通知用户该功能不起作用或有一个很好的后备。
该ConnectionResult.getResolution()
给你PendingIntent
,你需要使用一个Activity
和startIntentSenderForResult()
方法的Activity
,以解决这一意图。 因此,您将创建一个Notification
启动您的Activity
以解决该问题,并最终再次调用您的Service
。
我通常只是开始一项致力于完成所有工作的Activity
。 它更容易,但你不想在其中调用connectBlocking()
。 看看这个怎么做。
您可能会问为什么不直接在Activity
请求位置更新。 这实际上非常好,除非你需要位置监视器自动启动设备,即使用户没有明确打开应用程序。
<receiver android:name=".BootCompletedBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
这样,您可以在重新启动设备时运行服务以连接并请求位置更新。
有关如何构建位置请求的示例:
public LocationRequest buildLocationRequest() {
LocationRequest locRequest = LocationRequest.create();
// Use high accuracy
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// how often do you need to check for the location
// (this is an indication, it's not exact)
locRequest.setInterval(REQUIRED_INTERVAL_SEC * 1000);
// if others services requires the location more often
// you can still receive those updates, if you do not want
// too many consider setting this lower limit
locRequest.setFastestInterval(FASTEST_INTERVAL_SEC * 1000);
// do you care if the user moved 1 meter? or if he move 50? 1000?
// this is, again, an indication
locRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT_METERS);
return locRequest;
}
你未决的意图:
public PendingIntent buildPendingIntent(Context context) {
Intent intent = new Intent(context, LocationUpdateHandlerService.class);
intent.setAction(ACTION_LOCATION_UPDATE);
intent.setPackage(context.getPackageName());
return PendingIntent.getService(context, REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
如果您需要在后台工作,您的LocationUpdateHandlerService
可以是IntentService
:
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(FusedLocationProviderApi.KEY_LOCATION_CHANGED)) {
Location location = extras.getParcelable(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
handleLocationChanged(location);
} else {
Log.w(TAG, "Didn't receive any location update in the receiver");
}
}
}
但也可以是广播或任何适合你的东西。
最后,我在Evernote JobService的帮助下完成了
Github链接 - https://github.com/evernote/android-job
第1步:添加evernote jobservice依赖项
implementation 'com.evernote:android-job:1.3.0-alpha03'
第2步:创建DemoJobCreator.java类
public class DemoJobCreator implements JobCreator {
@Override
@Nullable
public Job create(@NonNull String tag) {
switch (tag) {
case DemoSyncJob.TAG:
return new DemoSyncJob();
default:
return null;
}
}
}
第3步:创建DemoSyncJob.java类
public class DemoSyncJob extends Job {
public static final String TAG = ">>>> job_demo_tag";
@Override
@NonNull
protected Result onRunJob(Params params) {
// run your job here
Log.d(TAG, "onRunJob: ");
if(!isMyServiceRunning(this.getContext(), TestService.class)){
Intent intent=new Intent(context,TestService.class);
context.startService(intent);
}
scheduleJob();
return Job.Result.SUCCESS;
}
public static void scheduleJob() {
new JobRequest.Builder(DemoSyncJob.TAG)
.setExecutionWindow(2_000L, 2_000L)
//.setPeriodic(900000) -> recommended. but it will work after 15 min (if you used this no need scheduleJob(); inside onRunJob();)
.build()
.schedule();
}
public static boolean isMyServiceRunning(Context context, Class<?> serviceClass) {
try {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
}catch (Exception e){
Log.e(TAG, "isMyServiceRunning: ",e );
}
return false;
}
}
第4步:在您的应用程序文件中(如果不可用,创建它)在onCreate()中添加以下行
JobManager.create(this).addJobCreator(new DemoJobCreator());
第5步:最后在您的Activity中启动JobService
DemoSyncJob.scheduleJob();
此JobService将检查服务是否运行(每2秒)如果服务未运行,它将重新启动该服务。
免责声明:这可能不是正确的解决方案。 但它将100%工作。
我希望将来至少可以帮助任何人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.