当前位置: 代码迷 >> java >> 下载多个JSON数组Android
  详细解决方案

下载多个JSON数组Android

热度:50   发布时间:2023-07-31 12:07:23.0

我正在制作一个从Web服务下载图像和文本的android应用,遇到的问题是每次我过渡到新活动时,当我返回到正常工作的默认活动时,新活动都无法下载数据首次启动该应用程序时,同样也无法下载数据,我该如何实施我可以实施的任何开源库? 我有10个活动,所有这些活动都在下载数据,我正在使用AsyncTask。

AsyncTask的execute方法(在较早的版本中,我认为在android 3之后)按顺序工作,这意味着对execute方法的下一次调用要等到当前方法完成为止,如果要更改此行为,必须使用方法executeOnExecutor和ThreadPool这样的方法

yourTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

首先,创建一个名为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

要在下载完成后与您的活动交流,您可以使用接口或处理程序。