【发布时间】:2016-06-29 10:00:10
【问题描述】:
我用 Android BLE 开发了一个应用程序(蓝牙低功耗) 它工作正常,但是当 Android 需要更多内存时,我的服务会被终止。
-
我正在使用带有单独进程的前台服务。
我从以下活动开始我的服务:
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;
}
【问题讨论】:
-
你的服务中有一些回调和广播吗?
-
你不能使用粘性服务
-
@Fakher 我的服务中有一个接收器,用于关闭蓝牙和打开蓝牙。 war_Hero...为什么?
-
因为如果服务没有与您的应用程序交互,它可能会被操作系统杀死。尝试查看使用 BLE github.com/Fakher-Hakim/android-BluetoothLeGatt 实现应用程序的 Google 示例项目
-
如果您的服务很粘但仍然没有重新启动,也许它正在崩溃?你检查过日志吗?粘性服务在崩溃时会被“隔离”一段时间,以防止无休止的崩溃循环。另外,您的 setNotification 方法是什么样的?您是否提供了有效的通知?以前的 android 版本有一个漏洞,您可以通过提供不可见的通知来使您的服务前台而不被任何人注意到,但在较新的版本中被拒绝,实际上永远不会使服务前台。