2

我在活动中使用 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);
        }
    }   
}
4

2 回答 2

1

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

编辑

您可以创建一个单独的类来扩展AyncTask并从您的活动中调用它。内部类的好处是您可以访问成员变量。您遇到的另一个问题是尝试progressBar从您的doInBackground(). 你不能UI从那里操纵。不过,您可以使用其他 3AsyncTask种方法(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
}`
于 2013-01-10T06:26:55.053 回答
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

于 2013-01-10T06:39:34.880 回答