gpt4 book ai didi

java - 为两个 Activity 访问 Asynctask

转载 作者:行者123 更新时间:2023-12-01 09:34:24 25 4
gpt4 key购买 nike

我有一个 AsyncTask 用于从 API Google Directions 下载路线。该任务从第一个 Activity 开始,我在其中显示用户到某个点的时间和距离,但我的 map 位于第二个 Activity 中,我需要在其中绘制路线。我的问题是如何在两个任务之间维护唯一的下载任务(如果第一个 Activity 中下载尚未完成),并在两个 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. 在第一个 Activity 中下载整个项目,将其作为 Intent 数据传递给第二个 Activity ,并在第二个 Activity 中进行访问。如果需要,您可以将数据存储在内部存储(首选项、数据库或文件,具体取决于大小)中,并进行相应的访问。
  2. 您想要多次执行该任务(一次又一次):保留对任务对象的引用,并从第二个 Activity 调用中,对第一个 Activity 进行等待调用。
  3. 想要使用服务吗?没问题。调用服务,下载数据,如果数据很大则存储它们。如果数据较小,则通过广播传递。在 Activity 中访问它们。

这是你想要的吗?

关于java - 为两个 Activity 访问 Asynctask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39127023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com