我是Android開發新手。我已經定義了一個測試應用程序與服務,在這裏我聲明瞭一個廣播接收器用於接收藍牙事件 -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;
}
}
爲
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);
}
}
}
我從活動啓動服務我的廣播接收器的定義,我期望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"));
}
此外,當我接收器添加到清單文件,那麼BluetoothEventsReceiver被調用。但是根據我的理解,如果我希望只有在服務運行時接收器纔有效,我不需要在Manifest文件中聲明接收器。
我有該清單文件中設置
<?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>
請幫助調試我在做什麼錯的權限。
不,我做了這個改變,但仍然沒有調用broadcastreceiver – user1608065