Java Code Examples for android.support.v4.app.ActivityCompat#checkSelfPermission()

The following examples show how to use android.support.v4.app.ActivityCompat#checkSelfPermission() . 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 check out the related API usage on the sidebar.
Example 1
Source File: MainActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mGoogleApiClient = new GoogleApiClient.Builder(this)
                       .addApi(Awareness.API)
                       .enableAutoManage(this, // MainActivity
                         this)         // OnConnectionFailedListener
                       .build();

  int permission = ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION);
  if (permission != PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this,
      new String[]{ACCESS_FINE_LOCATION},
      LOCATION_PERMISSION_REQUEST);
  }
}
 
Example 2
Source File: MultiTrackerActivity.java    From android-vision with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the UI and creates the detector pipeline.
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource();
    } else {
        requestCameraPermission();
    }
}
 
Example 3
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void getLastLocation() {
  FusedLocationProviderClient fusedLocationClient;
  fusedLocationClient =
    LocationServices.getFusedLocationProviderClient(this);
  if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)
      == PERMISSION_GRANTED ||
      ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION)
      == PERMISSION_GRANTED) {
    fusedLocationClient.getLastLocation()
      .addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
          updateTextView(location);
        }
      });
  }
}
 
Example 4
Source File: DBHelper.java    From fingen with Apache License 2.0 6 votes vote down vote up
public File backupDB(boolean vacuum) throws IOException {
    File backup = null;
    if (vacuum) {
        mDatabase.execSQL("VACUUM");
    }
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        String backupPath = FileUtils.getExtFingenBackupFolder();
        String alpha = "";
        if (BuildConfig.FLAVOR.equals("nd")) alpha = "_alpha";
        @SuppressLint("SimpleDateFormat") String backupFile = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()) + alpha + ".zip";

        if (!backupPath.isEmpty()) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
            String password = preferences.getString("backup_password", "");
            Boolean enableProtection = preferences.getBoolean("enable_backup_password", false);
            if (enableProtection && !password.isEmpty()) {
                backup = FileUtils.zipAndEncrypt(getDbPath(), backupPath + backupFile, password);
            } else {
                backup = FileUtils.zip(new String[]{getDbPath()}, backupPath + backupFile);
            }
            Log.d(TAG, String.format("File %s saved", backupFile));
        }
    }
    return backup;
}
 
Example 5
Source File: RxLocationTool.java    From RxTools-master with Apache License 2.0 6 votes vote down vote up
/**
 * 注册
 * <p>使用完记得调用{@link #unRegisterLocation()}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p>
 * <p>如果{@code minDistance}为0,则通过{@code minTime}来定时更新;</p>
 * <p>{@code minDistance}不为0,则以{@code minDistance}为准;</p>
 * <p>两者都为0,则随时刷新。</p>
 *
 * @param minTime     位置信息更新周期(单位:毫秒)
 * @param minDistance 位置变化最小距离:当位置距离变化超过此值时,将更新位置信息(单位:米)
 * @param listener    位置刷新的回调接口
 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失败
 */
public static boolean registerLocation(Context context, long minTime, long minDistance, OnLocationChangeListener listener) {
    if (listener == null) return false;
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        return false;
    }
    mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    mListener = listener;
    if (!isLocationEnabled(context)) {
        RxToast.showToast(context, "无法定位,请打开定位服务", 500);
        return false;
    }
    String provider = mLocationManager.getBestProvider(getCriteria(), true);

    Location location = mLocationManager.getLastKnownLocation(provider);
    if (location != null) listener.getLastKnownLocation(location);
    if (myLocationListener == null) myLocationListener = new MyLocationListener();
    mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener);
    return true;
}
 
Example 6
Source File: QuizActivity.java    From CoolSignIn with Apache License 2.0 6 votes vote down vote up
private void getLocation() {
    locationManager = (LocationManager) MyApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyApplication.getContext(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(QuizActivity.this, "我没有位置权限 ( > c < ) ", Toast.LENGTH_SHORT).show();
        String locationPermissions[] = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= 23) {
            requestPermissions(locationPermissions, REQUEST_CODE_FOR_POSITON);
        }
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
}
 
Example 7
Source File: PermissionUtil.java    From Ticket-Analysis with MIT License 5 votes vote down vote up
public void checkAndRequestPermission(Activity activity, String... needPermissions) {
    boolean isAllGranted = true;
    for (String needPermission : needPermissions) {
        if (ActivityCompat.checkSelfPermission(activity, needPermission)
                != PackageManager.PERMISSION_GRANTED) {
            isAllGranted = false;
        }
    }
    if (isAllGranted) {
        mListener.allGranted();
    } else {
        ActivityCompat.requestPermissions(activity, needPermissions, REQUEST_CODE_REQUEST_PERMISSION);
    }

}
 
Example 8
Source File: MainActivity.java    From MoeGallery with GNU General Public License v3.0 5 votes vote down vote up
private void askForPermission(String permission, int requestCode) {
    if (ActivityCompat.checkSelfPermission(this, permission)
            == PackageManager.PERMISSION_GRANTED) {
        return;
    }

    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission },
                requestCode);
    } else {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission },
                requestCode);
    }
}
 
Example 9
Source File: Principal.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (bPermissionGranted) {
            buildGoogleApiClient();
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mGoogleMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mGoogleMap.setMyLocationEnabled(true);
    }

}
 
