简体   繁体   中英

Continue service when app is killed

I have an activity with two buttons (ON and OFF): when I click the ON button a service starts. When I click the OFF botton the service stops. Now, my service does not have problems apart from when I kill the app from "Recent Apps" because in this circumstance the service restarts. I don't want that it restarts but I want that it continues working. The service is a START_STICKY.
This is my "service" code:

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    myServiceReceiver = new MyServiceReceiver();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // Display a notification about us starting.  We put an icon in the status bar.
    showNotification();
}

public class LocalBinder extends Binder {
    SensorService getService() {
        return SensorService.this;
    }
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return mBinder;
}

// This is the object that receives interactions from clients.  See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    if (!running){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MY_ACTION_FROMACTIVITY);
        registerReceiver(myServiceReceiver, intentFilter);
        running = true;

        sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),   SensorManager.SENSOR_DELAY_NORMAL);
    }
    //return super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}

@Override
public void onDestroy() {
    Log.v(TAG,"destroy");
    // TODO Auto-generated method stub
    sensorManager.unregisterListener(this);
    mNM.cancel(NOTIFICATION);
    this.unregisterReceiver(myServiceReceiver);
    super.onDestroy();
}


private void showNotification() {
    CharSequence text = getText(R.string.activity);
    Notification notification = new Notification(R.drawable.lifestyle, text, System.currentTimeMillis());

    SharedPreferences flagNot = getSharedPreferences("flagNotification", 0);
    final SharedPreferences.Editor editor = flagNot.edit();
    editor.putBoolean("flagNotification",true);
    editor.commit();

    Intent notificationIntent = new Intent(this, ActivityTab.class);
    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.app_name),text, contentIntent);
    notification.flags |= Notification.FLAG_NO_CLEAR;
    // Send the notification.
    mNM.notify(NOTIFICATION, notification);
}


public void onAccuracyChanged(Sensor sensor,int accuracy){

}

public void onSensorChanged(SensorEvent event){
    ......
}

public class MyServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        int hostCmd = arg1.getIntExtra(CMD, 0);
        if(hostCmd == CMD_STOP){
            running = false;

            stopSelf();
        }
    }
}       

}

Can you help me,please?
Many thanks.

Implement startForeground in your service and send it a persistent notification.

private void startForeground() {
    int ID = 1234;
    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Notification.Builder builder = new Notification.Builder(getBaseContext());
    builder.setContentIntent(pendIntent);
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setTicker("CUSTOM MESSAGE");
    builder.setWhen(System.currentTimeMillis());
    builder.setAutoCancel(false);
    builder.setContentTitle("Test Service");
    builder.setContentText("CUSTOM MESSAGE");

    Notification notification = builder.build();

    startForeground(ID, notification);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM