下面列出了怎么用androidx.annotation.RequiresPermission的API类实例代码及写法,或者点击链接到github查看源代码。
@RequiresPermission(anyOf = {
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.READ_SMS,
android.Manifest.permission.READ_PHONE_NUMBERS
})
@SuppressLint("MissingPermission")
public static Optional<Phonenumber.PhoneNumber> getDeviceNumber(Context context) {
try {
final String localNumber = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
final Optional<String> countryIso = getSimCountryIso(context);
if (TextUtils.isEmpty(localNumber)) return Optional.absent();
if (!countryIso.isPresent()) return Optional.absent();
return Optional.fromNullable(PhoneNumberUtil.getInstance().parse(localNumber, countryIso.get()));
} catch (NumberParseException e) {
Log.w(TAG, e);
return Optional.absent();
}
}
@RequiresPermission(permission.CAMERA)
private Set<Integer> getAvailableCameraLensFacing() {
// Start with all camera directions
Set<Integer> available = new LinkedHashSet<>(Arrays.asList(LensFacingConverter.values()));
// If we're bound to a lifecycle, remove unavailable cameras
if (mCurrentLifecycle != null) {
if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) {
available.remove(CameraSelector.LENS_FACING_BACK);
}
if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_FRONT)) {
available.remove(CameraSelector.LENS_FACING_FRONT);
}
}
return available;
}
/**
* 进行播放声音, 并且震动
* @return {@code true} success, {@code false} fail
*/
@RequiresPermission(android.Manifest.permission.VIBRATE)
public synchronized boolean playBeepSoundAndVibrate() {
// 判断是否允许播放
if (shouldBeep() && mMediaPlayer != null) {
// 判断是否允许震动
if (mIsVibrate) {
VibrationUtils.vibrate(mVibrateDuration);
}
try {
// 播放
mMediaPlayer.start();
return true;
} catch (Exception e) {
}
}
return false;
}
/**
* Opens the camera and starts sending preview frames to the underlying detector. The supplied
* surface holder is used for the preview so frames can be displayed to the user.
*
* @param surfaceHolder the surface holder to use for the preview frames
* @throws IOException if the supplied surface holder could not be used as the preview display
*/
@RequiresPermission(Manifest.permission.CAMERA)
public CameraSource start(SurfaceHolder surfaceHolder) throws IOException {
synchronized (mCameraLock) {
if (mCamera != null) {
return this;
}
mCamera = createCamera();
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mProcessingThread = new Thread(mFrameProcessor);
mFrameProcessor.setActive(true);
mProcessingThread.start();
}
return this;
}
/**
* 设置 Notification Bar 是否显示
* @param isVisible 是否显示 Notification Bar
* @return {@code true} success, {@code false} fail
*/
@RequiresPermission(android.Manifest.permission.EXPAND_STATUS_BAR)
public static boolean setNotificationBarVisibility(final boolean isVisible) {
String methodName;
if (isVisible) {
methodName = (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) ? "expand" : "expandNotificationsPanel";
} else {
methodName = (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) ? "collapse" : "collapsePanels";
}
try {
@SuppressLint("WrongConstant")
Object service = DevUtils.getContext().getSystemService("statusbar");
@SuppressLint("PrivateApi")
Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
Method expand = statusBarManager.getMethod(methodName);
expand.invoke(service);
return true;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "setNotificationBarVisibility");
}
return false;
}
/**
* Fetches a list of {@link PlaceLikelihood} instances that represent the Places the user is
* most
* likely to be at currently.
*/
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
private void findCurrentPlaceWithPermissions() {
setLoading(true);
FindCurrentPlaceRequest currentPlaceRequest =
FindCurrentPlaceRequest.newInstance(getPlaceFields());
Task<FindCurrentPlaceResponse> currentPlaceTask =
placesClient.findCurrentPlace(currentPlaceRequest);
currentPlaceTask.addOnSuccessListener(
(response) ->
responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked())));
currentPlaceTask.addOnFailureListener(
(exception) -> {
exception.printStackTrace();
responseView.setText(exception.getMessage());
});
currentPlaceTask.addOnCompleteListener(task -> setLoading(false));
}
/**
* Fetches a list of {@link PlaceLikelihood} instances that represent the Places the user is
* most
* likely to be at currently.
*/
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
private void findCurrentPlaceWithPermissions() {
setLoading(true);
FindCurrentPlaceRequest currentPlaceRequest =
FindCurrentPlaceRequest.newInstance(getPlaceFields());
Task<FindCurrentPlaceResponse> currentPlaceTask =
placesClient.findCurrentPlace(currentPlaceRequest);
currentPlaceTask.addOnSuccessListener(
(response) ->
responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked())));
currentPlaceTask.addOnFailureListener(
(exception) -> {
exception.printStackTrace();
responseView.setText(exception.getMessage());
});
currentPlaceTask.addOnCompleteListener(task -> setLoading(false));
}
/**
* 获取 MAC 地址
* @return MAC 地址
*/
@RequiresPermission(android.Manifest.permission.INTERNET)
private static String getMacAddressByNetworkInterface() {
try {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
if (ni == null || !ni.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = ni.getHardwareAddress();
if (macBytes != null && macBytes.length > 0) {
StringBuilder builder = new StringBuilder();
for (byte b : macBytes) {
builder.append(String.format("%02x:", b));
}
return builder.substring(0, builder.length() - 1);
}
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getMacAddressByNetworkInterface");
}
return DEFAULT_MAC_ADDRESS;
}
@RequiresPermission(Manifest.permission.CAMERA)
private void startIfReady() throws IOException, SecurityException {
if (mStartRequested && mSurfaceAvailable) {
mCameraSource.start(mSurfaceView.getHolder());
if (mOverlay != null) {
Size size = mCameraSource.getPreviewSize();
int min = Math.min(size.getWidth(), size.getHeight());
int max = Math.max(size.getWidth(), size.getHeight());
if (isPortraitMode()) {
// Swap width and height sizes when in portrait, since it will be rotated by
// 90 degrees
mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing());
} else {
mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing());
}
mOverlay.clear();
}
mStartRequested = false;
}
}
/**
* Set mobile data enabled.
* <p>Must hold {@code android:sharedUserId="android.uid.system"},
* {@code <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />}</p>
*
* @param enabled True to enabled, false otherwise.
*/
@RequiresPermission(MODIFY_PHONE_STATE)
public static void setMobileDataEnabled(final boolean enabled) {
try {
TelephonyManager tm =
(TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
if (tm == null) {
return;
}
Method setMobileDataEnabledMethod =
tm.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataEnabledMethod) {
setMobileDataEnabledMethod.invoke(tm, enabled);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method is used to start BLE scan.
*/
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH})
public void stopScan() {
Log.d(TAG, "Stop BLE device scan");
handler.removeCallbacks(stopScanTask);
if (bluetoothLeScanner != null && bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
try {
bluetoothLeScanner.stopScan(scanCallback);
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
isScanning = false;
bleScanListener.scanCompleted();
}
/**
* 判断 APP 是否在前台
* @param packageName 应用包名
* @return {@code true} yes, {@code false} no
*/
@RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
public static boolean isAppForeground(final String packageName) {
if (StringUtils.isSpace(packageName)) return false;
try {
List<ActivityManager.RunningAppProcessInfo> lists = getActivityManager().getRunningAppProcesses();
if (lists != null && lists.size() > 0) {
for (ActivityManager.RunningAppProcessInfo appProcess : lists) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return appProcess.processName.equals(packageName);
}
}
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "isAppForeground");
}
return false;
}
/**
* 获取 IMEI 码
* <pre>
* IMEI 是 International Mobile Equipment Identity ( 国际移动设备标识 ) 的简称
* IMEI 由 15 位数字组成的「电子串号」它与每台手机一一对应, 而且该码是全世界唯一的
* 其组成为:
* 1. 前 6 位数 (TAC) 是「型号核准号码」一般代表机型
* 2. 接着的 2 位数 (FAC) 是「最后装配号」一般代表产地
* 3. 之后的 6 位数 (SNR) 是「串号」一般代表生产顺序号
* 4. 最后 1 位数 (SP) 通常是「0」为检验码, 目前暂备用
* </pre>
* @param slotIndex 卡槽索引
* @return IMEI 码
*/
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public static String getIMEI(final int slotIndex) {
try {
TelephonyManager telephonyManager = AppUtils.getTelephonyManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (slotIndex == -1) return telephonyManager.getImei();
return telephonyManager.getImei(slotIndex);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// 反射调用方法
Class clazz = telephonyManager.getClass();
Method method = clazz.getDeclaredMethod("getImei");
method.setAccessible(true);
return (String) method.invoke(telephonyManager);
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getIMEI");
}
return null;
}
@RequiresPermission(Manifest.permission.CAMERA)
private void startIfReady() throws IOException, SecurityException {
if (mStartRequested && mSurfaceAvailable) {
mCameraSource.start(mSurfaceView.getHolder());
if (mOverlay != null) {
Size size = mCameraSource.getPreviewSize();
int min = Math.min(size.getWidth(), size.getHeight());
int max = Math.max(size.getWidth(), size.getHeight());
if (isPortraitMode()) {
// Swap width and height sizes when in portrait, since it will be rotated by
// 90 degrees
mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing());
} else {
mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing());
}
mOverlay.clear();
}
mStartRequested = false;
}
}
/**
* Opens the camera and starts sending preview frames to the underlying detector. The preview
* frames are not displayed.
*
* @throws IOException if the camera's preview texture or display could not be initialized
*/
@SuppressLint("MissingPermission")
@RequiresPermission(Manifest.permission.CAMERA)
public synchronized CameraSource start() throws IOException {
if (camera != null) {
return this;
}
camera = createCamera();
dummySurfaceTexture = new SurfaceTexture(DUMMY_TEXTURE_NAME);
camera.setPreviewTexture(dummySurfaceTexture);
usingSurfaceTexture = true;
camera.startPreview();
processingThread = new Thread(processingRunnable);
processingRunnable.setActive(true);
processingThread.start();
return this;
}
/**
* 发送短信
* @param phoneNumber 接收号码
* @param content 短信内容
* @return {@code true} success, {@code false} fail
*/
@RequiresPermission(android.Manifest.permission.SEND_SMS)
public static boolean sendSmsSilent(final String phoneNumber, final String content) {
if (TextUtils.isEmpty(content)) return false;
try {
PendingIntent sentIntent = PendingIntent.getBroadcast(DevUtils.getContext(), 0, new Intent("send"), 0);
SmsManager smsManager = SmsManager.getDefault();
if (content.length() >= 70) {
List<String> ms = smsManager.divideMessage(content);
for (String str : ms) {
smsManager.sendTextMessage(phoneNumber, null, str, sentIntent, null);
}
} else {
smsManager.sendTextMessage(phoneNumber, null, content, sentIntent, null);
}
return true;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "sendSmsSilent");
}
return false;
}
/**
* This method is used to connect ESPDevice.
*/
@RequiresPermission(allOf = {Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_FINE_LOCATION})
public void connectToDevice() {
switch (transportType) {
case TRANSPORT_BLE:
((BLETransport) transport).connect(bluetoothDevice, UUID.fromString(primaryServiceUuid));
break;
case TRANSPORT_SOFTAP:
deviceConnectionReqCount = 0;
connectWiFiDevice(wifiDevice.getWifiName(), wifiDevice.getPassword());
break;
}
}
/**
* Opens the camera and starts sending preview frames to the underlying detector. The supplied
* surface holder is used for the preview so frames can be displayed to the user.
*
* @param surfaceHolder the surface holder to use for the preview frames
* @throws IOException if the supplied surface holder could not be used as the preview display
*/
@RequiresPermission(Manifest.permission.CAMERA)
public CameraSource start(SurfaceHolder surfaceHolder) throws IOException {
synchronized (mCameraLock) {
if (mCamera != null) {
return this;
}
mCamera = createCamera();
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mProcessingThread = new Thread(mFrameProcessor);
mFrameProcessor.setActive(true);
mProcessingThread.start();
}
return this;
}
/**
* 使用 ping ip 方式判断网络是否可用
* @param ip IP 地址
* @return {@code true} yes, {@code false} no
*/
@RequiresPermission(android.Manifest.permission.INTERNET)
public static boolean isAvailableByPing(String ip) {
if (ip == null || ip.length() <= 0) {
ip = "223.5.5.5"; // 默认阿里巴巴 DNS
}
// cmd ping ip
ShellUtils.CommandResult result = ShellUtils.execCmd(String.format("ping -c 1 %s", ip), false);
// 打印信息
if (result.errorMsg != null) {
LogPrintUtils.dTag(TAG, "isAvailableByPing - errorMsg: " + result.errorMsg);
}
if (result.successMsg != null) {
LogPrintUtils.dTag(TAG, "isAvailableByPing - successMsg: " + result.successMsg);
}
// 判断结果, 返回数据不为 null
return result.isSuccess3();
}
/**
* 获取后台服务进程
* @return 后台服务进程
*/
@RequiresPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
public static Set<String> getAllBackgroundProcesses() {
try {
Set<String> set = new HashSet<>();
ActivityManager activityManager = AppUtils.getActivityManager();
List<ActivityManager.RunningAppProcessInfo> lists = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : lists) {
Collections.addAll(set, appProcess.pkgList);
}
return set;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getAllBackgroundProcesses");
}
return Collections.emptySet();
}
@SuppressLint({"HardwareIds", "MissingPermission"})
@RequiresPermission(READ_PHONE_STATE)
public static String getMEID(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager == null) return "";
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? telephonyManager.getMeid() : telephonyManager.getDeviceId();
}
@RequiresPermission(permission.CAMERA)
void bindToLifecycle(LifecycleOwner lifecycleOwner) {
mNewLifecycle = lifecycleOwner;
if (getMeasuredWidth() > 0 && getMeasuredHeight() > 0) {
bindToLifecycleAfterViewMeasured();
}
}
/**
* 获取连接的网络类型
* @return 连接的网络类型
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public static int getConnectType() {
// 获取手机所有连接管理对象 ( 包括对 wi-fi,net 等连接的管理 )
try {
// 获取网络连接状态
ConnectivityManager cManager = AppUtils.getConnectivityManager();
// 版本兼容处理
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
// 判断连接的是否 Wifi
NetworkInfo.State wifiState = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// 判断是否连接上
if (wifiState == NetworkInfo.State.CONNECTED || wifiState == NetworkInfo.State.CONNECTING) {
return NET_WIFI;
} else {
// 判断连接的是否移动网络
NetworkInfo.State mobileState = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// 判断移动网络是否连接上
if (mobileState == NetworkInfo.State.CONNECTED || mobileState == NetworkInfo.State.CONNECTING) {
return NET_MOBILE;
}
}
} else {
// 获取当前活跃的网络 ( 连接的网络信息 )
Network network = cManager.getActiveNetwork();
if (network != null) {
NetworkCapabilities networkCapabilities = cManager.getNetworkCapabilities(network);
// 判断连接的是否 Wifi
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return NET_WIFI;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return NET_MOBILE;
}
}
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getConnectType");
}
return NO_NETWORK;
}
@RequiresPermission(Manifest.permission.CAMERA)
public void start(CameraSource cameraSource) throws IOException, SecurityException {
if (cameraSource == null) {
stop();
}
mCameraSource = cameraSource;
if (mCameraSource != null) {
mStartRequested = true;
startIfReady();
}
}
@SuppressLint("MissingPermission")
@RequiresPermission(Manifest.permission.CAMERA)
public void toggleFlash() {
Camera.Parameters p = camera.getParameters();
if(p.getFlashMode() == Parameters.FLASH_MODE_ON){
p.setFlashMode(Parameters.FLASH_MODE_OFF);
}
else if(p.getFlashMode() == Parameters.FLASH_MODE_OFF){
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
else if(p.getFlashMode().equals("off")){
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
else if(p.getFlashMode().equals("torch")){
p.setFlashMode(Parameters.FLASH_MODE_OFF);
}
else if(p.getFlashMode() == Parameters.FLASH_MODE_AUTO){
p.setFlashMode(Parameters.FLASH_MODE_ON);
}
else if(p.getFlashMode() == Parameters.FLASH_MODE_TORCH){
p.setFlashMode(Parameters.FLASH_MODE_OFF);
}
else{
p.setFlashMode(Parameters.FLASH_MODE_AUTO);
}
camera.setParameters(p);
camera.startPreview();
}
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean isNetworkAvailable(@NonNull Context context) {
boolean result = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); // Use getApplicationContext to solve a bug on Android M: https://stackoverflow.com/questions/41431409/connectivitymanager-leaking-not-sure-how-to-resolve
if (connectivityManager != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
result = activeNetworkInfo.isConnected();
}
}
return result;
}
/**
* 获取 MAC 地址
* @return MAC 地址
*/
@RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
private static String getMacAddressByWifiInfo() {
try {
@SuppressLint("WifiManagerLeak")
WifiManager wifiManager = AppUtils.getWifiManager();
if (wifiManager != null) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) return wifiInfo.getMacAddress();
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getMacAddressByWifiInfo");
}
return DEFAULT_MAC_ADDRESS;
}
/**
* Opens the camera and starts sending preview frames to the underlying detector. The preview
* frames are not displayed.
*
* @throws IOException if the camera's preview texture or display could not be initialized
*/
@RequiresPermission(Manifest.permission.CAMERA)
public CameraSource start() throws IOException {
synchronized (mCameraLock) {
if (mCamera != null) {
return this;
}
mCamera = createCamera();
// SurfaceTexture was introduced in Honeycomb (11), so if we are running and
// old version of Android. fall back to use SurfaceView.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mDummySurfaceTexture = new SurfaceTexture(DUMMY_TEXTURE_NAME);
mCamera.setPreviewTexture(mDummySurfaceTexture);
} else {
mDummySurfaceView = new SurfaceView(mContext);
mCamera.setPreviewDisplay(mDummySurfaceView.getHolder());
}
mCamera.startPreview();
mProcessingThread = new Thread(mFrameProcessor);
mFrameProcessor.setActive(true);
mProcessingThread.start();
}
return this;
}
/**
* Opens the camera and starts sending preview frames to the underlying detector. The preview
* frames are not displayed.
*
* @throws IOException if the camera's preview texture or display could not be initialized
*/
@SuppressLint("MissingPermission")
@RequiresPermission(Manifest.permission.CAMERA)
public CameraSource start() throws IOException, MobileVisionException {
synchronized (cameraLock) {
if (camera != null) {
return this;
}
camera = createCamera();
// SurfaceTexture was introduced in Honeycomb (11), so if we are running and
// old version of Android. fall back to use SurfaceView.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
dummySurfaceTexture = new SurfaceTexture(DUMMY_TEXTURE_NAME);
camera.setPreviewTexture(dummySurfaceTexture);
} else {
dummySurfaceView = new SurfaceView(context);
camera.setPreviewDisplay(dummySurfaceView.getHolder());
}
camera.startPreview();
processingThread = new Thread(frameProcessor);
frameProcessor.setActive(true);
processingThread.start();
}
return this;
}
@SuppressLint({"HardwareIds", "MissingPermission"})
@RequiresPermission(READ_PHONE_STATE)
public static String getMEID(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager == null) return "";
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? telephonyManager.getMeid() : telephonyManager.getDeviceId();
}