通过向ui发送回调来创建新的异步任务

时间:2014-08-23 21:25:04

标签: android android-asynctask

我有listview,listview的内容变化取决于用户界面 如果我实现回调接收器

,我需要知道如何创建异步任务的新实例
 public interface CallbackReciever {
 public void receiveData(String result);
 }

和异步任务类

public abstract class ConnectDB extends AsyncTask<String, String, String> implements CallbackReciever {

 ProgressDialog pDialog;
 Context context;
 public  String resString;   


 public ConnectDB(Context context) 
 {
    // TODO Auto-generated constructor stub                 
     this.context=context;


}
 @Override
 public abstract void receiveData(String object);
/**
 * Before starting background thread Show Progress Dialog
 * */
@Override
protected void onPreExecute() 
{
    super.onPreExecute();
    pDialog = new ProgressDialog(context);       
    pDialog.setMessage("Loading. Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}
/**
 * getting All products from url
 * */
protected String doInBackground(String... args) 
{
    // getting JSON string from URL     
     resString =Connection.Get(path);

    return resString;

}
/**
 * After completing background task Dismiss the progress dialog
 * **/

protected void onPostExecute(String file_url) 
{
    // dismiss the dialog after getting all products                   
        pDialog.dismiss();              
         if(resString!=null)
         {
             receiveData(resString);
         }

}

}

和MainActivity类

public class MainActivity extends Activity  {

ListView list;
MovieAdapter adapter;
public ArrayList<Movie> data=new ArrayList<Movie>();
public ConnectDB conDB;  

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    final Context t=this.getApplicationContext(); 
    setContentView(R.layout.activity_main);

      conDB= new ConnectDB(MainActivity.this) {

        @Override
        public void receiveData(String result) {
            // TODO Auto-generated method stub
             try {
                 Log.d("ds", result);
                   JSONObject json = null;
                   JSONArray jArray = new JSONArray(result);
                   int i=0;
                   while ( i< jArray.length())                  
                   {
                       final Movie tmp=new  Movie();    
                        json = jArray.getJSONObject(i);
                        tmp.setName(json.getString("name"));
                        tmp.setUrl(json.getString("image"));
                        tmp.setDescription(json.getString("desc"));     
                        tmp.setTime(json.getString("time"));
                        tmp.setTime(Utils.ChangeTolocaclTime(tmp.getTime()));
                        tmp.setWatch(Utils.CanWatch(tmp.getTime()));                                            
                        data.add(tmp);
                        i++;              
                   }                   
               }
               catch (JSONException e) {
                   e.printStackTrace();
               }
             list=(ListView)findViewById(R.id.list);
               if(data.size()==0)
               {
                    Toast.makeText(t, "Server Error", Toast.LENGTH_SHORT).show();
                    list.setVisibility(View.INVISIBLE);   
               }                                                
               // Create custom adapter for listview
               adapter=new MovieAdapter(MainActivity.this,   data,t);                                                            
               //Set adapter to listview
               list.setAdapter(adapter);


        }
    };      

    conDB.execute("MBC2");
}

1 个答案:

答案 0 :(得分:0)

活动应该实现接收器,异步任务应该调用它,如下所示:

public class MyActivity extends Activity implements CallbackReceiver{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //Set everything up

        MyAsyncTask task = new MyAsyncTask();
        task.setOnDataReceivedListener(this);
        task.execute();
    }

    @Override
    public void onReceiveData(String data){
        //Do something with the data        
    }
}

然后,在异步任务中,您可以在onPostExecute中调用receiver方法

public abstract class MyAsyncTask extends AsyncTask<String, String, String>{

    private CallbackReciever receiver = null;

    public void setOnDataReceivedListener(CallbackReciever receiver){
        this.receiver = receiver
    }

    protected void onPostExecute(String file_url) 
    {
        if(receiver != null){
            receiver.onReceiveData(file_url);
        }
    }
}

第二种方法是简单地创建异步任务的匿名内部类并覆盖onPostExecute:

public class MyActivity extends Activity implements CallbackReceiver{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //Set everything up

        MyAsyncTask task = new MyAsyncTask(){
            @Override
            protected void onPostExecute(String file_url){
                //Do what you want with your data here
            }
        };

        task.execute();
    }
}