我开发了一款Android BLE应用程序(蓝牙低功能) 它工作正常但是当Android需要更多内存时,我的服务就会被杀死。
我正在使用具有单独进程的前台服务。
<接收器android:name =" .BluetoothLeService $ MyReceiver" />
< service android:name =" .BluetoothLeService" 机器人:启用="真" 机器人:导出="真" 机器人:过程=":为MyService" />
我从活动开始我的服务:
startService(new Intent(this, BluetoothLeService.class));
并在我的服务中:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
SetNotification(0);
return START_STICKY;
}
但是当我的服务被操作系统杀死时,它不会重启。 我试过关闭所有最近的应用程序,但没有得到任何解决方案......
这有什么解决方案吗?请帮我。任何帮助将不胜感激。提前谢谢。
--- Poweramp应用程序永远不会被杀 - 为什么?
编辑:
OnCreate中的MainActivity:
...
startService(new Intent(this, BluetoothLeService.class));
在BluetoothLeService中:
@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;
}
答案 0 :(得分:1)
您可以通过以下方式检查服务何时被杀死并重新启动:
@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次广播或仅进行以上其中一次。