Din*_*uka 3 service android android-service
service即使应用程序从任务管理器关闭,我也希望创建一个运行.我创建了一个服务,然后记录了一条消息以检查它是否正在运行,我注意到它只有在应用程序运行或处于前台时才有效.
服务类:
public class CallService extends Service {
private final LocalBinder mBinder = new LocalBinder();
protected Handler handler;
public class LocalBinder extends Binder {
public CallService getService() {
return CallService .this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TESTINGSERVICE", "Service is running");
}
}
Run Code Online (Sandbox Code Playgroud)
从我的MainActivity启动服务:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
startService(new Intent(this, CallService.class));
Run Code Online (Sandbox Code Playgroud)
表现
<application>
...
<service
android:name=".activities.services.CallService">
</service>
</application>
Run Code Online (Sandbox Code Playgroud)
我需要做些什么改变?谢谢,伙计们
小智 11
在您的服务中,添加以下代码.
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4826 次 |
| 最近记录: |