Example 10
Source File: DefaultLocation.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Override
public void clearWatch(String watchId) {
  WXLogUtils.d("into--[clearWatch] mWatchId:" + watchId);
  if (mWXSDKInstance == null || mWXSDKInstance.isDestroy() || mLocationManager == null) {
    return;
  }
  if (ActivityCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    WXLocationListener listener = mRegisterSucCallbacks.get(watchId);
    if (listener != null) {
      listener.destroy();
      mLocationManager.removeUpdates(listener);
    }
    mRegisterSucCallbacks.remove(watchId);
  }
}
 
Example 11
Source File: QRScanningActivity.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle state)
{
    super.onCreate(state);
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED)
    {
        setContentView(R.layout.activity_full_screen_scanner_fragment);
        initBackClick();
    }
    else
    {
        requestCameraPermission();
    }
}
 
Example 12
Source File: CheckInActivity.java    From StudentAttendanceCheck with MIT License 5 votes vote down vote up
@Override
public void onConnected(@Nullable Bundle bundle) {

    Log.w("LOCATION", "CONNECTED");

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

        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        ActivityCompat.requestPermissions(CheckInActivity.this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                12345);

        Log.w("CheckInActivity onConnected: ", "permission request");
        return;
    }

    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);


    if (mLastLocation != null) {

        douMyLat = mLastLocation.getLatitude();
        douMyLng = mLastLocation.getLongitude();

    }

    Log.d("MyLatLng", String.valueOf(douMyLat) + " " + douMyLng);
    updateLocation();
    addEvents();
}
 
Example 13
Source File: DeviceLocation.java    From ARCore-Location with MIT License 5 votes vote down vote up
public void permissionsCheck() {
    if (ActivityCompat.checkSelfPermission(
            activity,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
    ) {

        // Check Permissions Now
        ActivityCompat.requestPermissions(
                activity,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                0);
    }
}
 
Example 14
Source File: RxDeviceTool.java    From RxTools-master with Apache License 2.0 5 votes vote down vote up
/**
 * 拨打电话
 * 需添加权限 {@code <uses-permission android:name="android.permission.CALL_PHONE"/>}
 *
 * @param context     上下文
 * @param phoneNumber 电话号码
 */
public static void callPhone(final Context context, String phoneNumber) {
    if (!RxDataTool.isNullString(phoneNumber)) {
        final String phoneNumber1 = phoneNumber.trim();// 删除字符串首部和尾部的空格
        // 调用系统的拨号服务实现电话拨打功能
        // 封装一个拨打电话的intent,并且将电话号码包装成一个Uri对象传入

        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber1));
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        context.startActivity(intent);// 内部类
    }
}
 
Example 15
Source File: LogUtils.java    From BmapLite with Apache License 2.0 5 votes vote down vote up
/**
 * 写入log文件
 *
 * @param msg 信息
 */
public static void saveLog(final Context context, String msg) {
    final String string = "[" + TimeUtils.getSystemTime("HH:mm:ss") + "]" + msg + "\n";

    debug(msg);

    //判断是否有sd卡读写权限
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    //开启新线程写入日志
    new Thread() {
        @Override
        public void run() {
            File dir = context.getExternalFilesDir("log");
            if (null == dir) {
                return;
            }
            if (!dir.exists()) {
                dir.mkdir();
            }
            File logFile = new File(dir, "log" + TimeUtils.getSystemTime("yyyyMMdd") + ".txt");
            FileUtils.writeFileToSDCard(logFile, string);
        }
    }.start();


}
 
Example 16
Source File: MainActivity.java    From AutoInputAuthCode with Apache License 2.0 5 votes vote down vote up
/**
 * 简单处理了短信权限
 */
private void handlePermission() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_SMS}, REQUEST_PERMISSION_CODE);
    }
}
 
Example 17
Source File: BarcodeReaderFragment.java    From Barcode-Reader with Apache License 2.0 5 votes vote down vote up
/**
 * 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 18
Source File: ImageBaseActivity.java    From ImagePicker with Apache License 2.0 4 votes vote down vote up
public boolean checkPermission(@NonNull String permission) {
    return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
 
Example 19
Source File: DefaultPermissionsModule.java    From espresso-samples with Apache License 2.0 4 votes vote down vote up
public boolean isLocationGranted(Context context) {
    return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
        == PackageManager.PERMISSION_GRANTED;
}
 
Example 20
Source File: MapsActivity.java    From journaldev with MIT License 4 votes vote down vote up
/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    /*LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.setTrafficEnabled(true);
    mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_night));

    /**
     * UNCOMMENT TO TEST setLatLngBoundsForCameraTarget
     *
     *
     * final LatLngBounds ADELAIDE = new LatLngBounds(
            new LatLng(-35.0, 138.58), new LatLng(-34.9, 138.61));
    final CameraPosition ADELAIDE_CAMERA = new CameraPosition.Builder()
            .target(new LatLng(-34.92873, 138.59995)).zoom(20.0f).bearing(0).tilt(0).build();

    mMap.setLatLngBoundsForCameraTarget(ADELAIDE);

    mMap.addMarker(new MarkerOptions()
            .position(new LatLng(-34.92873, 138.59995))
            .title("My Marker"));


    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(ADELAIDE_CAMERA));

     **
     */

}