有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我对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);
}

总是我的变量“sms”=test,但在方法postExecute中,变量有我想要的数据。 我想在onReceive中使用“sms”变量将小部件的文本设置为此变量,但在onReceive方法中,此变量是默认值


共 (2) 个答案

  1. # 1 楼答案

    将需要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)
      }
    }
    

    使用以下命令调用下载任务:

    new DownloadTask(context).execute("examplepage.net");
    
  2. # 2 楼答案

    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");
        }
    
    };