Android 향상 의 블 루 투 스 숨겨 진 API 비밀 탐지

12876 단어 Android블 루 투 스
앞의 글 은 안 드 로 이 드 의 블 루 투 스 기본 용법 을 설명 하 였 으 며,본 고 는 좀 더 깊이 있 게 설명 하여 블 루 투 스 방면 의 숨겨 진 API 를 연구 하 였 다.안 드 로 이 드 시스템 설정(Setting)을 사용 한 사람 은 블 루 투 스 검색 후 짝 짓 기 를 만 들 고 짝 짓 기 를 해제 할 수 있다 는 것 을 알 고 있 지만 이 두 가지 기능 의 함 수 는 SDK 에 제시 되 지 않 았 습 니 다.그렇다면 이 두 가지 기능 을 어떻게 사용 합 니까?본 고 는 JAVA 의 반사 체 제 를 이용 하여 이 두 가지 기능 에 대응 하 는 함 수 를 호출 하고 자 한다.createbond 와 removeBond,구체 적 인 발굴 과 실현 절 차 는 다음 과 같다.
1.Git 도 구 를 사용 하여 platform/packages/apps/Settings.git 를 다운로드 하고 Setting 소스 코드 에서 짝 짓 기와 짝 짓 기 해제 에 관 한 API 를 찾 습 니 다.이 두 API 의 숙주(BluetoothDevice)를 알 고 있 습 니 다.
2.반사 체 제 를 사용 하여 BluetoothDevice 에 모든 방법 과 상수 를 매 거 하여 존재 하 는 지 확인 합 니 다.

static public void printAllInform(Class clsShow) {
 try {
 //       
 Method[] hideMethod = clsShow.getMethods();
 int i = 0;
 for (; i < hideMethod.length; i++) {
  Log.e("method name", hideMethod[i].getName());
 }
 //       
 Field[] allFields = clsShow.getFields();
 for (i = 0; i < allFields.length; i++) {
  Log.e("Field name", allFields[i].getName());
 }
 } catch (SecurityException e) {
 // throw new RuntimeException(e.getMessage());
 e.printStackTrace();
 } catch (IllegalArgumentException e) {
 // throw new RuntimeException(e.getMessage());
 e.printStackTrace();
 } catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
}

결 과 는 다음 과 같다.
11-29 09:19:12.012: method name(452): cancelBondProcess
11-29 09:19:12.020: method name(452): cancelPairingUserInput
11-29 09:19:12.020: method name(452): createBond
11-29 09:19:12.020: method name(452): createInsecureRfcommSocket
11-29 09:19:12.027: method name(452): createRfcommSocket
11-29 09:19:12.027: method name(452): createRfcommSocketToServiceRecord
11-29 09:19:12.027: method name(452): createScoSocket
11-29 09:19:12.027: method name(452): describeContents
11-29 09:19:12.035: method name(452): equals
11-29 09:19:12.035: method name(452): fetchUuidsWithSdp
11-29 09:19:12.035: method name(452): getAddress
11-29 09:19:12.035: method name(452): getBluetoothClass
11-29 09:19:12.043: method name(452): getBondState
11-29 09:19:12.043: method name(452): getName
11-29 09:19:12.043: method name(452): getServiceChannel
11-29 09:19:12.043: method name(452): getTrustState
11-29 09:19:12.043: method name(452): getUuids
11-29 09:19:12.043: method name(452): hashCode
11-29 09:19:12.043: method name(452): isBluetoothDock
11-29 09:19:12.043: method name(452): removeBond
11-29 09:19:12.043: method name(452): setPairingConfirmation
11-29 09:19:12.043: method name(452): setPasskey
11-29 09:19:12.043: method name(452): setPin
11-29 09:19:12.043: method name(452): setTrust
11-29 09:19:12.043: method name(452): toString
11-29 09:19:12.043: method name(452): writeToParcel
11-29 09:19:12.043: method name(452): convertPinToBytes
11-29 09:19:12.043: method name(452): getClass
11-29 09:19:12.043: method name(452): notify
11-29 09:19:12.043: method name(452): notifyAll
11-29 09:19:12.043: method name(452): wait
11-29 09:19:12.051: method name(452): wait
11-29 09:19:12.051: method name(452): wait
3.API 가 존재 하 는 것 을 일일이 발견 하면 호출 방법 을 스스로 실현 합 니 다.

/**
 *           :platform/packages/apps/Settings.git
 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
 */
static public boolean createBond(Class btClass,BluetoothDevice btDevice) throws Exception {
 Method createBondMethod = btClass.getMethod("createBond");
 Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
 return returnValue.booleanValue();
}
/**
 *             :platform/packages/apps/Settings.git
 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
 */
static public boolean removeBond(Class btClass,BluetoothDevice btDevice) throws Exception {
 Method removeBondMethod = btClass.getMethod("removeBond");
 Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
 return returnValue.booleanValue();
}

여기 주의:SDK 가 숨겨 진 API 를 제시 하지 않 는 데 는 분명 그 이유 가 있 을 것 입 니 다.안전성 이나 후속 버 전의 호환성 을 고려 한 것 일 수도 있 기 때문에 숨겨 진 API 가 모든 Android 플랫폼 에서 잘 작 동 할 수 있다 는 보장 이 없습니다.
본 프로그램의 운행 효 과 는 다음 그림 과 같다.

