在另一个类中使用asynctask

时间:2013-01-10 06:03:18

标签: android android-asynctask

我在活动中使用asynctask编写了一些代码。但是希望在服务类中重用相同的代码,该服务类是在单独的java文件上编写的。我试图在单独的java文件中编写代码,以便我可以在两者上使用它。但它没有为asynctask锻炼。有没有办法这样做。如果有的话,请提供一些教程。谢谢。代码是这样的。

MainActivity.java

//import java.util.Calendar;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class AndroidJSONParsingActivity extends ListActivity {

    protected static final String TAG_PRODUCTS = "products";
    protected static final String TAG_CID = "cid";
    public static final String TAG_NAME = "name";

    JSONArray products = null;
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
    public static String url = "http://ensignweb.com/sandbox/app/comment11.php";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startService(new Intent(this, UpdateService.class));
        new Messages().execute();
        Intent intent = new Intent(this,UpdateService.class);
        PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, pIntent);        

    }

@Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        new Messages().execute();
    }
    //Belongs to update service
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
//      stopService(new Intent(this, UpdateService.class));
    }

    class Messages extends AsyncTask<Void, Void, Void> {
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        ProgressDialog dialog = null;
        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            dialog.setTitle("Progressing");
            dialog.setMessage("be patient");
            JSONParser JSP = new JSONParser();
            JSONObject json = JSP.getJSONFromUrl(url);

            try{
                products = json.getJSONArray(TAG_PRODUCTS);
                for(int i = products.length()-1; i >=0; i--){
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String cid = c.getString(TAG_CID);
                    String name = c.getString(TAG_NAME);
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_CID, cid);
                    map.put(TAG_NAME, name);

                    // adding HashList to ArrayList
                    contactList.add(map);
                    Log.d("value", contactList.toString());
                }
        }catch(JSONException e){
            e.printStackTrace();
        }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
//          dialog.dismiss();
            ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, contactList,
                    R.layout.list_item,
                    new String[] { TAG_NAME,}, new int[] {
                            R.id.name});
            AndroidJSONParsingActivity.this.setListAdapter(adapter);
        }
    }   
}

2 个答案:

答案 0 :(得分:1)

我不确定为什么需要AsyncTask服务。但是,您可以这样做但是必须确保在从其他活动运行时不要尝试执行它。此外,他们需要发送相同类型的参数。通常,您最好为需要它的不同类创建单独的任务,但它可以工作。为了安全起见,您需要在销毁活动时在cancel()上调用AsyncTask,以确保在从其他类调用活动时它不会运行。除此之外,我们需要查看AsyncTask的代码以及如何从两个类中调用它。

修改

您可以创建一个扩展AyncTask的单独类,并从您的活动中调用该类。内部类的好处是你可以访问成员变量。您遇到的另一个问题是尝试从progressBar更新doInBackground()。你无法从那里操纵UI。您可以使用其他3种AsyncTask方法(onProgressUpdate()onPostExecute()onPreExecute())。

要为AsyncTask创建单独的类文件,请创建一个构造函数来接受上下文,以便您有办法操纵Activity UI

Public class MyAsyncTask extends AsyncTask
{

private Context context; 

public MyAsyncTask(Context context) {
    this.context = context;
}

// Add your AsyncTask methods and logic
//you can use your context variable in onPostExecute() to manipulate activity UI
}`

答案 1 :(得分:0)

你不需要在服务中使用asynchTask,这项工作可以通过intentService来完成

创建一个默认的工作线程,该线程执行与应用程序主线程分开的传递给onStartCommand()的所有意图。

        public class HelloIntentService extends IntentService {

  /** 
 * A constructor is required, and must call the super IntentService(String)
  * constructor with a name for the worker thread.
 */
  public HelloIntentService() {
     super("HelloIntentService");
   }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
  * stops the service, as appropriate.
   */
 @Override
  protected void onHandleIntent(Intent intent) {
  // Normally we would do some work here, like download a file.
  // For our sample, we just sleep for 5 seconds.
  long endTime = System.currentTimeMillis() + 5*1000;
  while (System.currentTimeMillis() < endTime) {
      synchronized (this) {
          try {
              wait(endTime - System.currentTimeMillis());
          } catch (Exception e) {
          }
      }
  }
 }
}

这是参考, http://developer.android.com/guide/components/services.html