我有服務,其中包括連接到bluetooth
設備。我從第一次活動中調用此服務。並且服務成功創建並開始。但是當我在第一個活動中使用綁定來調用服務中的方法時,它不會執行。我提到LocalService example未從活動調用的Android服務方法
我的服務代碼:
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
public class LocalBinder extends Binder {
public BluetoothServices getService() {
// Return this instance of LocalService so clients can call public methods
return BluetoothServices.this;
}
}
public void SendData(){
Log.d("msg", "Send msg");
}
我用下面的代碼在我第一個活動:
BluetoothServices mService;
boolean mBound = false;
@Override
public void onStart(){
super.onStart();
Intent btservices = new Intent(getApplication(),BluetoothServices.class);
startService(btservices);
bindService(btservices, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(mBound){
mService.SendData();
}
}
什麼是在上面的代碼中的問題,爲什麼呢?它不是綁定和調用方法?
我的清單:
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:debuggable="true"
android:icon="@drawable/logo_50"
android:theme="@style/app_theme" >
<service android:name="com.example.utilities.BluetoothServices"></service>
<activity
android:name="com.example.pkg.Thisisit"
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>
你看過logcat嗎?任何錯誤或其他有用的日誌? –
@DavidWasser實際上,當我調用if(mBound)內部沒有任何錯誤的方法。但是我在外面調用,得到NullPointer異常。那是因爲沒有綁定。 –
請張貼您的清單。 –