我正在创建一个从Web服务下载图像和文本的Android应用程序,我遇到的问题是,每当我转换到新活动时,新活动无法下载数据,当我返回到我的默认活动时当应用程序首次启动时工作正常也无法下载数据,我如何处理这个问题,我可以实现的任何开源库?我有10个活动,所有这些活动都在下载数据,我使用的是AsyncTask。
答案 0 :(得分:1)
执行AsyncTask的方法(在早期版本中我认为在android 3之后)顺序工作 这意味着下一次执行execute方法的调用将等待,直到当前的方法结束 如果要更改此行为,则必须使用方法executeOnExecutor和ThreadPool 像这样的东西
yourTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
答案 1 :(得分:0)
首先,创建一个名为MyService
的新类,例如扩展Service
:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("","startcommand is called");
return START_STICKY; //restart automatically if service destroyed
}
/*your code write it here for downloading your images and text ,you should
use asyntask inside it*/
public void startDownloading(){
}
//this IBinder is used for communicating with your activity
private final IBinder binder=new MyBinder();
//this use for binding with activity
@Override
public IBinder onBind(Intent intent) {
return binder;
}
/*this class used only by the activity to access the service through it
,will work only this way*/
public class MyBinder extends Binder {
public MyService getService(){
return MyService.this;
}
}
}//end class
现在,在oncreate
方法的每项活动中,请编写以下代码
Intent intent = new Intent(this, MyService.class);
//starting the service
startService(intent);
/*bind service to the actvitiy so that they can communicate between each
other*/
bindService(intent, serviceconnection, Context.BIND_AUTO_CREATE);
您需要一个ServiceConnection
来获取MyService
的引用,并告诉您服务何时连接或断开连接:
//to know when service is connected or disconnected to this activity
private ServiceConnection serviceconnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder mybinder=(MyService.MyBinder)service;
myservice=mybinder.getService();//a reference of MyService
myservice.startDownloading();//your function for downloading image
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("","disconnected to service");
}
};
不要忘记使用onDestroy
方法或onPause
方法取消绑定服务:
unbindService(serviceconnection); //unbind service from the activity
要在下载完成后与您的活动进行通信,您可以使用界面或处理程序。