通过多种活动保持android蓝牙连接

通过多种活动保持android蓝牙连接,android,android-intent,android-activity,bluetooth,onpause,Android,Android Intent,Android Activity,Bluetooth,Onpause,我正在构建一个Android应用程序,通过蓝牙与Arduino板进行通信,我在一个名为BlueComms的类中拥有蓝牙代码。要连接到设备,我使用以下方法: public boolean connectDevice() { CheckBt(); BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); Log.d(TAG, "Connecting to ... " + device);

我正在构建一个Android应用程序,通过蓝牙与Arduino板进行通信,我在一个名为BlueComms的类中拥有蓝牙代码。要连接到设备,我使用以下方法:

public boolean connectDevice() {
    CheckBt();
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    Log.d(TAG, "Connecting to ... " + device);
    mBluetoothAdapter.cancelDiscovery();
    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        btSocket.connect();
        outStream = btSocket.getOutputStream();
        Log.d(TAG, "Connection made.");
        return true;

    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            Log.d(TAG, "Unable to end the connection");
            return false;
        }
        Log.d(TAG, "Socket creation failed");
    }
    return false;

}
    private void CheckBt() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!mBluetoothAdapter.isEnabled()) {
        System.out.println("Bt dsbld");
    }

    if (mBluetoothAdapter == null) {
        System.out.println("Bt null");
    }
}
这连接很好,但一旦我离开我通过它连接的活动,就会断开连接,通过LogCat显示

 D/dalvikvm(21623): GC_CONCURRENT freed 103K, 10% free 2776K/3056K, paused 5ms+2ms, total 35ms
我无法再连接到设备,但如果调用killBt(),它会抛出一个致命错误,如果我尝试发送数据,则会出现“套接字创建失败”错误。我的发送消息代码如下:

public void sendData(String data, int recvAct) {
    try {
        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        Log.d(TAG, "Bug BEFORE Sending stuff", e);
    }

    String message = data;
    byte[] msgBuffer = message.getBytes();

    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {
        Log.d(TAG, "Bug while sending stuff", e);
    }
}
如何防止连接被我连接的活动暂停当我切换其他活动时,我正在使用以下代码切换活动:

Intent myIntent = new Intent(v.getContext(), Timelapse.class);
    startActivityForResult(myIntent, 0);
非常感谢,,
Rozz

您将BlueComms类的实例存储在哪里?如果您将其放在第一个活动中,那么当您离开该活动并移动到下一个活动时,该类实例将被销毁(NB活动也会在屏幕旋转时被销毁)

因此,您需要找到一种方法,使BlueComms类的实例在您需要的时间内保持活动状态。您可以通过公共属性在活动之间传递它,并在旋转期间将其存储在OnRetainonConfiguration Instance()中

一个更简单的技巧是创建一个扩展
应用程序的类
将其用作应用程序的应用程序委托,并向其添加公共属性以在其中存储BlueComms类的实例。这样,BlueComms类的实例将在应用程序的生命周期内保持活动状态

扩展应用程序

import android.app.Application;

public class cBaseApplication extends Application {

    public BlueComms myBlueComms;

    @Override
    public void onCreate() 
    {
        super.onCreate();
        myBlueComms = new BlueComms();
    }

}
使您的类成为应用程序清单中的应用程序委托

<application
    android:name="your.app.namespace.cBaseApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

当您选择要连接的设备时,以及当您选择要连接的设备时,单击设备列表项以请求连接到该设备,请使用异步任务 并将connect方法放在AsyncTask中,如下所示:-

 AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
                            bluetoothSocket.connect();

                            // After successful connect you can open InputStream
                       } catch (IOException e) {
                         e.printStackTrace();
                       }


