2014-07-27 91 views
0

我正在研究需要藍牙作爲Android設備和微控制器芯片之間通信形式的項目。通過活動使藍牙保持連接狀態

我已經成功完成了可以與設備配對並獲得連接並將數據發送到芯片並且工作正常的部分。

我的程序的流程是: 起始頁>輸入文本/字符串>連接到設備>發送數據

這裏的主要問題是,如果我要輸入文本/字符串>連接到設備,但連接後,我決定要更改上一頁中的內容。所以我點擊返回並停止藍牙連接。它不保持連接。

所以我的主要想法是提出藍牙連接頁面,允許我先連接到設備,然後繼續輸入我的文本/字符串。這樣,如果我決定製作另一個活動或選項卡,我只需滑過選項卡並輸入任何我想要的內容,每個選項卡中都會有一個發送按鈕,允許我直接發送數據而無需重新連接。我目前堅持這一點。

藍牙活動:

public class bluetoothtest extends Activity { 
    /** Called when the activity is first created. */ 

    SharedPreferences sPrefs; 

    //Variables 
    final byte ANIMATION_MODE=1; 
    final byte PICTURE_MODE=2; 
    final byte TEXT_MODE=3; 
    int a,b,c,d; 

    int count = 0, click = 0; 

    //TextView 
    TextView btStatus; 

    //ListView 
    ListView listViewPaired; 
    ListView deviceList; 
    ListView chatList; 

    //EditText 
    EditText contentRow1, contentRow2, contentRow3, contentRow4; 

    //Buttons 
    Button buttonSearch, buttonConnect; 
    ToggleButton bluetoothStatus; 

    //Bluetooth Related 
    BluetoothSocket socket; 
    BluetoothDevice bdDevice; 
    BluetoothClass bdClass; 
    deviceListAdapter mAdapter; 
    ChatListAdapter chAdapter; 
    Context mContext; 
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    private readThread readThread = null; 
    private String BlueToothAddress; 


    //Array List/Adapter 
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null; 
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices; 
    ArrayList<String> arrayListpaired; 
    ArrayAdapter<String> adapter; 
    private ArrayList<deviceListItem> list; 
    private ArrayList<SiriListItem> delist; 

    //Misc 
    static HandleSeacrh handleSeacrh; 
    private ButtonClicked clicked; 



    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     //TextView 
     btStatus = (TextView) findViewById(R.id.btStatus); 

     //ListView 
     deviceList = (ListView) findViewById(R.id.deviceList); 
     chatList = (ListView) findViewById(R.id.chatList); 

     //EditText 
     contentRow1 = (EditText) findViewById(R.id.contentRow1); 
     contentRow2 = (EditText) findViewById(R.id.contentRow2); 
     contentRow3 = (EditText) findViewById(R.id.contentRow3); 
     contentRow4 = (EditText) findViewById(R.id.contentRow4); 

     //Buttons 
     buttonSearch = (Button) findViewById(R.id.buttonSearch); 
     buttonConnect = (Button) findViewById(R.id.connectBtn); 
     bluetoothStatus = (ToggleButton) findViewById(R.id.btStatusBtn); 

     //Array List/Adapter 
     list = new ArrayList<deviceListAdapter.deviceListItem>(); 
     delist = new ArrayList<ChatListAdapter.SiriListItem>(); 
     chAdapter = new ChatListAdapter(this, delist); 
     mAdapter = new deviceListAdapter(this, list); 
     deviceList.setAdapter(chAdapter); 
     chatList.setAdapter(mAdapter); 

     //Misc 
     clicked = new ButtonClicked(); 
     handleSeacrh = new HandleSeacrh(); 
     deviceList.setOnItemClickListener(mDeviceClickListener); 

