您好我有问题我想在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()中我没有代码(它只用于测试)
请帮忙。
答案 0 :(得分:0)
您必须将Bluetooth
对象的使用转移到onServiceConnected()
,因为这是服务实际绑定的时间,这可能会在您致电bindService()
之后立即发生,也可能不会立即发生p>
您还可以绑定AsyncTask
中onStart()
之外的服务,然后从AsyncTask
onServiceConnected()
绑定到服务仍然使用回调,并且在UI线程上不应该很重。