用于多个活动的通用Asynctask

时间:2014-11-08 11:33:17

标签: android android-asynctask

您好我正在尝试在android中实现通用的Asynctask。我有大约8到10个活动,它们使用相同的asynctask和不同的参数。任务适用于每项活动。但是当我尝试实现UI组件时,它会崩溃。这是我的代码任何建议

public class SyncTaskService extends AsyncTask<String, Void, Void> {
    OnAsyncResult onAsyncResult;  
    String ServerResponse;
    String LocalResponse;
    int Operationtype=-1;

    private Context mContext;
    public SyncTaskService (Context context){
        mContext = context;
    }

    public void setOnResultListener(OnAsyncResult onAsyncResult) {  
        if (onAsyncResult != null) {  
            this.onAsyncResult = onAsyncResult;  
        }  
    }  

    @Override
    protected Void doInBackground(String... params) {
        BackGroundTasks Obj_BackGroungTasks = new BackGroundTasks();
        Operationtype = Integer.parseInt(params[0]);
        if (onAsyncResult != null)
        {  
            switch (Operationtype) {
            case 1:
                String  Type = params[2];
                ServerResponse=null;
                ServerResponse= Obj_BackGroungTasks.getdetails(mContext,Type);  
                break;
            default:
                break;
            }
        }
        if (ServerResponse!=null) {  
            onAsyncResult.onResultSuccess(ServerResponse);  
        } else {  
            onAsyncResult.onResultFail(ServerResponse +LocalResponse);  
        }
        return null;
    }  
    public interface OnAsyncResult {  
        public abstract void onResultSuccess(String message);  
        public abstract void onResultFail(String errorMessage); 
    }

这就是我在我的活动中使用它的方式

    SyncTaskService task = new SyncTaskService(getActivity());
    task.setOnResultListener(asynResult);
    task.execute("5",promotype);


OnAsyncResult asynResult = new OnAsyncResult() {  
        @Override  
        public void onResultFail(final String errorMessage) {  
            Log.d("On Result Fail In Activity", ""+errorMessage);
            Toast.makeText(getActivity(), "Task completed", Toast.LENGTH_LONG).show();

        }
        @Override
        public void onResultSuccess(String message) {
            Log.d("On Result Success In Activity", ""+message);
            ServerResponse=message;
            Toast.makeText(getActivity(), "Task completed", Toast.LENGTH_LONG).show(); //craches here
        }  


        };  

这里我们logcat

11-08 16:25:17.705: E/AndroidRuntime(671): FATAL EXCEPTION: AsyncTask #1
11-08 16:25:17.705: E/AndroidRuntime(671): java.lang.RuntimeException: An error occured while executing doInBackground()
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.lang.Thread.run(Thread.java:856)
11-08 16:25:17.705: E/AndroidRuntime(671): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.os.Handler.<init>(Handler.java:121)
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.widget.Toast$TN.<init>(Toast.java:317)
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.widget.Toast.<init>(Toast.java:91)
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.widget.Toast.makeText(Toast.java:233)
11-08 16:25:17.705: E/AndroidRuntime(671):  at packagename.Activity$1.onResultFail(Activity.java:157)
11-08 16:25:17.705: E/AndroidRuntime(671):  at packagename.SyncTaskService.doInBackground(SyncTaskService.java:115)
11-08 16:25:17.705: E/AndroidRuntime(671):  at packagename.SyncTaskService.doInBackground(SyncTaskService.java:1)
11-08 16:25:17.705: E/AndroidRuntime(671):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-08 16:25:17.705: E/AndroidRuntime(671):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-08 16:25:17.705: E/AndroidRuntime(671):  ... 5 more

1 个答案:

答案 0 :(得分:0)

您需要覆盖onPostExecuted()方法。基本上,Asynctask有4个重要的方法,其中三个在UI线程上执行,另一个在后台异步线程中执行:

  1. onPreExecute() - 在UI线程上执行,在执行后台进程之前,您应该在UI上执行任何操作。显示进度条
  2. doInBackground() - 在后台线程上执行,这是你应该做任何重要的任务需要在UI线程上做的地方,这样你的应用程序不会崩溃或你的UI不会挂起。进行API调用以进行下载。请记住,您无法与此处的任何UI元素进行交互!您也可以从此处发布进度。返回每200kb下载的文件大小,以便您的进度条可以更新
  3. onPostExecute() - 在UI线程上执行,您应该在任务执行完之后处理您想要在UI上执行的所有操作。关闭进度条并显示下载文件的结果
  4. onProgressUpdate() - 在doInBackground()发布进度时在UI线程上执行,以便您可以在漫长的后台进程中保持用户更新。在此处更新您的进度条百分比
  5. 希望这会有所帮助。您可能还想查看可能有助于您进一步了解Asynctask的全部功能的文档。

    https://developer.android.com/reference/android/os/AsyncTask.html