android - 在另一个类中使用 asynctask

标签 android android-asynctask

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

主 Activity .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);
        }
    }   
}

最佳答案

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

编辑

您可以创建一个单独的类来扩展 AyncTask 并从您的 Activity 中调用它。内部类的好处是您可以访问成员变量。您遇到的另一个问题是尝试从 doInBackground() 更新您的 progressBar。您不能从那里操作 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
}`

关于android - 在另一个类中使用 asynctask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14251735/

相关文章:

java - 正确使用 AsyncTasks 并处理 View 和 Activity 所需的对象

java - DefaultHttpClient AsyncTask 类超时异常

android - ASyncTask 并从一个返回字符串数组值

android - 应用程序关闭后如何在 fragment 中停止 AsyncTask

java - 替换 ArrayAdapter 列表

android - 从 SharedPreferences 中删除条目后未通知 OnSharedPreferenceChangeListener

android:将某些东西从广播接收器传回 Activity

android - 实现覆盖 Activity 的倒数计时器

java - 安卓 BottomSheetBehavior setState() NullPointerException

android - 模块中未列出的模拟依赖项