如何让doInBackground()等待AyncTask类中的另一个函数?

时间:2016-10-09 07:00:04

标签: java android multithreading android-asynctask

我有一个自定义的AsyncTask类,用于检查设备是否已授予位置权限,然后获取最后一个已知位置。如果它没有权限,则首先要求用户许可。所以在我的doInBackground函数中,我需要调用mGoogleApiClient.connect(),这将触发onConnected函数。可以看出,doInBackground需要等待onConnected,否则返回null对象lastKnownLocation。我的问题是如何让doInBackground等待onConnected?

public class GetLocationTask extends AsyncTask<Void, Void, Location> implements GoogleApiClient.ConnectionCallbacks
    , GoogleApiClient.OnConnectionFailedListener {

private Context context;
private Activity activity;
private GoogleApiClient mGoogleApiClient;
private Location lastKnownLocation = null; //In case the users reject location permission request, we might initialize the location to something interesting
public AsyncResponseForLocation delegate = null;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;

public GetLocationTask(Activity activity, Context context) {
    this.activity = activity;
    this.context = context;
}

@Override
protected Location doInBackground(Void... params) {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    mGoogleApiClient.connect();
    return lastKnownLocation;
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(context,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context,
            android.Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(activity,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }
    lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onPostExecute(Location location) {
    delegate.processFinish(location);
}


public interface AsyncResponseForLocation {

void processFinish(Location location);}

3 个答案:

答案 0 :(得分:1)

您的流量不正确,在您尝试获取位置之前检查您是否有权限...

{{1}}

当用户需要批准您的权限请求时,您必须处理onRequestPermissionsResult方法:

{{1}}

答案 1 :(得分:0)

实现一个每5秒运行一次的Timertask,用于检查条件isConnected()。

尝试以下代码

   private void startTimer(){
            mTimer1 = new Timer();
            mTt1 = new TimerTask() {
                public void run() {
                    mTimerHandler.post(new Runnable() {
                        public void run(){
                            if(isConnected){

                            //call the Async task
                               }
                        }
                    });
                }
            };

        mTimer1.schedule(mTt1, 1, 5000);
    }

答案 2 :(得分:0)

doInBackground()方法之前添加此内容。 AsyncTask()将首先执行onPreExecute(),然后执行doInBackground()

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // your code hear
    }