简体   繁体   English

通过蓝牙连接到设备,锁定的应用程序

[英]Connecting to device via bluetooth, locked app

I'm trying to connect to a embedded device which actually works but when i'm connecting it consumes alot of resources and the app comes to a halt which after some while will respond in a force quit or wait dialog.我正在尝试连接到实际工作的嵌入式设备,但是当我连接时它会消耗大量资源并且应用程序会停止,一段时间后会在强制退出或等待对话框中做出响应。

Read somewhere that a backgroundthread would be the way to go about this but I don't know how to implement it.在某处阅读背景线程将成为 go 的方式,但我不知道如何实现它。 Should I do it as a service?.. or?我应该把它作为一项服务吗?...还是? Real-time programming was a long time ago for me and some help from you guys would be appreciated.实时编程对我来说是很久以前的事了,如果你们能提供一些帮助,我们将不胜感激。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.carsetup);
    car1 = (TextView) findViewById(R.id.carsetuptest1);
    car2 = (TextView) findViewById(R.id.carsetuptest2);
    car3 = (TextView) findViewById(R.id.carsetuptest3);
    Intent i = getIntent();
    selectedcar = (CarModule) i.getParcelableExtra("car");
    car1.setText(selectedcar.getRealname());
    car2.setText(selectedcar.getRealname());
    car3.setText(selectedcar.getAddress());

    try {
        for (int c = 0; c < 3; c++) {
            connectBluetooth();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
private void connectBluetooth() throws Exception {
    if (connected) {
        return;
    }
    BluetoothDevice car = BluetoothAdapter.getDefaultAdapter().
    getRemoteDevice(selectedcar.getAddress());
    Method m = car.getClass().getMethod("createRfcommSocket",
        new Class[] { int.class });
    sock = (BluetoothSocket)m.invoke(car, Integer.valueOf(1));
    Log.d(selectedcar.getRealname(), "++++ Connecting");
    sock.connect();
    Log.d(selectedcar.getRealname(), "++++ Connected");
}

}
@Override
public void onBackPressed() {
    setResult(RESULT_CANCELED);
    super.onBackPressed();
}

It's at sock.connect() it fails.它在sock.connect()它失败了。 So how would I go about this problem?那么我将如何 go 关于这个问题?

EDIT: So I've been exploring different options but it still locks up.编辑:所以我一直在探索不同的选择,但它仍然被锁定。 Now I've tried to implement the threads as Runnable and execute them through a Handler in the following manner:现在我尝试将线程实现为 Runnable 并通过 Handler 以下列方式执行它们:

void connectBluetooth(boolean nextstage, IOException e1){
    if(!nextstage){
        showDialog(DIALOG_BT_ADDING);
        new Handler().post(new ConnectThread(ThreadHandler, selected_car.getDevice()));
    }
    else{
        if(e1 != null){
            new Handler().post(new BluetoothCheckThread(ThreadHandler,mBluetoothAdapter, 
                    5000, car_bt, after_bt));
            search_dialog.dismiss();
        }
        else{
            showDialog(DIALOG_BT_ADDING_FAILED);
        }


    }
}

ConnectThread implements Runnable and has run() overidden. ConnectThread实现Runnable并覆盖了run() The problem is that the UI thread is still locked up and I cannot figure out how.问题是 UI 线程仍然被锁定,我无法弄清楚如何。 ThreadHandler is located in the running Activity : ThreadHandler位于正在运行的Activity中:

Handler ThreadHandler = new Handler (){
    public void handleMessage(Message msg) {
        Log.i("MESSAGEHANDLER", "Message "+ msg.arg1 + " recieved" );
        if(msg.arg1 == 0){
            launchAndPrepare();
        }
        if(msg.arg1 == 1 || msg.arg1 == 2){
            search_dialog.dismiss();
            showDialog(DIALOG_BT_ADDING_FAILED);
        }

    }
};

I'm on the verge of trying another approach like AsyncTask .我即将尝试另一种方法,例如AsyncTask Will that work on the application above?这适用于上面的应用程序吗? Or have I done something incorrect in my current implementation?还是我在当前的实施中做错了什么?

Your code breaks a fundamental rule about Android programming in that you simply cannot perform any time-consuming work (especially network related) on the UI thread, so you need to use some threading.您的代码违反了关于 Android 编程的基本规则,因为您根本无法在 UI 线程上执行任何耗时的工作(尤其是与网络相关的工作),因此您需要使用一些线程。 Just follow the Android Bluetooth guide which explains how to implement the connection and connected states in individual threads.只需遵循 Android 蓝牙指南,该指南解释了如何在各个线程中实现连接和连接状态。 It's all there.这一切都在那里。

http://developer.android.com/guide/topics/wireless/bluetooth.html http://developer.android.com/guide/topics/wireless/bluetooth.html

Fortunately there's very little you actually need to do to get up and running, because most of the programming discussed in the above link is already done for you in the Bluetooth Chat example.幸运的是,启动和运行您实际上需要做的事情很少,因为上面链接中讨论的大部分编程已经在蓝牙聊天示例中为您完成。 You can get started very quickly with this, as it gives you a working application that you can use to derive your own application from.您可以很快开始使用它,因为它为您提供了一个工作应用程序,您可以使用它来派生您自己的应用程序。

http://developer.android.com/resources/samples/BluetoothChat/index.htmlhttp://developer.android.com/resources/samples/BluetoothChat/index.html

The above information provides all you need to know regarding how to handle Bluetooth connectivity in individual Threads.以上信息提供了您需要了解的有关如何在各个线程中处理蓝牙连接的所有信息。

Now, whether you use a separate Service to handle the Bluetooth networking stuff is, I think, really a question of whether you want to be able to maintain the Bluetooth connection for several Activities and/or periodically perform network communications in the background when the user is doing other things on the phone.现在,我认为,您是否使用单独的服务来处理蓝牙网络问题,实际上是一个问题,即您是否希望能够为多个活动维护蓝牙连接和/或在用户使用时在后台定期执行网络通信正在手机上做其他事情。 For instance, my application I'm currently doing has several Activity classes (ie several different UI screens) that all use a Bluetooth connection to a device.例如,我目前正在做的应用程序有几个 Activity 类(即几个不同的 UI 屏幕),它们都使用蓝牙连接到设备。 After the connection is initially created, I wish for the connection to remain up as the user moves between Activities.最初创建连接后,我希望连接在用户在活动之间移动时保持连接。 Furthermore, I even want the connection to remain in the background while the user is doing other stuff so that my application can continue to do datalogging from the device.此外,我什至希望在用户执行其他操作时连接保持在后台,以便我的应用程序可以继续从设备进行数据记录。 Therefore, for me, implementing the Bluetooth networking in a Service was essential.因此,对我来说,在服务中实现蓝牙网络是必不可少的。 If you only require the connection to be available for a duration of a single Activity while it's in the foreground, it may be sufficient to just implement it all within the same Activity (but of course using threads) just like the Bluetooth Chat example does.如果您只需要连接在单个 Activity 处于前台时可用,那么就像蓝牙聊天示例一样,只需在同一个 Activity 中实现所有连接(当然使用线程)就足够了。

What has to be noted is that using a Service in itself does not put the code contained within on a separate thread;需要注意的是,使用 Service 本身并不会将其中包含的代码放在单独的线程上; anything you put into a Service is still running in the main UI thread.您放入 Service 的任何内容仍在主 UI 线程中运行。 You'd still want to perform the long-winded communications stuff within separate threads in the Service, if you do use a Service.如果您确实使用服务,您仍然希望在服务的单独线程中执行冗长的通信内容。

It looks like your application is to be automotive related, which is what mine is.看起来您的应用程序与汽车相关,这就是我的应用程序。

On a final note, one basic modification you usually need to do to the Bluetooth Chat application straight away is to change the UUID so that it connects to the remote device's SPP (Serial Port) Profile.最后一点,您通常需要立即对蓝牙聊天应用程序进行的一项基本修改是更改 UUID,以便它连接到远程设备的 SPP(串行端口)配置文件。 If, for example, you happen to be trying to talk to a car OBD2 to Bluetooth dongle, then it's most probably exchanging serial data over SPP.例如,如果您碰巧尝试将汽车 OBD2 与蓝牙加密狗进行通信,那么它很可能是通过 SPP 交换串行数据。 You change the UUID in the Bluetooth Chat example to:您将蓝牙聊天示例中的 UUID 更改为:

// UUID for Serial Port Profile
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

the reflection of createRfcommSocket fails on some devices because of different implementations "under the hood" - using the special UUID 00001101-0000-1000-8000-00805F9B34FB for devices without SDP should do the trick for you由于“幕后”的不同实现,createRfcommSocket 的反射在某些设备上失败 - 对没有 SDP 的设备使用特殊的 UUID 00001101-0000-1000-8000-00805F9B34FB 应该可以为您解决问题

PS: please star that issue android issue http://code.google.com/p/android/issues/detail?id=5427 to show google that use-cases like ours exist.. PS:请给问题 android 问题http 加注星号://code.google.com/p/android/issues/detail?id=5427向谷歌表明存在像我们这样的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM