Android Open Source - BluetoothSppPro act Discovery






From Project

Back to project page BluetoothSppPro.

License

The source code is released under:

Apache License

If you think the Android project BluetoothSppPro listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package mobi.dzs.android.BLE_SPP_PRO;
/*from www. jav  a2s  . c om*/
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class actDiscovery extends Activity{
  /**CONST: scan device menu id*/
  public static final int MEMU_SCAN = 1;
  /**CONST: quit system*/
  public static final int MEMU_QUIT = 2;
  /**CONST: device type bltetooth 2.1*/
  public static final int DEVICE_TYPE_BREDR = 0x01;
  /**CONST: device type bltetooth 4.0 ble*/
  public static final int DEVICE_TYPE_BLE = 0x02;
  /**CONST: device type bltetooth double mode*/
  public static final int DEVICE_TYPE_DUMO = 0x03;
  
  public final static String EXTRA_DEVICE_TYPE = "android.bluetooth.device.extra.DEVICE_TYPE";
  
  /** Discovery is Finished */
  private boolean _discoveryFinished;
  
  /**??????????*/
  private BluetoothAdapter mBT = BluetoothAdapter.getDefaultAdapter();
  /**bluetooth List View*/
  private ListView mlvList = null;
  /**
   * Storage the found bluetooth devices
   * format:<MAC, <Key,Val>>;Key=[RSSI/NAME/COD(class od device)/BOND/UUID]
   * */
  private Hashtable<String, Hashtable<String, String>> mhtFDS = null;
  
  /**ListView????????(???????????)*/
  private ArrayList<HashMap<String, Object>> malListItem = null;
  /**SimpleAdapter??(????????)*/
  private SimpleAdapter msaListItemAdapter = null;

  /**
   * Scan for Bluetooth devices. (broadcast listener)
   */
  private BroadcastReceiver _foundReceiver = new BroadcastReceiver(){
    public void onReceive(Context context, Intent intent){
      /* bluetooth device profiles*/
      Hashtable<String, String> htDeviceInfo = new Hashtable<String, String>();
      
      Log.d(getString(R.string.app_name), ">>Scan for Bluetooth devices");
      
      /* get the search results */
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      /* create found device profiles to htDeviceInfo*/
      Bundle b = intent.getExtras();
      htDeviceInfo.put("RSSI", String.valueOf(b.get(BluetoothDevice.EXTRA_RSSI)));
      if (null == device.getName())
        htDeviceInfo.put("NAME", "Null");
      else
        htDeviceInfo.put("NAME", device.getName());
      
      htDeviceInfo.put("COD",  String.valueOf(b.get(BluetoothDevice.EXTRA_CLASS)));
      if (device.getBondState() == BluetoothDevice.BOND_BONDED)
        htDeviceInfo.put("BOND", getString(R.string.actDiscovery_bond_bonded));
      else
        htDeviceInfo.put("BOND", getString(R.string.actDiscovery_bond_nothing));
      //TODO:????
      String sDeviceType = String.valueOf(b.get(EXTRA_DEVICE_TYPE));
      if (!sDeviceType.equals("null"))
        htDeviceInfo.put("DEVICE_TYPE", sDeviceType);
      else
        htDeviceInfo.put("DEVICE_TYPE", "-1"); //?????????

      /*adding scan to the device profiles*/
      mhtFDS.put(device.getAddress(), htDeviceInfo);
      
      /*Refresh show list*/
      showDevices();
    }
  };  
  /**
   * Bluetooth scanning is finished processing.(broadcast listener)
   */
  private BroadcastReceiver _finshedReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
      Log.d(getString(R.string.app_name), ">>Bluetooth scanning is finished");
      _discoveryFinished = true; //set scan is finished
      unregisterReceiver(_foundReceiver);
      unregisterReceiver(_finshedReceiver);
      
      /* ??????????????????? */
      if (null != mhtFDS && mhtFDS.size()>0){  //???????
        Toast.makeText(actDiscovery.this, 
                 getString(R.string.actDiscovery_msg_select_device),
                 Toast.LENGTH_SHORT).show();
      }else{  //????????
        Toast.makeText(actDiscovery.this, 
               getString(R.string.actDiscovery_msg_not_find_device),
               Toast.LENGTH_LONG).show();
      }
    }
  };
  
  /**
   * start run
   * */
  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_discovery);
    
    this.mlvList = (ListView)this.findViewById(R.id.actDiscovery_lv);
    
      /* ???????????????? */
      this.mlvList.setOnItemClickListener(new OnItemClickListener(){  
            @Override  
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){  
                String sMAC = ((TextView)arg1.findViewById(R.id.device_item_ble_mac)).getText().toString();
            Intent result = new Intent();
            result.putExtra("MAC", sMAC);
            result.putExtra("RSSI", mhtFDS.get(sMAC).get("RSSI"));
            result.putExtra("NAME", mhtFDS.get(sMAC).get("NAME"));
            result.putExtra("COD", mhtFDS.get(sMAC).get("COD"));
            result.putExtra("BOND", mhtFDS.get(sMAC).get("BOND"));
            result.putExtra("DEVICE_TYPE", toDeviceTypeString(mhtFDS.get(sMAC).get("DEVICE_TYPE")));
            setResult(Activity.RESULT_OK, result);
            finish();
            }  
        });
      //??????????????
    new scanDeviceTask().execute("");
  }
  
  /**
   * add top menu
   * */
  @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);
        MenuItem miScan = menu.add(0, MEMU_SCAN, 0, getString(R.string.actDiscovery_menu_scan));
        MenuItem miClose = menu.add(0, MEMU_QUIT, 1, getString(R.string.menu_close));
        miScan.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        miClose.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return super.onCreateOptionsMenu(menu);
    }
  
  /**
   * ????????????????
   * */
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {  
        switch(item.getItemId()){  
          case MEMU_SCAN: //??????
            new scanDeviceTask().execute("");
            return true;
          case MEMU_QUIT: //???????
            this.setResult(Activity.RESULT_CANCELED, null);
            this.finish();
            return true;
          default:
            return super.onMenuItemSelected(featureId, item);
        }
    }
  
  /**
   * ???????
   *   ????????????
   * */
  @Override
  protected void onDestroy(){
    super.onDestroy();
    
    if (mBT.isDiscovering())
      mBT.cancelDiscovery();
  }
  
  /**
   * ??????????????<br/>
   *  ??:?????????????????????????
   *  @return void
   * */
  private void startSearch(){
    _discoveryFinished = false; //???????????
    
    //????????????????????
    if (null == mhtFDS)
      this.mhtFDS = new Hashtable<String, Hashtable<String, String>>();
    else
      this.mhtFDS.clear();
    
    /* Register Receiver*/
    IntentFilter discoveryFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(_finshedReceiver, discoveryFilter);
    IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(_foundReceiver, foundFilter);
    mBT.startDiscovery();//start scan

    this.showDevices(); //the first scan clear show list
  }
  
  /**
   * ?????ID??????????????
   * @return String
   * */
  private String toDeviceTypeString(String sDeviceTypeId){
    Pattern pt = Pattern.compile("^[-\\+]?[\\d]+$");
    if (pt.matcher(sDeviceTypeId).matches()){
          switch(Integer.valueOf(sDeviceTypeId)){
            case DEVICE_TYPE_BREDR:
              return getString(R.string.device_type_bredr);
            case DEVICE_TYPE_BLE:
              return getString(R.string.device_type_ble);
            case DEVICE_TYPE_DUMO:
              return getString(R.string.device_type_dumo);
            default: //??????2.0
              return getString(R.string.device_type_bredr);
          }
    }
    else
      return sDeviceTypeId; //?????????????
  }

  /* Show devices list */
  protected void showDevices(){
    if (null == this.malListItem) //????????????
      this.malListItem = new ArrayList<HashMap<String, Object>>();
    
    //???????????????
        if (null == this.msaListItemAdapter){
          //????????Item???????????  
          this.msaListItemAdapter = new SimpleAdapter(this,malListItem,//??????   
              R.layout.list_view_item_devices,//ListItem?XML??  
              //??????ImageItem??????          
              new String[] {"NAME","MAC", "COD", "RSSI", "DEVICE_TYPE", "BOND"},   
              //ImageItem?XML?????????ImageView,??TextView ID  
              new int[] {R.id.device_item_ble_name,
                   R.id.device_item_ble_mac,
                   R.id.device_item_ble_cod,
                   R.id.device_item_ble_rssi,
                   R.id.device_item_ble_device_type,
                   R.id.device_item_ble_bond
                  }
          );
          //??????  
        this.mlvList.setAdapter(this.msaListItemAdapter);
        }
        
    //???????????
        this.malListItem.clear();//???????
        Enumeration<String> e = this.mhtFDS.keys();
        /*?????????*/
        while (e.hasMoreElements()){
            HashMap<String, Object> map = new HashMap<String, Object>();
            String sKey = e.nextElement();
            map.put("MAC", sKey);
            map.put("NAME", this.mhtFDS.get(sKey).get("NAME"));
            map.put("RSSI", this.mhtFDS.get(sKey).get("RSSI"));
            map.put("COD", this.mhtFDS.get(sKey).get("COD"));
            map.put("BOND", this.mhtFDS.get(sKey).get("BOND"));
            map.put("DEVICE_TYPE", toDeviceTypeString(this.mhtFDS.get(sKey).get("DEVICE_TYPE")));
            this.malListItem.add(map);
        }
    this.msaListItemAdapter.notifyDataSetChanged(); //????????????????????
  }
    
    //----------------
    /*???????:??????????*/
    private class scanDeviceTask extends AsyncTask<String, String, Integer>{
      /**???:????????*/
      private static final int RET_BLUETOOTH_NOT_START = 0x0001;
      /**???:?????????*/
      private static final int RET_SCAN_DEVICE_FINISHED = 0x0002;
      /**????????????????(?????S)*/
      private static final int miWATI_TIME = 10;
      /**?????????(?????ms)*/
      private static final int miSLEEP_TIME = 150;
      /**?????????*/
      private ProgressDialog mpd = null;
      
    /**
     * ?????????????
     */
    @Override
    public void onPreExecute(){
        /*????????*/
      this.mpd = new ProgressDialog(actDiscovery.this);
      this.mpd.setMessage(getString(R.string.actDiscovery_msg_scaning_device));
      this.mpd.setCancelable(true);//??????
      this.mpd.setCanceledOnTouchOutside(true);//?????????
      this.mpd.setOnCancelListener(new DialogInterface.OnCancelListener(){
        @Override
        public void onCancel(DialogInterface dialog){  //??????????????????????
          _discoveryFinished = true;
        }
      });
      this.mpd.show();
      
      startSearch(); //?????????
    }
    
    @Override
    protected Integer doInBackground(String... params){
      if (!mBT.isEnabled()) //????????
        return RET_BLUETOOTH_NOT_START;
      
      int iWait = miWATI_TIME * 1000;//??????
      //??miSLEEP_TIME??????????????????????
      while(iWait > 0){
        if (_discoveryFinished)
          return RET_SCAN_DEVICE_FINISHED; //???????????
        else
          iWait -= miSLEEP_TIME; //????????
        SystemClock.sleep(miSLEEP_TIME);;
      }
      return RET_SCAN_DEVICE_FINISHED; //?????????????????
    }
    /**
     * ?????????
     */
    @Override
    public void onProgressUpdate(String... progress){
    }
    /**
      * ?????????????????
      */
    @Override
    public void onPostExecute(Integer result){
      if (this.mpd.isShowing())
        this.mpd.dismiss();//????????
      
      if (mBT.isDiscovering())
        mBT.cancelDiscovery();
      
      if (RET_SCAN_DEVICE_FINISHED == result){//?????????????
        
      }else if (RET_BLUETOOTH_NOT_START == result){  //????????????
        Toast.makeText(actDiscovery.this, getString(R.string.actDiscovery_msg_bluetooth_not_start), 
                Toast.LENGTH_SHORT).show();
      }
    }
    }
}




Java Source Code List

mobi.dzs.android.BLE_SPP_PRO.BaseActivity.java
mobi.dzs.android.BLE_SPP_PRO.BaseCommActivity.java
mobi.dzs.android.BLE_SPP_PRO.actAbout.java
mobi.dzs.android.BLE_SPP_PRO.actByteStream.java
mobi.dzs.android.BLE_SPP_PRO.actCmdLine.java
mobi.dzs.android.BLE_SPP_PRO.actDiscovery.java
mobi.dzs.android.BLE_SPP_PRO.actKeyBoard.java
mobi.dzs.android.BLE_SPP_PRO.actMain.java
mobi.dzs.android.BLE_SPP_PRO.globalPool.java
mobi.dzs.android.bluetooth.BTSerialComm.java
mobi.dzs.android.bluetooth.BluetoothCtrl.java
mobi.dzs.android.bluetooth.BluetoothSppClient.java
mobi.dzs.android.bluetooth.CResourcePV.java
mobi.dzs.android.control.button.ButtonPassListener.java
mobi.dzs.android.control.button.RepeatingButton.java
mobi.dzs.android.storage.CJsonStorage.java
mobi.dzs.android.storage.CKVStorage.java
mobi.dzs.android.storage.CSharedPreferences.java
mobi.dzs.android.util.CHexConver.java
mobi.dzs.android.util.LocalIOTools.java