Asynctask访问了两个活动

时间:2016-08-24 15:07:36

标签: java android android-asynctask

我有AsyncTaskAPI Google Directions下载路线。任务从第一个Activity开始,在那里我显示时间和用户到某个点的距离,但我的地图是在第二个活动中我需要绘制路线的线。我的问题是如何在两个任务之间维护一个独特的下载任务(如果第一个活动没有完成下载),并在两个活动中访问任务数据。

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;

            }

        }

    }
}

}

1 个答案:

答案 0 :(得分:1)

有很多选择。

  1. 下载第一个活动中的整个项目,将其作为意图数据传递给第二个活动,并在第二个活动中访问。如果需要,您可以将数据存储在内部存储(首选项,数据库或文件中,具体取决于大小),并相应地进行访问。
  2. 您想多次执行任务(一个接一个): 保留对任务对象的引用,并从第二个活动调用中,对第一个进行等待调用。
  3. 想要使用服务吗?没问题。调用服务,下载数据,如果非常大,请存储它们。如果数据很小,请通过广播传递。在活动中访问它们。
  4. 这就是你想要的吗?