我基于蓝牙聊天示例和蓝牙查看器创建了这个应用程序。这是启动第二个活动以找到蓝牙设备的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.search :
Intent serverIntent = new Intent(this, StartScan.class);
startActivityForResult(serverIntent, REQUEST_START_SCAN);
return true;
}
return false;
}
这是我扫描设备的第二个活动:
public class StartScan extends Activity {
//Debugging
public static final String TAG = "StartScan";
public static final boolean D = true;
//Return intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
//Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREAT +++");
setContentView(R.layout.activity_start_scan);
//Set result canceled in case the user backs out
setResult(Activity.RESULT_CANCELED);
// Show the Up button in the action bar.
setupActionBar();
//Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.startScan);
scanButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
doDiscovery();
}
});
//Initialize the button to perform cancel discovery
Button cancelScan = (Button) findViewById(R.id.cancelScan);
cancelScan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mBtAdapter.cancelDiscovery();
findViewById(R.id.progressBar).setVisibility(View.GONE);
}
});
//Initialize ArrayAdapter for newly discovered devices
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,R.layout.device_name);
//Find and setup list view for newly discovered devices
ListView newDevivesListView = (ListView)findViewById(R.id.listView1);
newDevivesListView.setAdapter(mNewDevicesArrayAdapter);
newDevivesListView.setOnItemClickListener(mDeviceClickListener);
// Register for Broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
//Register for Broadcasts when discovery is finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
//Get the local bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
}
@Override
public void onDestroy(){
super.onDestroy();
if(D) Log.e(TAG, "--- ON DESTROY ---");
//Make sure we are not doing discovery any more
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
//Unregister broadcast listener
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery(){
if(D) Log.d(TAG, "DO DISCOVERY");
mNewDevicesArrayAdapter.clear();
//turn on subtitle for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
//If we are already discovering , cancel it
if(mBtAdapter.isDiscovering()){
mBtAdapter.cancelDiscovery();
}
//Request discover from bluetooth adapter
mBtAdapter.startDiscovery();
}
//The on click listener for all devices in the list view
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3){
//Cancel discovery because it is costly and we are about to connect
mBtAdapter.cancelDiscovery();
//Get the device MAC address , which is the last 17 chars in the view
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
//Create the result intent and include MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
if(D) Log.d(TAG, "... PUT EXTRA ...");
//Set result and finish this activity
setResult(Activity.RESULT_OK, intent);
if (D) Log.d(TAG, ".. SET RESULT ..");
finish();
}
};
//The broadcast receiver that listens for discovered devices and changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context,Intent intent){
String action = intent.getAction();
//When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Get the bluetooth device object from the intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
//When discovery is finished , changed the activity title
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
findViewById(R.id.progressBar).setVisibility(View.GONE);
if(mNewDevicesArrayAdapter.getCount() == 0){
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start_scan, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
在我点击一个设备后它停止工作。你可以在这里看到我的应用程序的日志:
09-10 01:25:40.692: E/MainActivity(26328): +++ ON CREATE +++
09-10 01:25:40.872: E/MainActivity(26328): ++ ON START ++
09-10 01:25:40.922: E/MainActivity(26328): + ON RESUME +
09-10 01:25:40.962: E/MainActivity(26328): - ON PAUSE -
09-10 01:25:41.062: D/libEGL(26328): loaded /system/lib/egl/libGLES_android.so
09-10 01:25:41.102: D/libEGL(26328): loaded /system/lib/egl/libEGL_adreno200.so
09-10 01:25:41.152: D/libEGL(26328): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
09-10 01:25:41.152: D/libEGL(26328): loaded /system/lib/egl/libGLESv2_adreno200.so
09-10 01:25:41.333: I/Adreno200-EGLSUB(26328): <ConfigWindowMatch:2078>: Format RGBA_8888.
09-10 01:25:41.353: D/memalloc(26328): ashmem: Mapped buffer base:0x5217e000 size:1536000 fd:63
09-10 01:25:41.393: D/OpenGLRenderer(26328): Enabling debug mode 0
09-10 01:25:41.533: D/OpenGLRenderer(26328): has fontRender patch
09-10 01:25:41.603: D/OpenGLRenderer(26328): has fontRender patch
09-10 01:25:41.643: D/memalloc(26328): ashmem: Mapped buffer base:0x527bb000 size:1536000 fd:66
09-10 01:25:47.569: D/memalloc(26328): ashmem: Mapped buffer base:0x52a32000 size:1536000 fd:69
09-10 01:25:47.569: D/MainActivity(26328): onActivityResult -1
09-10 01:25:47.579: E/MainActivity(26328): + ON RESUME +
09-10 01:25:50.572: E/MainActivity(26328): - ON PAUSE -
09-10 01:25:50.582: E/StartScan(26328): +++ ON CREAT +++
09-10 01:25:50.682: I/Adreno200-EGLSUB(26328): <ConfigWindowMatch:2078>: Format RGBA_8888.
09-10 01:25:50.692: D/memalloc(26328): ashmem: Mapped buffer base:0x52e20000 size:1536000 fd:73
09-10 01:25:50.762: D/memalloc(26328): ashmem: Mapped buffer base:0x5310e000 size:1536000 fd:79
09-10 01:25:50.772: D/OpenGLRenderer(26328): Flushing caches (mode 0)
09-10 01:25:50.992: E/MainActivity(26328): -- ON STOP --
09-10 01:25:53.454: D/memalloc(26328): ashmem: Mapped buffer base:0x5217e000 size:1536000 fd:64
09-10 01:25:53.594: D/StartScan(26328): DO DISCOVERY
09-10 01:25:55.727: D/StartScan(26328): ... PUT EXTRA ...
09-10 01:25:55.727: D/StartScan(26328): .. SET RESULT ..
09-10 01:25:55.777: D/MainActivity(26328): onActivityResult -1
09-10 01:25:55.797: D/AndroidRuntime(26328): Shutting down VM
09-10 01:25:55.797: W/dalvikvm(26328): threadid=1: thread exiting with uncaught exception (group=0x40acd228)
09-10 01:25:55.817: E/AndroidRuntime(26328): FATAL EXCEPTION: main
09-10 01:25:55.817: E/AndroidRuntime(26328): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { (has extras) }} to activity {com.example.atrin/com.example.atrin.MainActivity}: java.lang.NullPointerException
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3437)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.ActivityThread.access$1100(ActivityThread.java:139)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1291)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.os.Handler.dispatchMessage(Handler.java:99)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.os.Looper.loop(Looper.java:154)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.ActivityThread.main(ActivityThread.java:4945)
09-10 01:25:55.817: E/AndroidRuntime(26328): at java.lang.reflect.Method.invokeNative(Native Method)
09-10 01:25:55.817: E/AndroidRuntime(26328): at java.lang.reflect.Method.invoke(Method.java:511)
09-10 01:25:55.817: E/AndroidRuntime(26328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-10 01:25:55.817: E/AndroidRuntime(26328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-10 01:25:55.817: E/AndroidRuntime(26328): at dalvik.system.NativeStart.main(Native Method)
09-10 01:25:55.817: E/AndroidRuntime(26328): Caused by: java.lang.NullPointerException
09-10 01:25:55.817: E/AndroidRuntime(26328): at com.example.atrin.MainActivity.onActivityResult(MainActivity.java:172)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.Activity.dispatchActivityResult(Activity.java:4740)
09-10 01:25:55.817: E/AndroidRuntime(26328): at android.app.ActivityThread.deliverResults(ActivityThread.java:3383)
09-10 01:25:55.817: E/AndroidRuntime(26328): ... 11 more
09-10 01:25:58.249: D/Process(26328): killProcess, pid=26328
09-10 01:25:58.269: D/Process(26328): dalvik.system.VMStack.getThreadStackTrace(Native Method)
09-10 01:25:58.269: D/Process(26328): java.lang.Thread.getStackTrace(Thread.java:599)
09-10 01:25:58.269: D/Process(26328): android.os.Process.killProcess(Process.java:788)
09-10 01:25:58.269: D/Process(26328): com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:104)
09-10 01:25:58.269: D/Process(26328): java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
09-10 01:25:58.269: D/Process(26328): java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
09-10 01:25:58.269: D/Process(26328): dalvik.system.NativeStart.main(Native Method)
09-10 01:25:58.269: I/Process(26328): Sending signal. PID: 26328 SIG: 9
09-10 01:52:55.337: E/MainActivity(26553): +++ ON CREATE +++
09-10 01:52:55.447: E/MainActivity(26553): ++ ON START ++
09-10 01:52:55.477: E/MainActivity(26553): + ON RESUME +
09-10 01:52:55.527: D/libEGL(26553): loaded /system/lib/egl/libGLES_android.so
09-10 01:52:55.537: D/libEGL(26553): loaded /system/lib/egl/libEGL_adreno200.so
09-10 01:52:55.547: D/libEGL(26553): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
09-10 01:52:55.547: D/libEGL(26553): loaded /system/lib/egl/libGLESv2_adreno200.so
09-10 01:52:55.607: I/Adreno200-EGLSUB(26553): <ConfigWindowMatch:2078>: Format RGBA_8888.
09-10 01:52:55.637: D/memalloc(26553): ashmem: Mapped buffer base:0x5217e000 size:1536000 fd:63
09-10 01:52:55.657: D/OpenGLRenderer(26553): Enabling debug mode 0
09-10 01:52:55.957: D/OpenGLRenderer(26553): has fontRender patch
09-10 01:52:55.997: D/OpenGLRenderer(26553): has fontRender patch
09-10 01:52:56.027: D/memalloc(26553): ashmem: Mapped buffer base:0x527bb000 size:1536000 fd:66
09-10 01:52:56.908: D/memalloc(26553): ashmem: Mapped buffer base:0x52a32000 size:1536000 fd:69
09-10 01:52:56.978: E/MainActivity(26553): - ON PAUSE -
09-10 01:52:56.988: E/StartScan(26553): +++ ON CREAT +++
09-10 01:52:57.078: I/Adreno200-EGLSUB(26553): <ConfigWindowMatch:2078>: Format RGBA_8888.
09-10 01:52:57.088: D/memalloc(26553): ashmem: Mapped buffer base:0x52e20000 size:1536000 fd:73
09-10 01:52:57.158: D/memalloc(26553): ashmem: Mapped buffer base:0x5310e000 size:1536000 fd:79
09-10 01:52:57.168: D/OpenGLRenderer(26553): Flushing caches (mode 0)
09-10 01:52:57.389: E/MainActivity(26553): -- ON STOP --
09-10 01:52:57.899: D/memalloc(26553): ashmem: Mapped buffer base:0x5217e000 size:1536000 fd:64
09-10 01:52:57.969: D/StartScan(26553): DO DISCOVERY
09-10 01:52:59.891: D/StartScan(26553): ... PUT EXTRA ...
09-10 01:52:59.891: D/StartScan(26553): .. SET RESULT ..
09-10 01:52:59.931: D/MainActivity(26553): onActivityResult -1
09-10 01:52:59.951: D/AndroidRuntime(26553): Shutting down VM
09-10 01:52:59.951: W/dalvikvm(26553): threadid=1: thread exiting with uncaught exception (group=0x40acd228)
09-10 01:52:59.961: E/AndroidRuntime(26553): FATAL EXCEPTION: main
09-10 01:52:59.961: E/AndroidRuntime(26553): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { (has extras) }} to activity {com.example.atrin/com.example.atrin.MainActivity}: java.lang.NullPointerException
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3437)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.ActivityThread.access$1100(ActivityThread.java:139)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1291)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.os.Handler.dispatchMessage(Handler.java:99)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.os.Looper.loop(Looper.java:154)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.ActivityThread.main(ActivityThread.java:4945)
09-10 01:52:59.961: E/AndroidRuntime(26553): at java.lang.reflect.Method.invokeNative(Native Method)
09-10 01:52:59.961: E/AndroidRuntime(26553): at java.lang.reflect.Method.invoke(Method.java:511)
09-10 01:52:59.961: E/AndroidRuntime(26553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-10 01:52:59.961: E/AndroidRuntime(26553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-10 01:52:59.961: E/AndroidRuntime(26553): at dalvik.system.NativeStart.main(Native Method)
09-10 01:52:59.961: E/AndroidRuntime(26553): Caused by: java.lang.NullPointerException
09-10 01:52:59.961: E/AndroidRuntime(26553): at com.example.atrin.MainActivity.onActivityResult(MainActivity.java:172)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.Activity.dispatchActivityResult(Activity.java:4740)
09-10 01:52:59.961: E/AndroidRuntime(26553): at android.app.ActivityThread.deliverResults(ActivityThread.java:3383)
09-10 01:52:59.961: E/AndroidRuntime(26553): ... 11 more
提前致谢。