gpt4 book ai didi

android - 如何在后台保持蓝牙连接?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:05:15 25 4
gpt4 key购买 nike

我正在编写一个与蓝牙模块通信的蓝牙应用程序。实际上它工作得很好。但是我希望在应用程序处于后台并且使用其他应用程序时也保持连接建立,以便其他 Activity (例如传入的短信或其他内容)可以触发我的应用程序在后台向我的设备发送消息。

直到现在我都很困惑如何做到这一点。谁能给我建议?

我还检查了这个:Background Bluetooth App - Threading?但这对我没有帮助。

到目前为止,这是我的代码: http://pastebin.com/C7Uynuan

辅助信息:有一个连接按钮,用于建立连接,然后还有 3 个其他按钮向我的设备发送不同的消息。在 OnResume 中,我重新连接到我的设备,但如果连接稳定,则不需要这样做。

谢谢,

progNewfag

编辑:现在我很确定我需要使用 IntentService,但不确定如何使用。

最佳答案

先学会服务

这是服务的例子

创建一个新类并将其命名为 Exmaple:MyService

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
public MyService() {
}

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

@Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();

}

@Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
// Do your Bluetooth Work Here
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();

}

@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}
}

现在在您的主要 Activity 中,您可以通过此代码启动服务

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

要停止服务,请将此代码放入 MainActivity

stopService(new Intent(this, MyService.class));

查看这篇文章

Connection between Activity and Service

另请参阅此链接

http://www.javacodegeeks.com/2014/01/android-service-tutorial.html

http://examples.javacodegeeks.com/android/core/service/android-service-example/

编辑:

Example: Communication between Activity and Service using Messaging

http://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/

关于android - 如何在后台保持蓝牙连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com