java - 两个异步任务在android studio中不能同时工作
问题描述
第一个异步任务 - 从服务器获取图像数据并将其显示到图像查看器中。(查看代码)第二个异步-一直运行。它将检查来自服务器的更新(例如:图片是否更新)如果更新的密钥为真(意味着更新),那么它将再次获取数据,否则它不会做任何事情。但在后台第二个异步任务将持续运行。我使用此代码,但它不工作。帮帮我
public class ImageActivity extends AppCompatActivity {
private ImageView img;
Bitmap decoded;
private String pureFile;
private String data;
private JSONObject post_dict2;
private boolean set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_image);
img = (ImageView) findViewById(R.id.img);
post_dict2 = new JSONObject();
try {
post_dict2.put("device", "ABCDEFGHIJ");
} catch (JSONException e) {
e.printStackTrace();
}
if (post_dict2.length() > 0) {
new jsonTask().execute(String.valueOf(post_dict2));
}
}
public class jsonTask extends AsyncTask<String, String, String> {
String ext;
@Override
protected String doInBackground(String... params) {
String JsonResponse = null;
String JsonDATA = params[0];
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL("");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
Writer writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
writer.close();
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = " ";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String file = stringBuffer.toString();
JSONObject filejsonObject = new JSONObject(file);
JSONObject metaObject = filejsonObject.getJSONObject("meta"); //meta data from JSON file
data = filejsonObject.getString("data"); //this is the main data key from object
ext = metaObject.getString("ext");
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
String run = "run";
//s is the image source data
if (s != null) {
byte[] decodeString = Base64.decode(s, Base64.DEFAULT);
try {
// Creating a new folder in to the device files storage i.e. media storage
File folder = new File(Environment.getExternalStorageDirectory() + "/ImgDownload");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
set = true;
FileOutputStream out = new FileOutputStream(folder + "/" + ".png");
out.write(decodeString);
out.flush();
out.close();
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ImgDownload/" + ".png");
img.setImageURI(uri);
Thread.sleep(10000);
while(run.equals("run")){
new updateFile().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, String.valueOf(post_dict2));
//
}
} else {
Toast.makeText(ImageActivity.this, "File Saving Failed", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Error", e.toString());
}
} else {
Toast.makeText(ImageActivity.this, "Failed To Download", Toast.LENGTH_LONG).show();
}
}
}
private class updateFile extends AsyncTask<String, String, String> {
String ext;
String media;
@Override
protected String doInBackground(String... params) {
String JsonResponse = null;
String JsonDATA = params[0];
// String media = params[1];
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader = null;
try {
Thread.sleep(10000);
URL url = new URL("myurl");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
Writer writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
writer.close();
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = " ";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String file = stringBuffer.toString();
JSONObject filejsonObject = new JSONObject(file);
JSONObject metaObject = filejsonObject.getJSONObject("data"); //meta data from JSON file
// data = filejsonObject.getString("data"); //this is the main data key from object
ext = metaObject.getString("updated");
if (ext.equals("true")) {
Intent in = new Intent(ImageActivity.this,MainActivity.class);
startActivity(in);
}
else {
Thread.sleep( 1 ); //as the pic is not update and stop this async task
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
}
解决方案
从文档:
首次引入时,AsyncTask 在单个后台线程上串行执行。从 DONUT 开始,这被更改为允许多个任务并行运行的线程池。从 HONEYCOMB 开始,任务恢复到在单个线程上执行,以避免并行执行导致的常见应用程序错误。
连续运行的AsyncTask
将占用单线程执行程序并阻止任何其他执行程序AsyncTask
运行。如果你真的想让两个AsyncTask
s 同时运行,你必须使用executeOnExecutor
并提供你自己的多线程执行器来执行它们。(即便如此,它们是否实际上同时运行取决于线程调度程序。)
推荐阅读
- r - 如何在 RStudio 编辑器中删除垂直线?
- operating-system - 为什么此代码中没有加载 gdt?
- javascript - 如何从函数返回之前定义的 useRef 变量?
- swift - UISlider 的自定义形状并在 Swift 5 中更新进度
- php - PHP7 const 在条件(如果)内的要求(外部文件)中定义正在工作 - 为什么?
- ruby - 如何在 ruby 的方法中返回 true 或 false?
- ffmpeg - ffmpeg 将多个 mp3 文件添加到特定位置的 mp4 视频
- c++ - std::vector::reserve 实际上是如何工作的?
- android - 如何使用 href 将 url 传递给 android 应用程序?
- c++ - 我不明白为什么我的 .find 功能不起作用