[英]How to run binded service method in AsyncTask android
嗨,我有一个问题,我想在我的AsyncTask中使用Running服务方法。
public class SplashActivity extends Activity {
boolean bBindedBluetooth;
static BTService Bluetooth;
...
@Override
protected void onStart() {
super.onStart();
new ActivityStarter().execute("");};@Override
protected void onStop() { super.onStop(); unbindMyService("onStop"); };
@Override
protected void onPause(){ super.onPause(); unbindMyService("onPause"); };
@Override
protected void onDestroy() { super.onDestroy(); unbindMyService("onDestroy"); };
...
private class ActivityStarter extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
try{
Intent btIntent = new Intent(SplashActivity.this, BTService.class);
bindService(btIntent, scConnection, Context.BIND_AUTO_CREATE);
//Bluetooth.initService();
//Bluetooth.StartBluetoothConnection();
} catch (Exception e){
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
Intent MainActivityIntent = new Intent(SplashActivity.this, MainActivity.class);
SplashActivity.this.startActivity(MainActivityIntent);
SplashActivity.this.finish();
}
}
private void unbindMyService(String methodNameForLog){
try{
if(bBindedBluetooth){
unbindService(scConnection);
bBindedBluetooth = false;
}
}catch(Exception e){
Log.e( this.getClass().getSimpleName(), methodNameForLog + " " + e.getMessage() );
}
}
ServiceConnection scConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
bBindedBluetooth = false;
Bluetooth = null;
}
public void onServiceConnected(ComponentName cnName, IBinder ibService) {
bBindedBluetooth = true;
LocalBinder mLocalBinder = (LocalBinder)ibService;
Bluetooth = mLocalBinder.getServerInstance();
}
};
}
问题出在这里我不知道如何解决这个问题。
//Bluetooth.initService();
//Bluetooth.StartBluetoothConnection();
AD3。 当我尝试运行Bluetooth.initService时LOGCAT告诉我一个:
执行doInBackground()时发生错误;
在initService()中我没有代码(它只用于测试)
请帮忙。
你必须将你对Bluetooth
对象的使用转移到onServiceConnected()
因为那是在服务实际绑定的时候,这可能会或者可能不会在你调用bindService()
之后立即发生
您还可以在onStart()
的AsyncTask
外部绑定服务,并从onServiceConnected()
启动AsyncTask
绑定到服务仍然使用回调,并且在UI线程上不应该很重。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.