我有包括连接到bluetooth
设备的服务。我从我的第一个活动中调用此服务。并且服务成功创建并启动。但是当我在第一个活动中使用绑定来调用服务中的方法时,它没有执行。我提到了LocalService 示例
我的服务代码:
// 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>