我在AndroidStudio中遇到了postExecute
和onReceive
的问题。这是我的代码:如何在postExecute中定义全局变量?
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” =测试,但在方法postExecute
变了,我想要的数据。 我想在onReceive
中使用“sms”变量来将widget的文本设置为这个变量,但是onReceive
方法这个变量是默认的。
一如既往的回答是:将你的代码依赖于结果'onPostExecute' ......问了很多次,我不知道为什么它有2个upvotes – Selvin
嗨,我不能移动方法的onReceive来onPostExecute;/ 对不起。我是begginner;/ – GlobooX