如何在AsyncTask android中运行绑定服务方法

时间:2015-03-04 22:20:48

标签: java android android-asynctask android-service

您好我有问题我想在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();
  1. 运行BluetoothService - 工作
  2. 绑定蓝牙服务 - 工作
  3. 运行必须将我连接到BluetoothDevice的AsyncTask。
  4. 1-3运行MainActivity后。 - 作品
  5. AD3。当我尝试运行Bluetooth.initService时LOGCAT告诉我一个:

    执行doInBackground();

    时发生错误

    在initService()中我没有代码(它只用于测试)

    请帮忙。

1 个答案:

答案 0 :(得分:0)

您必须将Bluetooth对象的使用转移到onServiceConnected(),因为这是服务实际绑定的时间,这可能会在您致电bindService()之后立即发生,也可能不会立即发生p>

您还可以绑定AsyncTaskonStart()之外的服务,然后从AsyncTask

开始onServiceConnected()

绑定到服务仍然使用回调,并且在UI线程上不应该很重。