2015-01-01 164 views
2

對不起,如果我的問題與其他人類似,但我沒有得到解決方案。AsyncTask是一個內部類:獲取onPostExecute()結果在服務

我有兩個類,MainActivity和SMSMonitorService。

AsyncTask是MainActivity的一個內部類。

我想獲得onPostExecute結果並通過短信發送。 sendReplySMS方法在SMSMonitorService上。

MainActivity.java

public class MainActivity extends ActionBarActivity { 

//some code... 

public class DownloadWebpageTask extends AsyncTask<String, Void, String> {   

    @Override 
    protected String doInBackground(String... urls) { 

     // params comes from the execute() call: params[0] is the url. 
     try { 
      return downloadUrl(urls[0]); 
     } catch (IOException e) { 
      return "Unable to retrieve web page. URL may be invalid."; 
     } 
    } 

    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 
    //Extract String between two delimiters 
     String finalResult = StringUtils.substringBetween(result, "extract\":\"", "\"}}}}");    
     String finalResponse = StringEscapeUtils.unescapeJava(finalResult); 

     textView.setText(finalResponse);  
     SMSMonitorService.sendReplySMS(SMSMonitorService.number, finalResponse); //sendReplySMS and number are declared static     

    } 
} 

SMSMonitorService.java

public class SMSMonitorService extends Service { 
//some code... 

public static void sendReplySMS(String number, String responseText) { 

    SmsManager sms = SmsManager.getDefault(); 
    sms.sendTextMessage(number, null, responseText, null, null);   
} 

//some code.. 

的短信從不發送。

我如何發送短信什麼包含onPostExecute結果?

非常感謝您的幫助。

+0

'SMSMonitorService.number'occupy是什麼值? –

+0

'號碼'是始發地址。 – androidBegginer

回答

1

SMSMonitorService是一種服務不是正常的java類,因此您需要使用startService方法啓動發送短信的服務。做到這一點是:

準備意圖在onPostExecute方法發送所有值SMSMonitorService

@Override 
protected void onPostExecute(String result) { 
//....your code 

    Intent intent = new Intent(CurrentActivity.this,SMSMonitorService.class);  
    intent.putExtra("finalResponse", finalResponse); 
    startService(intent); 
} 

SMSMonitorService服務使用

@Override 
public int onStartCommand(Intent intent , int flags , int startId) 
{ 
     super.onStartCommand(intent, flags , startId); 
     String finalResponse = intent.getStringExtra("finalResponse"); 
     if(extras != null) 
     sendReplySMS(SMSMonitorService.number, finalResponse); 
     return START_REDELIVER_INTENT; 
} 

確保您已在AndroidManifest.xml

添加 SMSMonitorService服務

備註:使用IntentService而不是服務,因爲任務完成時,IntentService會停止自我。欲瞭解更多信息,請參閱IntentService

+0

謝謝!但短信從不發送,我想這是因爲我的手機是雙卡,我會嘗試在一個SIM卡手機。 – androidBegginer

相關問題