Bewertung: 5 / 5

Stern aktivStern aktivStern aktivStern aktivStern aktiv
 

Um folgende Android Studio Meldung "This AsyncTask class should be static or leaks might occur" zu vermeiden, kann man entsprechend in einen Async Task über eine Hilfsklasse sämtliche Parameter übergeben.

Hier ein Beispiel (wobei location bereits ermittelt wurde; siehe diverse Android Foren/Hilfen auf Google). Mittels result wird das Ergebnis von der Methode doInBackground in die Methode postExecute vom AsyncTask übergeben

 String link = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+location.getLatitude()+","+location.getLongitude()+"&key=YourAPIKey";
 GetLocationDownloadTask getLocation = new GetLocationDownloadTask();
 MyTaskParams params = new MyTaskParams(context, link, "");
 getLocation.execute(params);
Source code

//private class to put parameter to AsyncTask
 private static class MyTaskParams {
 Context context;
String urlString;
 String result;
 
 MyTaskParams(Context context, String urlString, String result) {
 this.context = context;
this.urlString = urlString;
 this.result = result;
 }
 }
 
 public static class GetLocationDownloadTask extends AsyncTask<MyTaskParams, Void, MyTaskParams> {
 
 @Override
 protected MyTaskParams doInBackground(MyTaskParams... params) {
String urlString = params[0].urlString;  //fetch parameter; other parameter for example params[0].context we do not need in doInBackground method
 StringBuilder sb = new StringBuilder();
 URL url;
 HttpURLConnection urlConnection;
 try {
 url = new URL(urlString);
 urlConnection = (HttpURLConnection) url.openConnection();
 InputStream is = urlConnection.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(is);
 
 int data = inputStreamReader.read();
 
 while (data != -1) {
 char curr = (char) data;
 //result += curr;
 sb.append(curr);
 data = inputStreamReader.read();
 }
 params[0].result = sb.toString();
 return params[0];
 } catch (Exception e) {
 e.printStackTrace();
 }
 return null;
 }
 
 @Override
 protected void onPostExecute(MyTaskParams myTaskParams) {
 super.onPostExecute(myTaskParams);
 
 if (myTaskParams != null) {
 try {
 JSONObject locationObject = new JSONObject(myTaskParams.result);
 JSONObject locationAddress = locationObject.getJSONArray("results").getJSONObject(0).getJSONObject("formatted_address");
 updateAddress(locationAddress.toString(), myTaskParams.context);
 } catch (JSONException e) {
 e.printStackTrace();
 }
 }
 }
 
 private void updateAddress(String address, Context context) {
 //Log.d(TAG, "updateAddress");
 
 //Send to your app broadcast receiver for new address
 Intent filterRes = new Intent();
 filterRes.setAction("YOURACTION");
 filterRes.putExtra("address", address);
 context.sendBroadcast(filterRes);
 }
 
 }
Source code