Java Code Examples for android.support.v4.app.ActivityCompat

The following examples show how to use android.support.v4.app.ActivityCompat. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: APNG4Android   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActivityCompat.requestPermissions(
            MainActivity.this,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            100);

    findViewById(R.id.tv_1).setOnClickListener(this);
    findViewById(R.id.tv_2).setOnClickListener(this);
    findViewById(R.id.tv_3).setOnClickListener(this);
    findViewById(R.id.tv_4).setOnClickListener(this);
    findViewById(R.id.tv_5).setOnClickListener(this);
    findViewById(R.id.tv_6).setOnClickListener(this);
    findViewById(R.id.tv_7).setOnClickListener(this);
    findViewById(R.id.tv_8).setOnClickListener(this);
}
 
Example 2
Source Project: TouchNews   Source File: JokeImageListRecyclerAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof MViewHolder) {
            JokeImageRoot.Contentlist contentEntity = mData.get(position);
            ((MViewHolder) holder).mTitle.setText(contentEntity.getTitle());
            final ImageView imageView = ((MViewHolder) holder).mImage;
            ImageUtil.displayImage(mContext, contentEntity.getImg(), imageView);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ImageBrowseActivity.class);
                    intent.putExtra("url", mData.get(position).getImg());
//                     View transitionView = view.findViewById(R.id.ivNews);
                    ActivityOptionsCompat options =
                        ActivityOptionsCompat.makeSceneTransitionAnimation((HomeActivity) mContext,
                            imageView, mContext.getString(R.string.transition__img));

                    ActivityCompat.startActivity((HomeActivity) mContext, intent, options.toBundle());

                }
            });
        }
    }
 
Example 3
Source Project: PainlessMusicPlayer   Source File: BaseActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean navigateUpTo(final Intent upIntent) {
    ComponentName destInfo = upIntent.getComponent();
    if (destInfo == null) {
        destInfo = upIntent.resolveActivity(getPackageManager());
        if (destInfo == null) {
            return false;
        }
    }

    if (shouldUpRecreateTask(upIntent)) {
        startActivity(upIntent);
        finish();
    } else {
        ActivityCompat.finishAfterTransition(this);
    }
    return true;
}
 
Example 4
Source Project: blefun-androidthings   Source File: ScanActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void prepareForScan() {
    if (isBleSupported()) {
        // Ensures Bluetooth is enabled on the device
        BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter btAdapter = btManager.getAdapter();
        if (btAdapter.isEnabled()) {
            // Prompt for runtime permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLeScan();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_LOCATION);
            }
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    } else {
        Toast.makeText(this, "BLE is not supported", Toast.LENGTH_LONG).show();
        finish();
    }
}
 
Example 5
Source Project: Fatigue-Detection   Source File: HomeActivity.java    License: MIT License 6 votes vote down vote up
private boolean checkPermission(String permission,int requestCode){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                showHint("Camera and SDCard access is required by Omoshiroi, please grant the permission in settings.");
                finish();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{
                                permission,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.RECORD_AUDIO
                        },
                        requestCode);
            }
            return false;
        }else return true;
    }
    return true;
}
 
Example 6
@Override
public void onConnected() {
    if (ActivityCompat.checkSelfPermission(tempContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        if (prefs.getBoolean(Common.PREF_ENABLE_LOCATION_TRACKING, false) && !TextUtils.isEmpty(prefs.getString(Common.PREF_LOCATION_DEVICE_NAME, null))) {
            LocationRequest locationRequest = LocationRequest.create()
            .setInterval(prefs.getInt(Common.PREF_LOCATION_UPDATE_INTERVAL, 10) * 60 * 1000)
            .setFastestInterval(5 * 60 * 1000)
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, getPendingIntent(tempContext));
            Log.d(TAG, "Started requesting location updates");
        } else {
            LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, getPendingIntent(tempContext));
            Log.d(TAG, "Stopped requesting location updates");
        }
    }
    apiClient.disconnect();
    tempContext = null;
}
 
Example 7
@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "onConnected");
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    if (mCurrentLocation == null) {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}
 
Example 8
/**
 * Start the hidden camera. Make sure that you check for the runtime permissions before you start
 * the camera.
 *
 * @param cameraConfig camera configuration {@link CameraConfig}
 */
