如何在postExecute中定义全局变量?

时间:2017-09-06 11:55:41

标签: java android android-asynctask

我在AndroidStudio中遇到postExecuteonReceive的问题。这是我的代码:

public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.smap_activity);

    if (MY_BUTTTON_START.equals(intent.getAction())){
        new DownloadTask().execute("http://examplepage.net");
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.smap_activity);
        Log.d("TAG", "TA" + sms);
        remoteViews.setTextViewText(R.id.sms, sms);
        AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, SmapActivity.class), remoteViews);
    }

};

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

    @Override
    protected String doInBackground(String... params) {
        //do your request in here so that you don't interrupt the UI thread
        try {
            return downloadContent(params[0]);
        } catch (IOException e) {
            return "Unable to retrieve data. URL may be invalid.";
        }
    }

    @Override
    public void onPostExecute(String result) {
        String[] smsCzesci = result.split(" ");
        Log.d("TAG", smsCzesci[1]);
        sms = smsCzesci[0];
    }
}

public String downloadContent(String myurl) throws IOException {
    InputStream is = null;
    int length = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        int response = conn.getResponseCode();
        is = conn.getInputStream();
        // Convert the InputStream into a string
        String contentAsString = convertInputStreamToString(is, length);
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[length];
    reader.read(buffer);
    return new String(buffer);
}

总是我的变量&#34; sms&#34; = test但在方法postExecute变量中有我想要的数据。 我想用&#34; sms&#34; onReceive中的变量将窗口小部件的文本设置为此变量,但在onReceive方法上,此变量是默认值。

2 个答案:

答案 0 :(得分:0)

将需要AsyncTask结果的代码移动到onPostExecute方法中:

public class DownloadTask extends AsyncTask<String, Void, String> {
  private final Context context;

  public DownloadTask(final Context context) {
    this.context = context;
  }

  @Override 
  protected String doInBackground(String... params) {
    //do your request in here so that you don't interrupt the UI thread
    try {
        return downloadContent(params[0]);
    } catch (IOException e) {
        return "Unable to retrieve data. URL may be invalid.";
    }
  }

  @Override
  public void onPostExecute(String result) {
    String[] smsCzesci = result.split(" ");
    Log.d("TAG", smsCzesci[1]);
    sms = smsCzesci[0];
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.smap_activity);
    Log.d("TAG", "TA" + sms);
    remoteViews.setTextViewText(R.id.sms, sms);
    AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, SmapActivity.class), remoteViews)
  }
}

使用以下命令调用您的DownloadTask:

new DownloadTask(context).execute("examplepage.net");

答案 1 :(得分:0)

onPostExecute就像一个回调。因此,执行调用后您想要执行的所有操作都应该写在此方法中。在您的代码中,我将删除DownloadTask类并在onReceive方法中写入所有内容。如下所示:

public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.smap_activity);

    if (MY_BUTTTON_START.equals(intent.getAction())){
        AsyncTask downloadTask = new AsyncTask<String, Void, String>(){
            @Override
            protected String doInBackground(String... params) {
                //do your request in here so that you don't interrupt the UI thread
                try {
                    return downloadContent(params[0]);
                } catch (IOException e) {
                    return "Unable to retrieve data. URL may be invalid.";
                }
            }

            @Override
            public void onPostExecute(String result) {
                String[] smsCzesci = result.split(" ");
                Log.d("TAG", smsCzesci[1]);
                sms = smsCzesci[0];

                RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.smap_activity);
                Log.d("TAG", "TA" + sms);
                remoteViews.setTextViewText(R.id.sms, sms);
                AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, SmapActivity.class), remoteViews);
            }
        };
        downloadTask.execute("http://examplepage.net");
    }

};