【问题标题】:Bluetooth Into service蓝牙进入服务
【发布时间】:2014-02-17 09:53:33
【问题描述】:

我正在尝试在 android 的服务中建立我的手机和蓝牙卡之间的连接,但我遇到了服务问题。半小时后服务会自动重启。我的目标是让我的服务尽可能长时间地运行。

public void onCreate() {
Log.d("PrinterService", "Service started");   

  super.onCreate();
 }

@Override
public IBinder onBind(Intent intent) {

 return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("PrinterService", "Onstart Command");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {

    if(bluetoothProvider != null)
        bluetoothProvider = null;

        bluetoothProvider = new BluetoothProvider(getApplicationContext());
        bluetoothProvider.startUpdates();
}

return Service.START_STICKY ;
}

@Override
public void onDestroy() {
super.onDestroy();
}

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

    您应该创建一个粘性服务。

    您可以通过在 onStartCommand 中返回 START_STICKY 来做到这一点。

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }
    

    还阅读有关 application:persistent 的内容,即“应用程序是否应始终保持运行”。这个比较麻烦——系统会尽量不杀死你的应用,这会影响系统中的其他应用,你应该小心使用它。

    参考以下链接: https://stackoverflow.com/a/15038770/3110609

    【讨论】:

    • 谢谢,我做了同样的事情,但服务在半小时后继续自动重启
    • 你需要使用警报管理器。请阅读警报管理器的教程。
    • 我还在清单中尝试了 'android:process="" ',服务会自动重启
    • 你觉得 startforeground() 怎么样?
    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多