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

10
我正在编写一个与蓝牙模块通信的蓝牙应用程序。实际上,它运行得非常好。但我希望在应用程序在后台并使用其他应用程序时保持连接,以便另一个活动(如来电短信或其他内容)可以在后台触发我的应用程序向我的设备发送消息。
到目前为止,我非常困惑该如何做到这一点。有人能给我建议吗?
我还检查了这个:Background Bluetooth App - Threading? 但它对我没有帮助。
以下是我到目前为止的代码:http://pastebin.com/C7Uynuan 附加信息:有一个连接按钮,它建立连接,然后有3个其他按钮向我的设备发送不同的消息。在OnResume中,我重新连接到我的设备,但当有一个稳定的连接时,这是不必要的。
谢谢, progNewfag
编辑:现在我非常确定我需要使用IntentService,但不确定如何使用。

1
你尝试过服务吗? - Jamil
我的问题是我不确定如何处理Intentservice,以便它不会停止。同时,我的Intentservice和GUI之间的连接也令人困惑。 - progNewbie
1个回答

11

你需要先学习服务

以下是服务的示例

创建一个新类并命名为例如: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));

请查看此文章

活动和服务之间的连接

还可以参考以下链接

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

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

编辑:

示例:使用消息传递进行活动和服务之间的通信

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


非常感谢。但是在第一个链接中,他们通过将字符串添加到Intent并调用StartService来发送字符串。但是当我的服务已经在运行时,我该如何向其发送数据?因为我想在我的服务中建立蓝牙连接,然后发送应该通过蓝牙发送的命令。 - progNewbie
我尝试使用上述命令启动我的服务,但我的Eclipse总是说它是错误的,并将其更正为:startService(new Intent()); - progNewbie
如果我以这种方式运行它,在创建服务时,我看不到onCreate中的toast。我应该能够看到它,对吗? - progNewbie
啊,我明白了。我需要写成 MyActivity.this 而不是只写 this。 - progNewbie
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/59375/discussion-between-prognewfag-and-softcoder。 - progNewbie
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接