@RequiresPermission(Manifest.permission.CAMERA)
protected void startCamera(CameraConfig cameraConfig) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) { //check if the camera permission is available

        onCameraError(CameraError.ERROR_CAMERA_PERMISSION_NOT_AVAILABLE);
    } else if (cameraConfig.getFacing() == CameraFacing.FRONT_FACING_CAMERA
            && !HiddenCameraUtils.isFrontCameraAvailable(this)) {   //Check if for the front camera

        onCameraError(CameraError.ERROR_DOES_NOT_HAVE_FRONT_CAMERA);
    } else {
        mCachedCameraConfig = cameraConfig;
        mCameraPreview.startCameraInternal(cameraConfig);
    }
}
 
Example 9
Source Project: fingen   Source File: ActivityEditLocation2.java    License: Apache License 2.0 6 votes vote down vote up
@NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
void startDetectCoords() {
    if (location.getID() < 0) {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager != null && locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            }

        if (locationManager != null && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
    }
}
 
Example 10
Source Project: protrip   Source File: SplashActivity.java    License: MIT License 6 votes vote down vote up
private void getLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            mCurrentLat = String.valueOf(mLastLocation.getLatitude());
            mCurrentLng = String.valueOf(mLastLocation.getLongitude());
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(mCurrentLat), Double.parseDouble(mCurrentLng), 1);
                //mCurrentLocName = addresses.get(0).getLocality();
                mCurrentLocName = addresses.get(0).getAddressLine(1);

            } catch (Exception e) {
                Log.d(TAG, "Exception");
            }
        }
        skip();
    }

}
 
Example 11
Source Project: android-samples   Source File: CombineFenceApiActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(final View view) {
    switch (view.getId()) {
        case R.id.register_fence:
            //Check for the location permission. We need them to generate location fence.
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        LOCATION_PERMISSION_REQUEST_CODE);
            } else {
                registerFence();
            }
            break;
        case R.id.unregister_fence:
            unregisterFence();
            break;
    }
}
 
Example 12
Source Project: SoloPi   Source File: QRScanActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void requestCameraPermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
        Snackbar.make(mainLayout, R.string.qr__camera_permission,
                Snackbar.LENGTH_INDEFINITE).setAction(R.string.constant__yes, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(QRScanActivity.this, new String[]{
                        Manifest.permission.CAMERA
                }, MY_PERMISSION_REQUEST_CAMERA);
            }
        }).show();
    } else {
        Snackbar.make(mainLayout, R.string.qr__requst_permission,
                Snackbar.LENGTH_SHORT).show();
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.CAMERA
        }, MY_PERMISSION_REQUEST_CAMERA);
    }
}
 
Example 13
Source Project: FaceDetectCamera   Source File: PhotoDetectActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            super.onBackPressed();
            return true;

        case R.id.gallery:

            int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (rc == PackageManager.PERMISSION_GRANTED) {
                getImage();
            } else {
                requestWriteExternalPermission();
            }

            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}
 
Example 14
Source Project: always-on-amoled   Source File: Flashlight.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Flashlight(Context context) {
    this.context = context;
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
        try {
            cam = Camera.open();
            Camera.Parameters p = cam.getParameters();
            p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            cam.setParameters(p);
            SurfaceTexture mPreviewTexture = new SurfaceTexture(0);
            try {
                cam.setPreviewTexture(mPreviewTexture);
            } catch (IOException ignored) {
            }
        } catch (RuntimeException e) {
            Utils.showErrorNotification(context, context.getString(R.string.error), context.getString(R.string.error_5_camera_cant_connect_desc), 233, null);
        }
    }
}
 
Example 15
Source Project: openlauncher   Source File: PermissionChecker.java    License: Apache License 2.0 6 votes vote down vote up
public boolean doIfExtStoragePermissionGranted(String... optionalToastMessageForKnowingWhyNeeded) {
    if (ContextCompat.checkSelfPermission(_activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (optionalToastMessageForKnowingWhyNeeded != null && optionalToastMessageForKnowingWhyNeeded.length > 0 && optionalToastMessageForKnowingWhyNeeded[0] != null) {
            new AlertDialog.Builder(_activity)
                    .setMessage(optionalToastMessageForKnowingWhyNeeded[0])
                    .setCancelable(false)
                    .setNegativeButton(android.R.string.no, null)
                    .setPositiveButton(android.R.string.yes, (dialog, which) -> {
                        if (android.os.Build.VERSION.SDK_INT >= 23) {
                            ActivityCompat.requestPermissions(_activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_PERMISSION_EXTERNAL_STORAGE);
                        }
                    })
                    .show();
            return false;
        }
        ActivityCompat.requestPermissions(_activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_PERMISSION_EXTERNAL_STORAGE);
        return false;
    }
    return true;
}
 
Example 16
Source Project: ToGoZip   Source File: PermissionHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return true if has-(runtime-)permissions.
 * */
public static boolean hasPermission(Activity context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        boolean needsRead = ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;

        boolean needsWrite = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;

        if (needsRead || needsWrite) {
            // no permission yet
            return false;
        }
    } // if android-m

    // already has permission.
    return true;
}
 