     bluetoothStatus.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       bluetoothOnOff(); 

      } 
     }); 

     //Button Connect OnClickListener 
     buttonConnect.setOnClickListener(new View.OnClickListener() { 

      @SuppressLint("NewApi") 
      @Override 
      public void onClick(View arg0) { 
       if (count == 0) { 
        Toast.makeText(bluetoothtest.this, 
          "Please connect to a device first.", 
          Toast.LENGTH_LONG).show(); 
       } 
       // Need API=14 
       else if (!socket.isConnected()) { 
         Toast.makeText(bluetoothtest.this, 
           "Connecting! Please wait.", 
           Toast.LENGTH_LONG).show(); 
        } 
       else { 
        try { 
         sendMessageHandle(contentRow1.getText().toString(), contentRow2.getText().toString(), contentRow3.getText().toString(), contentRow4.getText().toString()); 
         //sendMessageHandle(contentRow2.getText().toString()); 

        } catch (Exception e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 

      } 
     }); 

     sPrefs = getSharedPreferences("storeData", MODE_PRIVATE); 
     if(((byte) sPrefs.getInt("Mode", 1) == TEXT_MODE)){ 

      contentRow1.setText(sPrefs.getString("firstRow", " ")); 
      contentRow2.setText(sPrefs.getString("secondRow", " ")); 
      contentRow3.setText(sPrefs.getString("thirdRow", " ")); 
      contentRow4.setText(sPrefs.getString("fourthRow", " ")); 
     } 

     IntentFilter discoveryFilter = new IntentFilter(
       BluetoothDevice.ACTION_FOUND); 
     this.registerReceiver(myReceiver, discoveryFilter); 

     IntentFilter foundFilter = new IntentFilter(
       BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
     this.registerReceiver(myReceiver, foundFilter); 

     IntentFilter btState = new IntentFilter(
       BluetoothAdapter.ACTION_STATE_CHANGED); 
     this.registerReceiver(myReceiver, btState); 
    } 
    @Override 
    protected void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 
     buttonSearch.setOnClickListener(clicked); 
     if(bluetoothAdapter.isEnabled()) 
     { 
      bluetoothStatus.setChecked(true); 
      //bluetoothStatus.setBackgroundColor(Color.GREEN); 
      btStatus.setText("Bluetooth Status: Enabled"); 
      btStatus.setBackgroundColor(Color.GREEN); 
     }else if(!bluetoothAdapter.isEnabled()) 
     { 
      bluetoothStatus.setChecked(false); 
      //bluetoothStatus.setBackgroundColor(Color.RED); 
      btStatus.setText("Bluetooth Status: Disabled"); 
      btStatus.setBackgroundColor(Color.RED); 
     } 

    } 



    class ButtonClicked implements OnClickListener 
    { 
     @Override 
     public void onClick(View view) { 
      switch (view.getId()) { 
      case R.id.buttonSearch: 
       //arrayListBluetoothDevices.clear(); 
       startSearching(); 
       break; 
      default: 
       break; 
      } 
     } 
    } 
    private BroadcastReceiver myReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Message msg = Message.obtain(); 
      String action = intent.getAction(); 

//   if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){ 
//    bluetoothOnOff(); 
//   } 
      if(BluetoothDevice.ACTION_FOUND.equals(action)){ 
       Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show(); 

       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

       if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
       { delist.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), action, action, action, false)); 
        mAdapter.notifyDataSetChanged(); 
        deviceList.setSelection(delist.size() - 1); 
       } 
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
       setProgressBarIndeterminateVisibility(false); 
       if (deviceList.getCount() == 0) { 
        delist.add(new SiriListItem("Did not find any bluetooth device", action, action, action, false)); 
        mAdapter.notifyDataSetChanged(); 
        deviceList.setSelection(list.size() - 1); 
       } 
       buttonSearch.setText("Search again"); 
       } 
      }   
     }; 


    private void bluetoothOnOff(){ 

     if(!bluetoothAdapter.isEnabled()) 
     { 
      bluetoothAdapter.enable(); 
      String text = "Bluetooth Status: Enabled"; 
      bluetoothStatus.setChecked(false); 
      //bluetoothStatus.setBackgroundColor(Color.GREEN); 
      btStatus.setText(text); 
      btStatus.setBackgroundColor(Color.GREEN); 
     }else if(bluetoothAdapter.isEnabled()){ 
      String text = "Bluetooth Status: Disabled"; 
      bluetoothAdapter.disable(); 
      bluetoothStatus.setChecked(true); 
      //bluetoothStatus.setBackgroundColor(Color.RED); 
      btStatus.setText(text); 
      btStatus.setBackgroundColor(Color.RED); 
     } 

    } 


    class HandleSeacrh extends Handler 
    { 
     @Override 
     public void handleMessage(Message msg) { 
      switch (msg.what) { 
      case 111: 

       break; 

      default: 
       break; 
      } 
     } 
    } 

    //SharedPreferences sp; 

