下面列出了android.support.annotation.ColorRes#android.support.v4.app.ActivityCompat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
@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());
}
});
}
}
@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;
}
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();
}
}
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;
}
@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;
}
@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();
}
}
/**
* 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);
}
}
@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);
}
}
}
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();
}
}
@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;
}
}
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);
}
}
@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);
}
}
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);
}
}
}
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;
}
/**
* @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;
}
@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();
}
}
private void requestPermission(AppPermissions permission) {
if (ContextCompat.checkSelfPermission(this, permission.getPermissionName())
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] { permission.getPermissionName() },
permission.getPermissionCode());
}
}
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);
}
}
private void requestRequiredPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
},
REQUEST_REQUIRED_PERMISSION);
}
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);
}
}
}
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());
}
}
/**
* 获取权限集中需要申请权限的列表
*
* @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;
}
@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());
}
});
}
@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();}
}
/**
* 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();
}
}
}
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;
}
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showRequestPermissionRationale();
} else {
showAppPermissionSettings();
}
}
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;
}
});
}
/**
* 一次申请多个权限
*/
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);
}
}