Example 17
Source Project: kute   Source File: ProfilePictureActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode==0 && ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED ) {
        if(permissions.length>1 && ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "We Got External Storage and Camera", Toast.LENGTH_SHORT).show();
            getNewProfileImage();
        }
        else
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED) {
            //User just granted one of the denied permissions
            getNewProfileImage();
        }
        else {
            Snackbar.make(cl,"You need to give permissions to setup custom profile picture",Snackbar.LENGTH_LONG).show();
        }
    }
    else if(requestCode==0) {
        Snackbar.make(cl,"You need to give permissions to setup custom profile picture",Snackbar.LENGTH_LONG).show();
    }

}
 
Example 18
private void requestPermission(AppPermissions permission) {
    if (ContextCompat.checkSelfPermission(this, permission.getPermissionName())
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[] { permission.getPermissionName() },
                permission.getPermissionCode());
    }
}
 
Example 19
Source Project: AndroidDonate   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
private void checkPermissionAndDonateWeixin() {
    //检测微信是否安装
    if (!WeiXinDonate.hasInstalledWeiXinClient(this)) {
        Toast.makeText(this, "未安装微信客户端", Toast.LENGTH_SHORT).show();
        return;
    }
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        //已经有权限
        showDonateTipDialog();
    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
    }
}
 
Example 20
Source Project: ml   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void requestRequiredPermissions() {
    ActivityCompat.requestPermissions(this,
            new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            },
            REQUEST_REQUIRED_PERMISSION);
}
 
Example 21
private void requestPermissionForMicrophone() {
    if (getCurrentActivity() != null) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getCurrentActivity(), Manifest.permission.RECORD_AUDIO)) {
//            Snackbar.make(coordinatorLayout,
//                    "Microphone permissions needed. Please allow in your application settings.",
//                    SNACKBAR_DURATION).show();
        } else {
            ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, MIC_PERMISSION_REQUEST_CODE);
        }
    }
}
 
Example 22
Source Project: Noyze   Source File: ConfigurationActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void launchAbout(View view) {
    Intent about = new Intent(getApplicationContext(), NoyzeLibActivity.class);
    about.putExtra(Libs.BUNDLE_FIELDS, Libs.toStringArray(R.string.class.getFields()));
    about.putExtra(Libs.BUNDLE_VERSION, true);
    about.putExtra(Libs.BUNDLE_LICENSE, true);
    about.putExtra(Libs.BUNDLE_TITLE, getString(R.string.about_settings));
    about.putExtra(Libs.BUNDLE_THEME, R.style.AboutTheme);
    if (null == view) {
        startActivity(about);
    } else {
        ActivityOptionsCompat anim = ActivityOptionsCompat.makeSceneTransitionAnimation(this, view, "Google Plus");
        ActivityCompat.startActivity(this, about, anim.toBundle());
    }
}
 
Example 23
/**
 * 获取权限集中需要申请权限的列表
 * 
 * @param permissions
 * @return
 * @since 2.5.0
 *
 */
private List<String> findDeniedPermissions(String[] permissions) {
	List<String> needRequestPermissonList = new ArrayList<String>();
	for (String perm : permissions) {
		if (ContextCompat.checkSelfPermission(this,
				perm) != PackageManager.PERMISSION_GRANTED
				|| ActivityCompat.shouldShowRequestPermissionRationale(
						this, perm)) {
			needRequestPermissonList.add(perm);
		} 
	}
	return needRequestPermissonList;
}
 
