1-я асинхронная задача - получить данные изображения с сервера
и показывает его в просмотрщике изображений. (проверить код) 2-й
асинхронный - работает все время. это будет проверять обновление от
сервер (например: изображение обновлено или нет), если обновленный ключ верен
(означает обновление), тогда он будет получать данные еще раз, иначе он не будет делать
что-нибудь . но в фоновом режиме 2-я асинхронная задача будет работать постоянно.
Я использую этот код, но он не работает. помоги мне
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;
}
}
}