Asynctask在运行时权限中多次加载

时间:2017-08-18 07:07:08

标签: android android-asynctask runtime-permissions

我是android的初学者。我试图在Marshmallow( NearLocations.execute())中授予Runtime权限后调用特定的Async-task,但是如果我授予了权限(允许)我的异步任务多次调用,进度条继续加载。建议我如何解决这个问题?

public class DashViewScreen extends Fragment implements OnRefreshListener {
    public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
    String[] permissions = new String[] {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION };
    Location mLocation;
    View v1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.dashboard_layout, container, false);
        initialUISetup();
        Toast.makeText(getActivity(), "Oncreate", Toast.LENGTH_SHORT).show();
        checkPermission(getActivity());
        return v;
    }

    @SuppressWarnings("deprecation")
    public void initialUISetup() {
        //Async task one
        mTask = new Information(v, false);
        mTask.execute();
    }

    private class Information extends AsyncTask<Void, Void, Object> {
        private ProgressDialog mProgressDialog;
        private View v1;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(getActivity(), "Retrieve Acc", Toast.LENGTH_SHORT).show();
            mTask = null;
        }

        @Override
        protected Object doInBackground(Void... params) {
            AccountInformation results = null;
            results = AppUtil.drex.AccountInformation(v1.getContext());
            return results;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            mAccInfo = (AccountInformation) result;
            //Async task two
            mTask = new Messages().execute();
        }
    }

    private boolean checkPermission(Activity act) {
        int result;
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String p : permissions) {

            result = ContextCompat.checkSelfPermission(act, p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            } else {
                if (lastLocation == null) {
                    locationManager = (LocationManager) v.getContext()
                            .getSystemService(Context.LOCATION_SERVICE);

                    gpsLocationListener = createListener(v);
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER, 0, 0,
                            gpsLocationListener);
                }
                //Async three
                new NearLocations(lastLocation, v).execute();
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {

            requestPermissions(
                    listPermissionsNeeded.toArray(new String[listPermissionsNeeded
                            .size()]), MULTIPLE_PERMISSIONS);

            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
            String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        switch (requestCode) {
            case MULTIPLE_PERMISSIONS: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    lastLocation = AppUtil.getMyLastLocation(v.getContext());

                    if (lastLocation == null) {
                        locationManager = (LocationManager) v.getContext()
                                .getSystemService(Context.LOCATION_SERVICE);

                        lastLocation = AppUtil.getBestLocation(v.getContext(),
                                locationManager);

                        gpsLocationListener = createListener(v);
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER, 0, 0,
                                gpsLocationListener);
                    }
                    new NearLocations(lastLocation, v).execute();
                } else {
                    AppUtil.saveBoolToPrefs(getActivity(), "stopPopup", true);
                }
                return;
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions,    grantResults);
    }    
}

3 个答案:

答案 0 :(得分:0)

我读了你的代码,但我无法理解每一件事。 我有一个类像异步任务一样运行。我更喜欢使用它。

public abstract class AsyncTaskSubhi {

Activity activity;
MaterialDialog dialog;
String processName;
public AsyncTaskSubhi(Activity activity, String processName) {
    this.activity = activity;
    this.processName=processName;
}


public void onPreExecute() {
    dialog= new MaterialDialog.Builder(activity)
            .title("*****")
            .content(processName+"is running").cancelable(false)
            .progress(true, 0).autoDismiss(false)
            .show();
}

public abstract void doInBackground();

public void execute() {
    try {
         new Thread(new Runnable() {
            @Override
            public void run() {
                if (activity != null)
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            onPreExecute();
                        }
                    });

                doInBackground();

                if (activity != null)
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            onPostExecute();
                        }
                    });

            }
        }).start();

    }catch (Exception e){
        dialog.dismiss();
    }


}
public void onPostExecute() {
    dialog.dismiss();
    new MaterialDialog.Builder(activity)
            .title("*****")
            .content("OK")
            .positiveText(R.string.ok).show();
}

}

答案 1 :(得分:0)

for (String p : permissions) {
    result = ContextCompat.checkSelfPermission(act, p);
    if (result != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(p);
    } else {
        if (lastLocation == null) {
             locationManager = (LocationManager) v.getContext()
                                .getSystemService(Context.LOCATION_SERVICE);

             gpsLocationListener = createListener(v);
             locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER, 0, 0,
                                gpsLocationListener);
             }
             //Async three
             //it will be executed PackageManager.PERMISSION_GRANTED is true put log where how many time it is executed
                    new NearLocations(lastLocation, v).execute();
    }
}

尝试使用

删除此代码
for (String p : permissions) {
            result = ContextCompat.checkSelfPermission(act, p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            } else {
                if (lastLocation == null) {
                    locationManager = (LocationManager) v.getContext()
                            .getSystemService(Context.LOCATION_SERVICE);

                    gpsLocationListener = createListener(v);
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER, 0, 0,
                            gpsLocationListener);
                }
            }
        }

        if (!listPermissionsNeeded.isEmpty()) {
            requestPermissions(
                    listPermissionsNeeded.toArray(new String[listPermissionsNeeded
                            .size()]), MULTIPLE_PERMISSIONS);
            return false;
        }else {
            new NearLocations(lastLocation, v).execute();
        }

答案 2 :(得分:0)

您正在调用AsyncTask.execute():

      new NearLocations(lastLocation, v).execute();

在checkPermission()方法的for循环中:对于已授予的每个权限:

        for (String p : permissions) {

        result = ContextCompat.checkSelfPermission(act, p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        } else {
            if (lastLocation == null) {
                locationManager = (LocationManager) v.getContext()
                        .getSystemService(Context.LOCATION_SERVICE);

                gpsLocationListener = createListener(v);
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 0, 0,
                        gpsLocationListener);
            }
            //Async three
            new NearLocations(lastLocation, v).execute();
        }
    }

然后再次在onRequestPermissionsResult()中调用它,这导致多次调用AsyncTask。