我有这个服务类:
public class BluetoothService extends Service {
private static Activity mActivity;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(bluetoothReceiver, intentFilter);
}
@Override
public void onDestroy() {
if (bluetoothReceiver != null) {
this.unregisterReceiver(bluetoothReceiver);
}
}
@Override
public void onStart(Intent intent, int startid) {
//
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public static BroadcastReceiver bluetoothReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
TextView tvStatus = (TextView) mActivity.findViewById(R.id.tvtatus);
Messaging.appendMessage(tvStatus, Bluetooth.getDeviceState(state));
if (Bluetooth.isBluetoothEnabled()) {
Messaging.appendMessage(tvStatus, Bluetooth.showMessage());
}
}
}
};
}
在我的活动课上,我有这个:
public class MainActivity extends Activity {
private TextView tvStatus;
private Intent intentBluetooth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView)findViewById(R.id.tvtatus);
intentBluetooth = new Intent(this, BluetoothService.class);
startService(intentBluetooth);
}
}
Service 类中的 BroadcastReceiver 方法 (bluetoothReceiver) 永远不会被调用。我不知道为什么。如果我首先在 Activity 中拥有 IntentFilter 和 BroadcastReceiver 代码,那么它可以工作 - 但不是在 [单独的] 服务中。我难住了。
我的 AndroidManifest.xml 是:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.onegoal.androidexample"
android:versionCode="1"
android:versionName="1.0.0"
android:installLocation="auto"
android:hardwareAccelerated="true">
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:debuggable="true" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BluetoothService">
</service>
</application>
</manifest>
我是 Android 新手,所以我所做的可能不是最好的。希望可以有人帮帮我。