**Here is the full code for the same problem that i have cracked :-**

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

              lablelexconnected.setText("Connecting ...");
              bdDevice = arrayListBluetoothDevices.get(position);
              //bdClass = arrayListBluetoothDevices.get(position)
              //    Toast.makeText(getApplicationContext()," " + bdDevice.getAddress(),Toast.LENGTH_SHORT).show();
              Log.i("Log", "The dvice : " + bdDevice.toString());

              bdDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());


              Globals.bluetoothDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
              System.out.println("Device in GPS Settings : " + bdDevice);
              //       startService(new Intent(getApplicationContext(),MyService.class));

             /* Intent i = new Intent(GpsSettings.this, MyService.class);
              startService(i);*/
              //  finish();


            //  connectDevice();


             AsyncTask.execute(new Runnable() {
                 @Override
                 public void run() {

                     try {

                         bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
                         bluetoothSocket.connect();

                         // After successful connect you can open InputStream

                         InputStream in = null;
                         in = bluetoothSocket.getInputStream();
                         InputStreamReader isr = new InputStreamReader(in);
                         br = new BufferedReader(isr);

                         while (found == 0) {
                             String nmeaMessage = br.readLine();
                             Log.d("NMEA", nmeaMessage);
                             // parse NMEA messages
                             sentence = nmeaMessage;

                             System.out.println("Sentence : " + sentence);


                             if (sentence.startsWith("$GPRMC")) {
                                 String[] strValues = sentence.split(",");
                                 System.out.println("StrValues : " + strValues[3] + " " + strValues[5] + " " + strValues[8]);
                                 if (strValues[3].equals("") && strValues[5].equals("") && strValues[8].equals("")) {
                                     Toast.makeText(getApplicationContext(), "Location Not Found !!! ", Toast.LENGTH_SHORT).show();

                                 } else {

                                     latitude = Double.parseDouble(strValues[3]);
                                     if (strValues[4].charAt(0) == 'S') {
                                         latitude = -latitude;
                                     }
                                     longitude = Double.parseDouble(strValues[5]);
                                     if (strValues[6].charAt(0) == 'W') {
                                         longitude = -longitude;
                                     }
                                     course = Double.parseDouble(strValues[8]);

                                     //    Toast.makeText(getApplicationContext(), "latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course, Toast.LENGTH_SHORT).show();
                                     System.out.println("latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course);
                                 //    found = 1;

                                     NMEAToDecimalConverter(latitude, longitude);


                                 }
                             }


                         }


                     } catch (IOException e) {
                         e.printStackTrace();
                     }


                 }
             });


          }

      });
