我遇到了問題。我已閱讀此主題: How to detect Bluetooth state change using a broadcast receiver? 和我用相同的方式編寫我的應用程序,但是當我運行它並關閉應用程序的藍牙會崩潰。系統版本:4.0.3。下面是代碼:如何使用BroadcastReceiver檢測藍牙狀態
MainActivity:
package com.example.lokalizing;
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.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Toast.makeText(context, "Bluetooth off", Toast.LENGTH_LONG);
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Toast.makeText(context, "Turning Bluetooth off", Toast.LENGTH_LONG);
break;
case BluetoothAdapter.STATE_ON:
Toast.makeText(context, "Bluetooth on", Toast.LENGTH_LONG);
break;
case BluetoothAdapter.STATE_TURNING_ON:
Toast.makeText(context, "Turning Bluetooth on", Toast.LENGTH_LONG);
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "Włączono program", Toast.LENGTH_LONG).show();
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
/* ... */
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
public void showToast(String msg) {
Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_SHORT).show();
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lokalizing"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver
android:name="com.example.lokalizing.MainActivity"
android:enabled="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>