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
変数iが必要なデータを持っています。 onReceive
に "sms"変数を使用して、この変数にウィジェットのテキストを設定しますが、onReceive
メソッドでは、この変数はデフォルトです。
いつものように答えている:それは2 upvotes – Selvin
こんにちは、私はこの方法を動かしカントonReceiveにしている理由は、私は疑問に思うように多くの時間を尋ねた... onPostExecute' 'に結果に依存して、あなたのコードを移動/ – GlobooX