前台服务已终止且未重新启动

Foreground Service killed and not restarted

我用 Android BLE(蓝牙低功耗)开发了一个应用程序 它工作正常,但是当 Android 需要更多内存时,我的服务被终止了。

我从 activity 开始我的服务:

 startService(new Intent(this, BluetoothLeService.class));

在我的服务中:

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {

    SetNotification(0);
    return START_STICKY;
}

但是当我的服务被 OS 终止时,它不会重新启动。 我尝试关闭所有最近使用的应用程序,但没有得到任何解决方案....

有什么解决办法吗?请帮我。任何帮助将不胜感激。提前谢谢你。

--- Poweramp 应用程序并非永远不会被杀死 --- 为什么?

编辑:

OnCreate 中的 MainActivity:

...
                startService(new Intent(this, BluetoothLeService.class));

在蓝牙服务中:

 @Override
public void onDestroy() {
    unregisterReceiver(mReceiver); // receiver for bt on and bt off
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    SetNotification(0);
    return START_STICKY;
}

    @Override
public IBinder onBind(Intent intent) {
    return null;
}


public void SetNotification(int VerdeRosso){

    if (VerdeRosso == 1) { // connected
        remoteViews = new RemoteViews(getPackageName(), R.layout.notification_connesso);
    }else {
        remoteViews = new RemoteViews(getPackageName(), R.layout.notification_disconnesso);
    }
    mBuilder = new NotificationCompat.Builder(getApplicationContext());
    mBuilder.setContent(remoteViews);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    startForeground(123, mBuilder.build()); // 123 è l'id a caso
}

   @Override
public void onCreate() {


    mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    //broadcaster = LocalBroadcastManager.getInstance(this);

    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    mReceiver = new MyReceiver();

    registerReceiver(mReceiver, filter);
    scanLeDevice(true);

}

--- 编辑 2

    private final IBinder myBinder = new LocalBinder();

public class LocalBinder extends Binder {
    BluetoothLeService getService() {
        return BluetoothLeService.this;
    }
}
....
    @Override
public IBinder onBind(Intent intent) {

    return myBinder;
}

您可以通过以下方式查看服务何时被杀死并重新启动:

@Override
    public void onLowMemory() {
        //Send broadcast to the Activity to kill this service and restart it.
        super.onLowMemory();
    }

@Override
    public void onTaskRemoved(Intent rootIntent)
    {
            //Send broadcast to the Activity to restart the service
            super.onDestroy();
    }

您可以进行 2 次广播或仅进行上述一种广播。