java - 需要序列化的 EnqueueWork 导致 AsyncTask 崩溃

标签 java android asynchronous serialization android-asynctask

这个项目背后的想法是在将数据库上传到 webService 时运行进度条

我有一个 AsyncTask 执行一些工作,然后调用服务并等待它完成,然后再调用 onPostExecute()

private class UploadDatabaseAsyncTask extends AsyncTask<Void, Long, Void> {

    private AlertDialog dialog;
    private Activity activity;
    private TextView messageView;
    private String location;
    private long maxSize;
    private ProgressBar progressBar;

    UploadDatabaseAsyncTask(Activity activity, long maxSize, String location) {
        super();
        this.location = location;
        this.maxSize = maxSize;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressBar = new ProgressBar(activity);
        progressBar.setMax(100);
        progressBar.setProgress(0);

        dialog = new AlertDialog.Builder(activity).setTitle("Uploading").setView(progressBar).create();
        messageView = dialog.findViewById(android.R.id.message);

       // dialog.show();

        if (activity != null && activity.getView() != null)
        {
            activity.getView().setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });

            activity.getView().setBackgroundColor(ContextCompat.getColor(App.getAppContext(), R.color.grey));
        }
    }

    @Override
    protected void onProgressUpdate(Long... values) {
        messageView.setText(values[0] + " / " + maxSize);

        BigDecimal current = new BigDecimal(values[0]);
        BigDecimal max = new BigDecimal(maxSize);

        BigDecimal progress = current.divide(max, 3, RoundingMode.UP);

        progressBar.setProgress(Integer.valueOf(progress.multiply(new BigDecimal(100)).toString()));
    }

    @Override
    protected Void doInBackground(Void... voids) {

        Intent intent = new Intent();

        final Object lock = new Object();

        final boolean[] active = new boolean[]{true};

        DatabaseSyncService.SyncProgressCallback callback = new DatabaseSyncService.SyncProgressCallback() {
            @Override
            public void onProgress(long progress) {
                onProgressUpdate(progress);
            }

            @Override
            public void onFinish() {
                active[0] = false;
                lock.notify();
            }
        };


        intent.putExtra(DATABASE_ID, callback);
        intent.putExtra("LOCATION", location);
        DatabaseSyncService.enqueueWork(activity, intent);

        synchronized (lock)
        {
            while (active[0])
            {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    protected void onCancelled(Void aVoid) {
        if (activity != null && activity.getView() != null)
        {
            activity.getView().setOnTouchListener(null);
            activity.getView().setBackgroundColor(ContextCompat.getColor(App.getAppContext(), R.color.transparent));
        }
    }

    @Override
    protected void onCancelled() {
        if (activity != null && activity.getView() != null)
        {
            activity.getView().setOnTouchListener(null);
            activity.getView().setBackgroundColor(ContextCompat.getColor(App.getAppContext(), R.color.transparent));
        }
    }

    @Override
    protected void onPostExecute(Void aVoid) { 
        if (activity != null && activity.getView() != null) 
        {
            activity.getView().setOnTouchListener(null);
            activity.getView().setBackgroundColor(ContextCompat.getColor(App.getAppContext(), R.color.transparent))
        }

       AlertDialog.Builder builder = new AlertDialog.Builder(App.getAppContext());
       builder.setTitle("Upload Complete");
       builder.setMessage("You upload was completed!");
       builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) { }
       });

       builder.show();
    }
}

我在尝试序列化 AsyncTask 时遇到了 DatabaseSyncService.enqueueWork() 方法的问题,该方法不起作用。知道为什么要这样做吗?