main.xml 원본 코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <LinearLayout android:id="@+id/LinearLayout01"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 <Button android:layout_height="wrap_content" android:id="@+id/btnSearch"
  android:text="Search" android:layout_width="160dip"></Button>
 <Button android:layout_height="wrap_content"
  android:layout_width="160dip" android:text="Show" android:id="@+id/btnShow"></Button>
 </LinearLayout>
 <LinearLayout android:id="@+id/LinearLayout02"
 android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
 <ListView android:id="@+id/ListView01" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 </ListView>
</LinearLayout>

도구 클래스 ClUtils.java 원본 코드 는 다음 과 같 습 니 다.

package com.testReflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
public class ClsUtils {
 /**
 *           :platform/packages/apps/Settings.git
 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
 */
 static public boolean createBond(Class btClass,BluetoothDevice btDevice) throws Exception {
 Method createBondMethod = btClass.getMethod("createBond");
 Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
 return returnValue.booleanValue();
 }
 /**
 *             :platform/packages/apps/Settings.git
 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
 */
 static public boolean removeBond(Class btClass,BluetoothDevice btDevice) throws Exception {
 Method removeBondMethod = btClass.getMethod("removeBond");
 Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
 return returnValue.booleanValue();
 }
 /**
 * 
 * @param clsShow
 */
 static public void printAllInform(Class clsShow) {
 try {
  //       
  Method[] hideMethod = clsShow.getMethods();
  int i = 0;
  for (; i < hideMethod.length; i++) {
  Log.e("method name", hideMethod[i].getName());
  }
  //       
  Field[] allFields = clsShow.getFields();
  for (i = 0; i < allFields.length; i++) {
  Log.e("Field name", allFields[i].getName());
  }
 } catch (SecurityException e) {
  // throw new RuntimeException(e.getMessage());
  e.printStackTrace();
 } catch (IllegalArgumentException e) {
  // throw new RuntimeException(e.getMessage());
  e.printStackTrace();
 } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 }
}

주 프로그램 testReflect.java 의 원본 코드 는 다음 과 같 습 니 다.

package com.testReflect;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class testReflect extends Activity {
 Button btnSearch, btnShow;
 ListView lvBTDevices;
 ArrayAdapter<String> adtDevices;
 List<String> lstDevices = new ArrayList<String>();
 BluetoothDevice btDevice;
 BluetoothAdapter btAdapt;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 btnSearch = (Button) this.findViewById(R.id.btnSearch);
 btnSearch.setOnClickListener(new ClickEvent());
 btnShow = (Button) this.findViewById(R.id.btnShow);
 btnShow.setOnClickListener(new ClickEvent());
 lvBTDevices = (ListView) this.findViewById(R.id.ListView01);
 adtDevices = new ArrayAdapter<String>(testReflect.this,
  android.R.layout.simple_list_item_1, lstDevices);
 lvBTDevices.setAdapter(adtDevices);
 lvBTDevices.setOnItemClickListener(new ItemClickEvent());

 btAdapt = BluetoothAdapter.getDefaultAdapter();//          
 if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)//    
  btAdapt.enable();
 //   Receiver            
 IntentFilter intent = new IntentFilter();
 intent.addAction(BluetoothDevice.ACTION_FOUND);
 intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
 registerReceiver(searchDevices, intent);

 }
 private BroadcastReceiver searchDevices = new BroadcastReceiver() {
 public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  Bundle b = intent.getExtras();
  Object[] lstName = b.keySet().toArray();
  //              
  for (int i = 0; i < lstName.length; i++) {
  String keyName = lstName[i].toString();
  Log.e(keyName, String.valueOf(b.get(keyName)));
  }
  //      ,     MAC  
  if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  BluetoothDevice device = intent
   .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  if (device.getBondState() == BluetoothDevice.BOND_NONE) {
   String str = "   |" + device.getName() + "|" + device.getAddress();
   lstDevices.add(str); //        mac  
   adtDevices.notifyDataSetChanged();
  }
  }
 }
 };
 class ItemClickEvent implements AdapterView.OnItemClickListener {

 @Override
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
  long arg3) {
  btAdapt.cancelDiscovery();
  String str = lstDevices.get(arg2);
  String[] values = str.split("//|");
  String address=values[2];
  btDevice = btAdapt.getRemoteDevice(address);
  try {
  if(values[0].equals("   "))
  { 
   Toast.makeText(testReflect.this, "         ", 500).show();
   ClsUtils.createBond(btDevice.getClass(), btDevice);
  }
  else if(values[0].equals("   "))
  {
   Toast.makeText(testReflect.this, "         ", 500).show();
   ClsUtils.removeBond(btDevice.getClass(), btDevice);
  }
  } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }
 }
 /**
 *     
 * @author GV
 *
 */
 class ClickEvent implements View.OnClickListener {
 @Override
 public void onClick(View v) {
  if (v == btnSearch) {//         
  lstDevices.clear();
  Object[] lstDevice = btAdapt.getBondedDevices().toArray();
  for (int i = 0; i < lstDevice.length; i++) {
   BluetoothDevice device=(BluetoothDevice)lstDevice[i];
   String str = "   |" + device.getName() + "|" + device.getAddress();
   lstDevices.add(str); //        mac  
   adtDevices.notifyDataSetChanged();
  }
  //     
  setTitle("      :" + btAdapt.getAddress());
  btAdapt.startDiscovery();
  }
  else if(v==btnShow){//  BluetoothDevice        ,    API
  ClsUtils.printAllInform(btDevice.getClass());
  }
 }
 }
}
본 고의 실례 가 여러분 의 안 드 로 이 드 프로그램 개발 에 어느 정도 참고 와 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기