AsyncTask状态始终在运行

时间:2017-01-25 02:50:24

标签: java android android-asynctask google-play-services

您好,我尝试在AsyncTask中获取Google Play服务广告ID 我阅读了Android AsyncTask API文档和许多stackoverflow答案。我希望首先获得广告ID,然后启动其他流程。 因此,我制作了AdIdAsyncTask,用于在BackgroundThread中获取广告ID并在我的MainActivity中调用。但是我的AsyncTask状态始终是RUNNING。 什么错了?

MainActivity和AdIdAsyncTask

public class MainActivity extends Activity {
    private static final String TAG = "DummyActivity";
    private final long MEDIA_ID = 292929L;
    private final String ACCESS_KEY = "xxxx-xxxx-xxxx";

    private String adId = null;

    private AdContext adContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AdIdAsyncTask task = new AdIdAsyncTask();
        task.execute();
        Log.d(TAG, "task.getStatus=" + task.getStatus());

        if (task.getStatus().equals(AsyncTask.Status.FINISHED)) {
            // do work
        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        Log.i(TAG, "onDestroy");
    }

    public class AdIdAsyncTask extends AsyncTask<Void, Void, Void> {

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

            Log.d(TAG, "doInBackground");
            AdvertisingIdClient.Info idInfo = null;
            try {
                idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
            } catch (GooglePlayServicesNotAvailableException | GooglePlayServicesRepairableException | IOException e) {
                Log.e(TAG, "fetch Google Ads is failed. message=" + e.getMessage());
            }

            String advertisingId = null;
            try {
                advertisingId = idInfo.getId();
            } catch (NullPointerException e) {
                Log.e(TAG, "adId is null. message=" + e.getMessage());
            }

            adId = advertisingId;
            cancel(true);

            Log.i(TAG, "adId=" + advertisingId + ", isCancelled=" + isCancelled());

            return null;
        }

        @Override
        protected void onCancelled() {

            super.onCancelled();
            Log.i(TAG, "onCancelled");
        }

        @Override
        protected void onCancelled(Void aVoid) {

            super.onCancelled(aVoid);
            Log.i(TAG, "onCancelled");
        }
    }
}

日志

D/DummyActivity: task.getStatus=RUNNING
D/DummyActivity: doInBackground
I/DummyActivity: adId=xxxx-xxxx-xxxx, isCancelled=true
I/DummyActivity: onCancelled
I/DummyActivity: onCancelled

SdkVersion

compileSdkVersion 25
minSdkVersion 14
targetSdkVersion 25

1 个答案:

答案 0 :(得分:1)

您好,您可以强制关闭AsyncTask 请使用带有条件的AsyncTask中的以下代码,并在您要停止的活动中调用它,它将停止运行asynk任务

/**
 * Check if asynctask is running, if still running cancel it.
 */
public void forceCancel(){
    if (getStatus().equals(AsyncTask.Status.RUNNING)) {
        cancel(true);
    }
}