问题描述
一旦清除应用程序,Android 服务就会停止。 即使用户清除了所有应用程序,我也需要一个在后台持续运行的服务。 我为启动服务创建了警报。
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Alarm","Alarm receive");
Intent i=new Intent(context,GetLocationService.class);
context.startService(i);
}
}
我的服务文件
public class GetLocationService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(),"calling Get Location service", Toast.LENGTH_LONG).show();
//service code here
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Service","Service destroy");
}
}
清单文件
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GetLocationService" android:stopWithTask="false" android:exported="false" />
<receiver android:name=".AlarmReceiver" android:enabled="true" />
</application>
现在我需要跟踪移动位置,即使活动销毁..但在我的情况下,一旦我清除了应用程序,我的服务就会被销毁,而没有执行 destroy 方法。
我已经阅读了关于STICKY_INTENT
但它对我不起作用。
1楼
你应该看看JobScheduler
这里有一些参考。
2楼
在服务中使用stopSelf()
来销毁服务
绑定服务文档
服务连接文档
示例绑定和服务连接
3楼
这是只是解决我不支持它的代码。 因此,如果您的服务停止,它可以通过在广播接收器中注册来重新启动。 把这个放在你的清单上
<receiver android:name=".RestartTrigger">
<intent-filter>
<action android:name="donotkill" />
</intent-filter>
</receiver>
只需添加这个类
public class RestartTrigger extends BroadcastReceiver {
private static final String TAG = "RestartServiceReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive");
Intent intent1 = Intent(context,GetLocationService.class);
context.startService(intent1);
}
}
在服务中添加这个
@Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("donotkill"));
}
在 Manifest 中,您应该将您的服务作为单独的进程添加android:process=":name_of_process"
<service android:name=".GetLocationService" android:stopWithTask="false" android:process=":name_of_process" android:exported="true" android:enabled="true" />
而且我不支持这种代码。 这将对用户造成危害。