有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个自定义的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,
            安卓.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context,
            安卓.Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(activity,
                new String[]{安卓.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);}

共 (2) 个答案

  1. # 1 楼答案

    你的流量不正确,在你尝试获取位置检查之前,如果你有权限

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.ACCESS_FINE_LOCATION)) {
    
        // Show an expanation to the user *asynchronously*   don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    
    } else {
    
        // No explanation needed, we can request the permission.
    
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_LOCATION);
    
        // MY_PERMISSIONS_REQUEST_LOCATION is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    } else{
     // Run your async task here(you have got location permission already)
     new GetLocationTask(Activity).execute();
    }
    

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

    @Override
    public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                // permission was granted, Execute the asynctask here
                new GetLocationTask(Activity).execute();
            } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    
        // other 'case' lines to check for other
        // permissions this app might request
    }
    }
    
  2. # 2 楼答案

    执行一个Timertask,每5秒运行一次,以检查条件是否已连接()

    试试下面的代码

       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);
        }