Java ImageDownload asynctask在测试asynctask完成之前启动
此处调用imageDownload异步任务::Java ImageDownload asynctask在测试asynctask完成之前启动,java,android,android-asynctask,imagedownload,Java,Android,Android Asynctask,Imagedownload,此处调用imageDownload异步任务:: Log.e("JUST","CHECK"); Log.e("JUST","CHECK"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } 这里是在ImageDownl
Log.e("JUST","CHECK");
Log.e("JUST","CHECK");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这里是在ImageDownload开始执行之前,在测试异步任务完成之前
我无法获得任务的状态。你能告诉我它是如何完成的吗?我从这里了解到的任何情况。你想在任务线程之后执行ImageDownload线程,所以从任务线程的onPostExecute()启动ImageDownload线程执行异步任务时,会启动一个新线程,但您当前的线程仍在运行。它在启动test.async之后立即运行到thread.sleep(1000)中 看起来您在test.async中进行了一些internet下载,正如您可能猜到的,这需要超过1000毫秒(1秒)的时间。这意味着1秒钟后,在第一次异步完成之前,另一个异步正在启动 我猜你想错开他们。在第一个异步的postExecute中,可以生成第二个异步。一种更符合风格的方法是在活动上实现一个接口,该接口在异步完成时接受回调,然后在收到回调后启动第二个异步 下面是一个如何构建此结构的示例
new ImageDownload().execute();
Log.e("imagename",""+imagename);
}
}
接口异步回调{
void onsynccomplete();
}
公共类ExampleActivity扩展活动实现异步回调{
....
public void launchFirstAsync(){
新任务(this.execute();
}
@凌驾
公共void onAsyncComplete(){
//todo启动第二个异步任务;
}
}
类任务扩展了异步任务{
异步回调cb;
任务(异步回调){
this.cb=cb;
}
@凌驾
受保护的Void doInBackground(Void…参数){
//TODO自动生成的方法存根
返回null;
}
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
cb.onAsyncComplete();
}
}看看这里,这对我同样有帮助..将您的url传递到
GetTemplateImageController
并在位图
数组中获取结果
GetTemplateImageController类:
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
@Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
公共类GetTemplateImageController扩展异步任务
{
语境;
私人对话;
公共静态字符串[]imageURL;
公共静态位图bm[]=新位图[15];
//获取JSON的URL
私有静态最终字符串url=”http://xxx.xxx.xxx.xxx/image_master.php?";
私有静态最终字符串TEMPLATE=“TEMPLATE\u images”;
私有静态最终字符串IMAGEURLS=“tempimagename”;
//杰索纳雷
JSONArray loginjsonarray=null;
//来自url的结果
公共GetTemplateImageController(上下文c){
this.mcontext=c;
}
受保护的void onPreExecute(){
//显示进度对话框
super.onPreExecute();
pDialog=新建进度对话框(mcontext);
pDialog.setMessage(“加载”);
pDialog.setCancelable(真);
pDialog.setUndeterminate(真);
pDialog.show();
}
受保护位图[]doInBackground(字符串…arg){
List params=new ArrayList();
add(新的BasicNameValuePair(“templateMasterId”,arg[0].toString());
//创建服务处理程序类实例
ServiceHandler sh=新的ServiceHandler();
//向url发出请求并获得响应
字符串jsonstr=sh.makeServiceCall(url,ServiceHandler.POST,params);
Log.d(“响应:”、“>”+jsonstr);
if(jsonstr!=null)
{
试一试{
JSONObject jsonObj=新的JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(模板);
imageURL=新字符串[loginjsonarray.length()];
对于(int i=0;i随着时间的推移,Android处理并发运行的异步任务的方式发生了一些变化多个异步任务按顺序执行。该行为已被更改为在Android 2.3之前并行运行异步任务。从Android 3.0开始,Android团队认为人们在同步并行运行的任务时不够小心,并将默认行为切换回顺序执行。内部异步任务使用ExecutionService,可根据需要配置为按顺序(默认)或并行运行:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
请尝试以下内容:@singh.jagmohan::tnx代表,但我想知道我的代码中的问题..这是正确的,只是异步任务导致了一些问题Dude u r rite作为解决方案,但您能否告诉我,在我目前的情况下,这个问题即将出现SyncTask由android操作系统本身处理,它们在后台串行或并行执行,因为android操作系统版本正在运行两个asycntask不能保证一个任务会一个接一个地执行,如果您想以这种方式执行,可以重写Executor类及其方法并指定优先顺序
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
@Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]>
{
Context mcontext;
private ProgressDialog pDialog;
public static String[] imageurls;
public static Bitmap bm[]=new Bitmap[15];
// URL to get JSON
private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?";
private static final String TEMPLATE = "Template_images";
private static final String IMAGEURLS = "tempimagename";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
public GetTemplateImageController(Context c) {
this.mcontext=c;
}
protected void onPreExecute() {
// Showing progress dialog
super.onPreExecute();
pDialog=new ProgressDialog(mcontext);
pDialog.setMessage("Loading");
pDialog.setCancelable(true);
pDialog.setIndeterminate(true);
pDialog.show();
}
protected Bitmap[] doInBackground(String... arg) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("templateMasterId",arg[0].toString()));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(TEMPLATE);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(IMAGEURLS);
}
for(int i=0;i<imageurls.length;i++){
bm[i]=DownloadImage(imageurls[i]);
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return bm;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
pDialog.dismiss();
if(result != null)
Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show();
//}
}
}
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );