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

时间:2014-08-12 15:02:40

标签: android multithreading android-intent bluetooth

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

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

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

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

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

谢谢,

progNewfag

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

1 个答案:

答案 0 :(得分:9)

您必须先学习服务

以下是服务示例

创建一个新类并为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();

        }
    }

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

 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/