堆栈跟踪

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: com.app.app, PID: 15935
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:353)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
    at java.util.concurrent.FutureTask.run(FutureTask.java:271)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.app.app.api.SettingApi$UploadDatabaseAsyncTask$2)
    at android.os.Parcel.writeSerializable(Parcel.java:1786)
    at android.os.Parcel.writeValue(Parcel.java:1734)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:801)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1506)
    at android.os.Bundle.writeToParcel(Bundle.java:1181)
    at android.os.Parcel.writeBundle(Parcel.java:841)
    at android.content.Intent.writeToParcel(Intent.java:10199)
    at android.app.job.JobWorkItem.writeToParcel(JobWorkItem.java:117)
    at android.app.job.IJobScheduler$Stub$Proxy.enqueue(IJobScheduler.java:205)
    at android.app.JobSchedulerImpl.enqueue(JobSchedulerImpl.java:53)
    at androidx.core.app.JobIntentService$JobWorkEnqueuer.enqueueWork(JobIntentService.java:343)
    at androidx.core.app.JobIntentService.enqueueWork(JobIntentService.java:523)
    at androidx.core.app.JobIntentService.enqueueWork(JobIntentService.java:501)
    at com.ascsoftware.ascora.sync.DatabaseSyncService.enqueueWork(DatabaseSyncService.java:37)
    at com.ascsoftware.ascora.api.SettingApi$UploadDatabaseAsyncTask.doInBackground(SettingApi.java:291)
    at com.ascsoftware.ascora.api.SettingApi$UploadDatabaseAsyncTask.doInBackground(SettingApi.java:212)
    at android.os.AsyncTask$2.call(AsyncTask.java:333)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
    at java.lang.Thread.run(Thread.java:764) 
 Caused by: java.io.NotSerializableException: com.app.app.api.SettingApi$UploadDatabaseAsyncTask
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1233)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at android.os.Parcel.writeSerializable(Parcel.java:1781)
    at android.os.Parcel.writeValue(Parcel.java:1734) 
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:801) 
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1506) 
    at android.os.Bundle.writeToParcel(Bundle.java:1181) 
    at android.os.Parcel.writeBundle(Parcel.java:841) 
    at android.content.Intent.writeToParcel(Intent.java:10199) 
    at android.app.job.JobWorkItem.writeToParcel(JobWorkItem.java:117) 
    at android.app.job.IJobScheduler$Stub$Proxy.enqueue(IJobScheduler.java:205) 
    at android.app.JobSchedulerImpl.enqueue(JobSchedulerImpl.java:53) 
    at androidx.core.app.JobIntentService$JobWorkEnqueuer.enqueueWork(JobIntentService.java:343) 
    at androidx.core.app.JobIntentService.enqueueWork(JobIntentService.java:523) 
    at androidx.core.app.JobIntentService.enqueueWork(JobIntentService.java:501) 
    at com.app.app.sync.DatabaseSyncService.enqueueWork(DatabaseSyncService.java:37) 
    at com.app.app.api.SettingApi$UploadDatabaseAsyncTask.doInBackground(SettingApi.java:291) 
    at com.app.app.api.SettingApi$UploadDatabaseAsyncTask.doInBackground(SettingApi.java:212) 
    at android.os.AsyncTask$2.call(AsyncTask.java:333) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
    at java.lang.Thread.run(Thread.java:764) 
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
(HTTPLog)-Static: isSBSettingEnabled false

这是回调

public interface SyncProgressCallback extends Serializable {
    void onProgress(long progress);
    void onFinish();
}

最佳答案

此行不起作用:

intent.putExtra(DATABASE_ID, callback);

要将对象放入 Intent 中,该对象必须实现 Serialized/Parcelable 接口(interface)。此外,相同的要求适用于对象的所有字段。

尽管您的callback对象(属于DatabaseSyncService.SyncProgressCallback类型)实现了Serialized,但它是从内部类实例化的>callback = new DatabaseSyncService.SyncProgressCallback() {...}。根据thisjava.io.NotSerializedException 在您的情况下发生,因为:

  • serializing such an inner class instance will result in serialization of its associated outer class instance as well
  • Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

这意味着您必须使外部类 UploadDatabaseAsyncTask 实现 Serializable,而后者又必须应用于其所有字段,依此类推。

这真是令人沮丧。

根据经验,请考虑将一些轻量级/纯数据(而不是具有复杂依赖关系的复杂对象)放入 Intent 中。

回到您的代码,一个简单的解决方法是将callback对象传递给DatabaseSyncService.enqueueWork方法:

    //intent.putExtra(DATABASE_ID, callback);
    intent.putExtra("LOCATION", location);
    DatabaseSyncService.enqueueWork(activity, intent, callback);

enqueueWork()内部直接使用回调,而不是从 Intent 反序列化

关于java - 需要序列化的 EnqueueWork 导致 AsyncTask 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248760/

相关文章:

android - 阻止/禁用最近使用的应用程序按钮

php - PHP (CakePHP) 中的异步处理或消息队列

java - 如果 boolean 值是基于某种逻辑生成的,它可以自动更新吗?

Android O API 26. 新添加的 Location 方法不能按需要工作

android - 如何在 react 原生模式上设置borderRadius?

javascript - 如何从异步调用返回响应?

c# - PostSubmitter 的异步 CTP

java - 使用方法分配 Final 关键字

java - RxJava - 当返回可能为空时使用平面图

java - 泛型在 Java 中被忽略