2017-08-13 81 views
0

我有一個從套接字讀取的AsyncTask。 DoInBackground在活動打開時運行。我想在活動關閉時取消DoInBackground,但在啓動AsyncTask時無法分配變量。 我的類是: -異步任務不兼容類型

private class receivingData extends AsyncTask<String, Void, String> { 

     private volatile boolean exit = false; 
     DataInputStream in; 

     byte[] fullBuffer = new byte[7]; 
     byte[] buffer = new byte[100]; // buffer store for the stream 
     int bytes; // bytes returned from read() 
     int bytesCount = 0; 

     @Override 
     protected String doInBackground(String... params) { 
      try { 
       if (socket.isConnected()) { 
        in = new DataInputStream(socket.getInputStream()); 
        //Log.d(TAG,"In async receive data run, connected"); 
       } 
      }catch(Exception e){ 
       Log.d(TAG, "in async receiveData - run exception - " + e.toString()); 
      } 
      while(!exit){ 
       try { 
        bytes = in.read(buffer);  // Get number of bytes and message in "buffer" 
        System.arraycopy(buffer,0,fullBuffer,bytesCount,bytes); 
        bytesCount = bytesCount + bytes; 
        if(bytesCount >= 7) { 
         hdt.obtainMessage(RECEIVED_MESSAGE, bytesCount, -1, fullBuffer).sendToTarget();  // Send to message queue Handler 
         Log.d("DTA Read - ", "Message sent"); 
         bytesCount = 0; 
         Log.d("DTA Read - ", "bytesCount re-set"); 
        } 
       }catch(Exception e){ 
        Log.d(TAG, "Read Error - " + e.toString()); 
       } 
      } 
      return "Executed"; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
     } 

     @Override 
     protected void onPreExecute() {} 

     @Override 
     protected void onProgressUpdate(Void... values) {} 
    } 

我聲明瞭一個變量,啓動的AsyncTask這樣。

private DateTimeActivity.receivingData mRecData; 

// start async task to receive data 
     mRecData = new DateTimeActivity.receivingData().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 

這給了我一個不兼容的類型錯誤。

它說 -

Required DateTimeActivity.receivingData 

找到

android.os.asyncTask <java.lang.string, java.lang.void, ava.lang.string> 

任何幫助,將不勝感激。

回答

1

您需要首先分配您的變量,然後啓動的AsyncTask:

// start async task to receive data 
    mRecData = new DateTimeActivity.receivingData(); 
    mRecData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);