我是 Android 开发的新手。我已经定义了一个带有服务的测试应用程序,我在其中声明了一个 BroadcastReceiver 用于接收蓝牙事件 -
public class MyService extends Service
{
BluetoothEventsReceiver mBluetoothEventsReceiver = null;
@Override
public int onStartCommand(Intent i, int flags, int startId) {
// register the receiver to listen for Bluetooth Connected/Dis-connected events
if (mBluetoothEventsReceiver != null) {
mBluetoothEventsReceiver = new BluetoothEventsReceiver();
Log.e(TAG, "Register receiver=" + mBluetoothEventsReceiver);
IntentFilter intent = new IntentFilter("android.bluetooth.device.action.ACL_CONNECTED");
intent.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
getApplicationContext().registerReceiver(mBluetoothEventsReceiver, intent);
}
return super.onStartCommand(i, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
我的 BroadcastReceiver 定义为
public class BluetoothEventsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.e(TAG, "Received Event" + " ACTION_ACL_DISCONNECTED" );
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "device=" + device);
} else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
Log.e(TAG, "Received Event" + " ACTION_ACL_CONNECTED" );
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "device=" + device);
}
}
}
我从我的 Activity 启动服务,我希望 BroadcastReceiver 在我连接和断开蓝牙耳机时打印日志消息,但没有打印日志。所以,我想它没有被调用。
public class MyActivity extends Activity {
// Debugging
public final static String TAG ="MyActivity";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(TAG, "Starting service");
startService(new Intent(".MyService"));
}
此外,当我将接收器添加到 Manifest 文件时,会调用 BluetoothEventsReceiver。但据我了解,如果我希望接收器仅在服务运行时处于活动状态,则不需要在清单文件中声明接收器。
我确实在清单文件中设置了权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8"/>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:label="@string/app_name">
<activity android:name="MyActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".MyService" android:process=":remote">
<intent-filter>
<!-- These are the interfaces supported by the service, which
you can bind to. -->
<action android:name=".MyService" />
</intent-filter>
</service>
</application>
</manifest>
请帮助调试我做错了什么。