2011-05-19 150 views
3

我試圖從嵌入在服務中的異步任務向我的主要活動發送消息。基本上,異步任務必須阻止輸入,並且不能在主Activity活動線程中運行(從下面的示例代碼中刪除了阻止)。當數據進入時,我需要將它發送到主要活動。我發現下面發送的消息從來沒有成功。如果答案是在異步任務中移動綁定,那麼您怎麼做?如果可能的話,指向示例代碼將是一個很大的幫助。從AsyncTask發送的消息

public class InputService2 extends Service { 
int bufferSize = 1024; 
Process process; 
DataInputStream os; 
TextView inputView; 
byte[] buffer = new byte[bufferSize]; 
private MyAsyncTask inputTask = null; 
     public void onCreate(){ 
      inputTask = new MyAsyncTask(); 
      inputTask.execute((Void[])null); 

     } 
     private class MyAsyncTask extends AsyncTask<Void,Void,Void> { 

     int mValue = 0; 
     static final int MSG_SET_VALUE = 3; 
      protected void onProgressUpdate(Void progress){ 

      } 

      protected void onPostExecute(Void result) { 

      } 

      protected Void doInBackground(Void... params) { 

       int i = 0; 


       try { 
        mValue = 0x23; 
      Message message =  Message.obtain(null,MSG_SET_VALUE,mValue,0); 
        mMessenger.send(message); 
       } 
       catch (Exception e) { 

       } 


      } 
     } 
     class IncomingHandler extends Handler { 
      @Override 
      public void handleMessage(Message msg) { 
      } 
     } 
     final Messenger mMessenger = new Messenger(new IncomingHandler()); 
     public IBinder onBind(Intent intent) { 
      return mMessenger.getBinder(); 
     } 

} 

下面是活動中:

class IncomingHandler extends Handler { 
    @Override 
    public void handleMessage(Message msg) { 
     Context context = getApplicationContext(); 
     int duration = Toast.LENGTH_LONG; 
     Toast toast = Toast.makeText(context, msg.arg1, duration); 
     toast.show(); 
    } 
} 

boolean mBound; 
private ServiceConnection mConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     // This is called when the connection with the service has been 
     // established, giving us the object we can use to 
     // interact with the service. We are communicating with the 
     // service using a Messenger, so here we get a client-side 
     // representation of that from the raw IBinder object. 
     mService = new Messenger(service); 
     mBound = true; 
    } 

    public void onServiceDisconnected(ComponentName className) { 
     // This is called when the connection with the service has been 
     // unexpectedly disconnected -- that is, its process crashed. 
     mService = null; 
     mBound = false; 
    } 
}; 

protected void onStart() { 
    super.onStart(); 
    // Bind to the service 
    bindService(new Intent(this, InputService2.class), mConnection, 
      Context.BIND_AUTO_CREATE); 
} 

回答