AsyncTask.execute(新的Runnable(){
@凌驾
公开募捐{
试一试{
bluetoothSocket=Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT\u SPP\u UUID);
bluetoothSocket.connect();
//成功连接后,可以打开InputStream
}捕获(IOE异常){
e、 printStackTrace();
}
**下面是我破解的同一个问题的完整代码:-**
setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
lableExconnected.setText(“连接…”);
bdDevice=arrayListBluetoothDevices.get(位置);
//bdClass=arrayListBluetoothDevices.get(位置)
//Toast.makeText(getApplicationContext(),“”+bdDevice.getAddress(),Toast.LENGTH\u SHORT).show();
Log.i(“Log”,“dvice:+bdDevice.toString());
bdDevice=bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
Globals.bluetoothDevice=bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
System.out.println(“GPS设置中的设备:“+bdDevice”);
//startService(新的意图(getApplicationContext(),MyService.class));
/*意图i=新意图(GpsSettings.this、MyService.class);
startService(一)*/
//完成();
//连接设备();
AsyncTask.execute(新的Runnable(){
@凌驾
公开募捐{
试一试{
bluetoothSocket=Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT\u SPP\u UUID);
bluetoothSocket.connect();
//成功连接后,可以打开InputStream
InputStream in=null;
in=bluetoothSocket.getInputStream();
InputStreamReader isr=新的InputStreamReader(in);
br=新的缓冲读取器(isr);
while(找到==0){
字符串nmeaMessage=br.readLine();
Log.d(“NMEA”,NMAMessage);
//解析NMEA消息
句子=N留言;
System.out.println(“句子:”+句子);
如果(句子.startsWith(“$GPRMC”)){
String[]strValues=句子.split(“,”);
System.out.println(“StrValues:+StrValues[3]+”“+StrValues[5]+”“+StrValues[8]);
if(strValues[3]。等于(“”&&strValues[5]。等于(“”&&strValues[8]。等于(“”){
Toast.makeText(getApplicationContext(),“找不到位置!!!”,Toast.LENGTH\u SHORT.show();
}否则{
纬度=Double.parseDouble(标准值[3]);
if(strValues[4]。字符(0)='S'){
纬度=-纬度;
}
经度=Double.parseDouble(标准值[5]);
if(标准值[6]。字符(0)==“W”){
经度=-经度;
}
course=Double.parseDouble(标准值[8]);
//Toast.makeText(getApplicationContext(),“latitude=“+latitude+”;longitude=“+longitude+”;course=“+course,Toast.LENGTH\u SHORT).show();
s
 AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
                            bluetoothSocket.connect();

                            // After successful connect you can open InputStream
                       } catch (IOException e) {
                         e.printStackTrace();
                       }


**Here is the full code for the same problem that i have cracked :-**

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

              lablelexconnected.setText("Connecting ...");
              bdDevice = arrayListBluetoothDevices.get(position);
              //bdClass = arrayListBluetoothDevices.get(position)
              //    Toast.makeText(getApplicationContext()," " + bdDevice.getAddress(),Toast.LENGTH_SHORT).show();
              Log.i("Log", "The dvice : " + bdDevice.toString());

              bdDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());


              Globals.bluetoothDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
              System.out.println("Device in GPS Settings : " + bdDevice);
              //       startService(new Intent(getApplicationContext(),MyService.class));

             /* Intent i = new Intent(GpsSettings.this, MyService.class);
              startService(i);*/
              //  finish();


            //  connectDevice();


             AsyncTask.execute(new Runnable() {
                 @Override
                 public void run() {

                     try {

                         bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
                         bluetoothSocket.connect();

                         // After successful connect you can open InputStream

                         InputStream in = null;
                         in = bluetoothSocket.getInputStream();
                         InputStreamReader isr = new InputStreamReader(in);
                         br = new BufferedReader(isr);

                         while (found == 0) {
                             String nmeaMessage = br.readLine();
                             Log.d("NMEA", nmeaMessage);
                             // parse NMEA messages
                             sentence = nmeaMessage;

                             System.out.println("Sentence : " + sentence);


                             if (sentence.startsWith("$GPRMC")) {
                                 String[] strValues = sentence.split(",");
                                 System.out.println("StrValues : " + strValues[3] + " " + strValues[5] + " " + strValues[8]);
                                 if (strValues[3].equals("") && strValues[5].equals("") && strValues[8].equals("")) {
                                     Toast.makeText(getApplicationContext(), "Location Not Found !!! ", Toast.LENGTH_SHORT).show();

                                 } else {

                                     latitude = Double.parseDouble(strValues[3]);
                                     if (strValues[4].charAt(0) == 'S') {
                                         latitude = -latitude;
                                     }
                                     longitude = Double.parseDouble(strValues[5]);
                                     if (strValues[6].charAt(0) == 'W') {
                                         longitude = -longitude;
                                     }
                                     course = Double.parseDouble(strValues[8]);

                                     //    Toast.makeText(getApplicationContext(), "latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course, Toast.LENGTH_SHORT).show();
                                     System.out.println("latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course);
                                 //    found = 1;

                                     NMEAToDecimalConverter(latitude, longitude);


                                 }
                             }


                         }


                     } catch (IOException e) {
                         e.printStackTrace();
                     }


                 }
             });


          }

      });
Class MyBTConnection{
  private static MyBTConnection connectionObj;

  private Handler mHandler;

  public MyBTConnection() { //constructor }

  public static MyBTConnection getInstance() {
    if(connectionObj == null) {
        connectionObj = new MyBTConnection();
    }
     return connectionObj;
    }
  }

  public void setHandler(Handler handler) {
     mHandler = handler;
  }


  ..... Code for Bluetooth Connection ....
  to send message : 
  mHandler.obtainMessage(what).sendToTarget();

}

// in first activity
class MainActivity extends Activity {
     private MyBTConnection connectionObj;

     public onCreate(....) {

         /*
          * Since this is first call for getInstance. A new object
          * of MyBTConnection will be created and a connection to
          * remote bluetooth device will be established.
          */
         connectionObj = MyBTConnection.getInstance();
         connectionObj.setHandler(mHandler);
     }

     private Handler mHandler = new Handler(){
          public void onReceive(...) {
               /// handle received messages here 
          }
     };

}

// in second activity
class SecondActivity extends Activity {

     private MyBTConnection connectionObj;

     public onCreate(....) {

         /*
          * Since this is second call for getInstance.
          * Object for MyBTConnection was already created in previous 
          * activity. So getInstance will return that previously
          * created object and in that object, connection to remote
          * bluetooth device is already established so you can                
          * continue your work here.
          */
         connectionObj = MyBTConnection.getInstance();
         connectionObj.setHandler(mHandler);
     }

     private Handler mHandler = new Handler(){
          public void onReceive(...) {
               /// handle received messages here 
          }
     };
}