Example 24
Source Project: MeiZiNews   Source File: AndroidDevWeekAdapter.java    License: MIT License 5 votes vote down vote up
@Override
protected void convert(final BaseAdapterHelper helper, final AndroidDevWeek item, int position) {

    helper.getTextView(R.id.story_item_title).setText(item.getTitle());
    helper.getTextView(R.id.story_excerpt).setText(item.getExcerpt());
    helper.getTextView(R.id.story_author).setText(item.getAuthor());
    helper.getTextView(R.id.story_date).setText(item.getDate());

    helper.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            Intent intent = new Intent(context, DevWeekDetailActivity.class);
            intent.putExtra("path",item.getUrl());
            intent.putExtra("title",item.getTitle());
            intent.putExtra("excerpt",item.getExcerpt());

            //让新的Activity从一个小的范围扩大到全屏
            ActivityOptionsCompat options = ActivityOptionsCompat.makeScaleUpAnimation(
                    helper.getTextView(R.id.story_item_title), helper.getTextView(R.id.story_item_title).getWidth() / 2,
                    helper.getTextView(R.id.story_item_title).getHeight() / 2, 0, 0
            );
            ActivityCompat.startActivity((MainMvpActivity) context, intent, options.toBundle());
        }
    });
}
 
Example 25
Source Project: apkextractor   Source File: ImportFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onItemClicked(ImportItem importItem, RecyclerViewAdapter.ViewHolder viewHolder, int position) {
    if(getActivity()==null)return;
    Intent intent =new Intent(getActivity(), PackageDetailActivity.class);
    //intent.putExtra(PackageDetailActivity.EXTRA_IMPORT_ITEM_POSITION,position);
    intent.putExtra(PackageDetailActivity.EXTRA_IMPORT_ITEM_PATH,importItem.getFileItem().getPath());
    ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),new Pair<View, String>(viewHolder.icon,"icon"));
    try{
        ActivityCompat.startActivity(getActivity(), intent, compat.toBundle());
    }catch (Exception e){e.printStackTrace();}
}
 
Example 26
/**
 * Restarts the camera.
 */
@Override
public void onResume() {
    super.onResume();
    startCameraSource();
    if (sentToSettings) {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            //Got Permission
            proceedAfterPermission();
        } else {
            mListener.onCameraPermissionDenied();
        }
    }
}
 
Example 27
Source Project: ContinuesVoiceRecognition   Source File: PermissionHandler.java    License: MIT License 5 votes vote down vote up
public static void askForPermission(int which,final Activity activity)
{
    if(Build.VERSION.SDK_INT<23)
    {
        return;
    }
    else //We are running on Android M
    {
        switch(which)
        {
            case RECORD_AUDIO:
                if(ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS)== PackageManager.PERMISSION_GRANTED  )
                    return;
                else
                {
                    if(ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.RECORD_AUDIO))
                    {
                        Toast.makeText(activity,activity.getString(R.string.record_audio_is_required),Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO);
                    }
                }
                break;
        }
    }
}
 
Example 28
Source Project: MultipleImageSelect   Source File: HelperActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void requestPermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showRequestPermissionRationale();

    } else {
        showAppPermissionSettings();
    }
}
 
Example 29
Source Project: CineLog   Source File: SettingsFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void configureAutomaticExportPreference() {
    CheckBoxPreference listcheckBoxPreference = (CheckBoxPreference) findPreference("automatic_save");
    listcheckBoxPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if((Boolean) newValue && !writeStoragePermission) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
            return true;
        }
    });
}
 
Example 30
Source Project: OpenWeatherPlus-Android   Source File: PermissionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 一次申请多个权限
     */
    public static void requestMultiPermissions(final Activity activity, PermissionGrant grant) {

        final List<String> permissionsList                = getNoGrantedPermission(activity, false);
        final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true);

        // checkSelfPermission
        if (permissionsList == null || shouldRationalePermissionsList == null) {
            return;
        }
        Log.d(TAG, "requestMultiPermissions permissionsList:" + permissionsList.size() + ",shouldRationalePermissionsList:" + shouldRationalePermissionsList.size());

        if (permissionsList.size() > 0) {
            ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]),
                    CODE_MULTI_PERMISSION);
            Log.d(TAG, "showMessageOKCancel requestPermissions");

        } else if (shouldRationalePermissionsList.size() > 0) {
            ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
                    CODE_MULTI_PERMISSION);
//            showMessageOKCancel(activity, "should open those permission",
//                    new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
//                                    CODE_MULTI_PERMISSION);
//                            Log.d(TAG, "showMessageOKCancel requestPermissions");
//                        }
//                    });
        } else {
            grant.onPermissionGranted(CODE_MULTI_PERMISSION);
        }

    }