2016-08-24 60 views
0

我有一個AsyncTaskAPI Google Directions下載路由。該任務從第一個Activity開始,我在這裏顯示用戶到一個點的時間和距離,但是我的地圖位於第二個活動中,我需要繪製路線。我的問題是如何在兩個任務之間維護唯一的下載任務(如果下載沒有在第一個活動中完成),並訪問兩個活動的任務數據。Asynctask訪問兩個活動

public class DownloadDirections { 

String urlDownload; 
PolylineOptions lineOptions = null; 
Context context; 
String mTime; 
String mDistance; 

public DownloadDirections (Context context, String urlDownload){ 
    this.urlDownload = urlDownload; 
    this.context = context; 

    new DownloadDirectionsTask().execute(urlDownload); 
} 

// Fetches data from url passed 
private class DownloadDirectionsTask extends AsyncTask<String, Void, String> { 

    // Downloading data in non-ui thread 
    @Override 
    protected String doInBackground(String... url) { 

     // For storing data from web service 
     String data = ""; 

     try { 
      // Fetching the data from web service 
      data = downloadUrl(url[0]); 
     } catch (Exception e) { 
      Log.d("Background Task", e.toString()); 
     } 
     return data; 
    } 

    // Executes in UI thread, after the execution of 
    // doInBackground() 
    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     ParserTask parserTask = new ParserTask(); 

     // Invokes the thread for parsing the JSON data 
     parserTask.execute(result); 

    } 
} 


/** 
* A method to download json data from url 
*/ 
private String downloadUrl(String strUrl) throws IOException { 
    String data = ""; 
    InputStream iStream = null; 
    HttpURLConnection urlConnection = null; 
    try { 
     URL url = new URL(strUrl); 

     // Creating an http connection to communicate with url 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     // Connecting to url 
     urlConnection.connect(); 

     // Reading data from url 
     iStream = urlConnection.getInputStream(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

     StringBuffer sb = new StringBuffer(); 

     String line = ""; 
     while ((line = br.readLine()) != null) { 
      sb.append(line); 
     } 

     data = sb.toString(); 

     br.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     iStream.close(); 
     urlConnection.disconnect(); 
    } 
    return data; 
} 

/** 
* A class to parse the Google Places in JSON format 
*/ 
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> { 

    // Parsing the data in non-ui thread 
    @Override 
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) { 

     JSONObject jObject; 
     List<List<HashMap<String, String>>> routes = null; 

     try { 
      jObject = new JSONObject(jsonData[0]); 
      DirectionsJSONParser parser = new DirectionsJSONParser(); 

      // Starts parsing data 
      routes = parser.parse(jObject); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return routes; 
    } 

    // Executes in UI thread, after the parsing process 
    @Override 
    protected void onPostExecute(List<List<HashMap<String, String>>> result) { 
     ArrayList<LatLng> points = null; 
     MarkerOptions markerOptions = new MarkerOptions(); 
     String distance = ""; 
     String duration = ""; 

     if(result != null) { 
      if (result.size() < 1) { 
       Toast.makeText(context, "No Points", Toast.LENGTH_SHORT).show(); 
       return; 
      } 
     } 

     if(result != null) { 
      // Traversing through all the routes 
      for (int i = 0; i < result.size(); i++) { 
       points = new ArrayList<LatLng>(); 
       lineOptions = new PolylineOptions(); 

       // Fetching i-th route 
       List<HashMap<String, String>> path = result.get(i); 

       // Fetching all the points in i-th route 
       for (int j = 0; j < path.size(); j++) { 
        HashMap<String, String> point = path.get(j); 

        if (j == 0) { // Get distance from the list 
         distance = (String) point.get("distance"); 
         continue; 
        } else if (j == 1) { // Get duration from the list 
         duration = (String) point.get("duration"); 
         continue; 
        } 

        double lat = Double.parseDouble(point.get("lat")); 
        double lng = Double.parseDouble(point.get("lng")); 
        LatLng position = new LatLng(lat, lng); 

        points.add(position); 
       } 

       // Adding all the points in the route to LineOptions 
       lineOptions.addAll(points); 
       lineOptions.width(2); 
       lineOptions.color(Color.RED); 
       mTime = duration; 
       mDistance = distance; 

      } 

     } 

    } 
} 

}

+3

如果你想下載互聯網數據並訪問它,當你在兩個活動之間進行導航時,你應該使用一項服務。 – adalPaRi

回答

1

有很多的選擇。

  1. 下載的第一個活動的整個項目,把它傳遞給第二和意向數據,並在第二個活動的訪問。如果需要,您可以將數據存儲在內部存儲器中(首選項,數據庫或文件取決於大小),並相應地訪問。
  2. 您想多次執行任務(一個接一個): 保留對任務對象的引用,並從第二個活動調用中,對第一個進行等待調用。
  3. 想使用服務嗎?沒問題。調用服務,下載數據,如果數據很大,請將其存儲起來。如果數據很小,請通過廣播傳遞。在活動中訪問它們。

這是你想要的嗎?