private void sendMessageHandle(String msg, String msg2, String msg3, String msg4) throws InterruptedException { 

     final byte ANIMATION_MODE=1; 
     final byte PICTURE_MODE=2; 
     final byte TEXT_MODE=3; 
     final int k = 5; 

     int temp,row; 

     sPrefs = getSharedPreferences("storeData",MODE_PRIVATE); 

     byte mode = (byte) sPrefs.getInt("Mode",1); 
     byte [] pictureData = new byte [129]; 

     if (socket == null) { 
      Toast.makeText(mContext, "No connection", Toast.LENGTH_SHORT) 
        .show(); 
      return; 
     } 
     try { 
      OutputStream outputStream = socket.getOutputStream(); 
      if(mode==TEXT_MODE){ 
       //TextMode Signal 
       outputStream.write(4); 
       Thread.sleep(500); 

       //Row 1 Message/Scroll 
       outputStream.write(0); 
       if(sPrefs.getBoolean("scrollRow1", false)) 
         {}else 
         {outputStream.write(6);} 
       msg.getBytes(); 
       if(msg.getBytes().length > 0) 
       {a = 1; 
       outputStream.write(msg.getBytes()); 
       outputStream.write(32);} 


       //Row 2 Message/Scroll 
       outputStream.write(1); 
       if(sPrefs.getBoolean("scrollRow2", false)) 
       {}else 
       {outputStream.write(6);} 
       msg2.getBytes(); 
       if(msg2.getBytes().length > 0) 
       {b = 1; 
       outputStream.write(msg2.getBytes()); 
       outputStream.write(32);} 


       //Row 3 Message/Scroll 
       outputStream.write(2); 
       if(sPrefs.getBoolean("scrollRow3", false)) 
       {}else 
       {outputStream.write(6);} 
       msg3.getBytes(); 
       if(msg3.getBytes().length > 0) 
       {c = 1; 
       outputStream.write(msg3.getBytes()); 
       outputStream.write(32);} 


       //Row 4 Message/Scroll 
       outputStream.write(3); 
       if(sPrefs.getBoolean("scrollRow4", false)) 
       {}else 
       {outputStream.write(6);} 
       msg4.getBytes(); 
       if(msg4.getBytes().length > 0) 
       {d = 1; 
       outputStream.write(msg4.getBytes()); 
       outputStream.write(32);} 

       //End of Signal Transmission 
       outputStream.write(k); 
      } 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     if(a == 1) 
      { a = 0; 
      list.add(new deviceListItem(msg, false)); 
      } 
     if(b == 1) 
      { b = 0; 
      list.add(new deviceListItem(msg2, false)); 
      } 
     if(c == 1) 
      { c = 0; 
     list.add(new deviceListItem(msg3, false)); 
      } 
     if(d == 1) 
      { d = 0; 
     list.add(new deviceListItem(msg4, false)); 
      } 

     mAdapter.notifyDataSetChanged(); 
     chatList.setSelection(list.size() - 1); 
    } 

public void cancle() { 
    try { 
     socket.close(); 
    } catch (IOException e) { 
    } 
} 

    private class clientThread extends Thread { 
     public void run() { 

      try { 
       // 
       bdDevice = bluetoothAdapter.getRemoteDevice(BlueToothAddress); 
       socket = bdDevice.createRfcommSocketToServiceRecord(UUID 
         .fromString("00001101-0000-1000-8000-00805F9B34FB")); 
       Message msg2 = new Message(); 
       msg2.obj = "Please wait, connecting to server: " 
         + BlueToothAddress; 
       msg2.what = 0; 
       LinkDetectedHandler.sendMessage(msg2); 
       socket.connect(); 
       Log.i("tag", "This is the pairing section"); 

       Message msg = new Message(); 
       msg.obj = "Device connected. Sending message is allowed."; 
       msg.what = 0; 
       LinkDetectedHandler.sendMessage(msg); 

       readThread = new readThread(); 
       readThread.start(); 
       click++; 

      } catch (IOException e) { 
       Message msg = new Message(); 
       msg.obj = "Error! Can't connect to device. Please try again."; 
       msg.what = 0; 
       LinkDetectedHandler.sendMessage(msg); 
       click--; 

      } 
     } 
    }; 

    private Handler LinkDetectedHandler = new Handler() { 
     public void handleMessage(Message msg) { 
      Toast.makeText(getApplicationContext(), (String) msg.obj, 
        Toast.LENGTH_SHORT).show(); 
      if (msg.what == 1) { 
       list.add(new deviceListItem((String) msg.obj,true)); 
      } else { 
       list.add(new deviceListItem((String) msg.obj, false)); 
      } 
      mAdapter.notifyDataSetChanged(); 
      chatList.setSelection(list.size() - 4); 
     } 

    }; 


    private class readThread extends Thread { 
     public void run() { 

      byte[] buffer = new byte[1024]; 
      int bytes; 
      InputStream mmInStream = null; 
      String tmp = null; 
      try { 
       mmInStream = socket.getInputStream(); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      while (true) { 
       try { 
        // read the data from the inputStream 
        if ((bytes = mmInStream.read(buffer)) > 0) 
        { 
         for (int i = 0; i < bytes; i++) { 
          tmp = "" + buffer[i]; 
          String st = new String(tmp); 
          tmp = null; 
          Message msg = new Message(); 
          msg.obj = st; 
          msg.what = 1; 
         } 
        } 
       } catch (IOException e) { 
        try { 
         mmInStream.close(); 
        } catch (IOException e1) { 
         // TODO Auto-generated catch block 
         e1.printStackTrace(); 
        } 
        break; 
       } 
      } 
     } 
    } 

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
      // Cancel discovery because it's costly and we're about to connect 

         bluetoothAdapter.cancelDiscovery(); 
         System.out.println("Bluetooth Adapter2 = "+bluetoothAdapter.cancelDiscovery()); 
         SiriListItem item = delist.get(arg2); 
         mAdapter.notifyDataSetChanged(); 
         // When device being clicked 
         count++; 
         click = 1; 
         // Get the device MAC address, which is the last 17 chars in the 
         // View 
         String info = item.message; 
         String address = info.substring(info.length() - 17); 
         BlueToothAddress = address; 
         if (click == 1) { 
          clientThread ct = new clientThread(); 
          ct.start(); 

     } 
}; 
}; 


    @Override 
    protected void onDestroy() { 
     // TODO Auto-generated method stub 
     unregisterReceiver(myReceiver); 
     super.onDestroy(); 
    } 



} 

我不知道,什麼變量或我應該如何分配需要到SharedPreferences變量,讓我保持聯繫一切的時候,我在應用程序。總之,一直保持聯繫,當我連接一次。我希望有人能幫助我解決這個問題。

在此先感謝。

回答

0

SDK中有一個藍牙示例。如果你遵循它,你會看到他們正在一項服務中執行藍牙操作,並且這些活動連接到該服務。無論您的程序運行時有何活動,服務都會保持活動狀態。

+0

我在哪裏可以找到SDK中的Bluetooth Sample?我現在在SDK Manager上,但我沒有看到任何藍牙相關的東西,雖然 – misleading93

+0

https://android.googlesource.com/platform/development/+/eclair-passion-release/samples/BluetoothChat –