AsyncTask是一个内部类:在Service中获取onPostExecute()结果

时间:2015-01-01 03:44:54

标签: java android android-asynctask sms

打扰一下,如果我的问题与其他问题类似,但我还没有解决方案。

我有两个类,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结果的短信?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分: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;
}

确保您在SMSMonitorService

中添加了AndroidManifest.xml服务

注意:使用IntentService代替服务,因为IntentService在完成任务时会自行停止。有关详细信息,请参阅IntentService