androidx.annotation.RequiresPermission Java Examples

The following examples show how to use androidx.annotation.RequiresPermission. 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: CameraSourcePreview.java    From samples-android with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example #2
Source File: ESPDevice.java    From esp-idf-provisioning-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #3
Source File: CameraSource.java    From esp-idf-provisioning-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: CurrentPlaceTestActivity.java    From android-places-demos with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #5
Source File: CurrentPlaceTestActivity.java    From android-places-demos with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #6
Source File: BarUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 设置 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;
}
 
Example #7
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 发送短信
 * @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;
}
 
Example #8
Source File: CameraSource.java    From flutter_barcode_scanner with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: CameraSource.java    From fast_qr_reader_view with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: DeviceUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 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;
}
 
Example #11
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 使用 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();
}
 
Example #12
Source File: CameraSourcePreview.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
@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;
    }
}
 
Example #13
Source File: BeepVibrateAssist.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 进行播放声音, 并且震动
 * @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;
}
 
Example #14
Source File: BleScanner.java    From esp-idf-provisioning-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #15
Source File: CameraXModule.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #16
Source File: AppUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 判断 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;
}
 
Example #17
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 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;
}
 
Example #18
Source File: Util.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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();
  }
}
 
Example #19
Source File: ProcessUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取后台服务进程
 * @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();
}
 
Example #20
Source File: NetworkUtils.java    From AcgClub with MIT License 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example #21
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取活动网络
 * @return {@link Network}
 */
@RequiresApi(Build.VERSION_CODES.M)
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public static Network getActiveNetwork() {
    try {
        return AppUtils.getConnectivityManager().getActiveNetwork();
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getActiveNetwork");
    }
    return null;
}
 
Example #22
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取设备唯一 UUID
 * @return 设备唯一 UUID
 */
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public static String getUUID() {
    String deviceId = getDeviceId() + "";
    String androidId = getAndroidId() + "";
    String serialNumber = getSerialNumber() + "";
    // 生成唯一关联 uuid
    UUID deviceUUID = new UUID(androidId.hashCode(), ((long) deviceId.hashCode() << 32) | serialNumber.hashCode());
    return deviceUUID.toString();
}
 
Example #23
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 根据 Wifi 获取网络 IP 地址
 * @return 网络 IP 地址
 */
@RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
public static String getIpAddressByWifi() {
    try {
        @SuppressLint("WifiManagerLeak")
        WifiManager wifiManager = AppUtils.getWifiManager();
        return Formatter.formatIpAddress(wifiManager.getDhcpInfo().ipAddress);
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getIpAddressByWifi");
    }
    return null;
}
 
Example #24
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 根据 Wifi 获取网关 IP 地址
 * @return 网关 IP 地址
 */
@RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
public static String getGatewayByWifi() {
    try {
        @SuppressLint("WifiManagerLeak")
        WifiManager wifiManager = AppUtils.getWifiManager();
        return Formatter.formatIpAddress(wifiManager.getDhcpInfo().gateway);
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getGatewayByWifi");
    }
    return null;
}
 
Example #25
Source File: ESPDevice.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(allOf = {Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE})
private String fetchWiFiSSID() {

    String ssid = null;
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {

        ssid = wifiInfo.getSSID();
        ssid = ssid.replace("\"", "");
    }
    Log.e(TAG, "Returning ssid : " + ssid);
    return ssid;
}
 
Example #26
Source File: CameraSource.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否连接了网络
 * @return {@code true} yes, {@code false} no
 */
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public static boolean isConnect() {
    try {
        // 获取手机所有连接管理对象 ( 包括对 wi-fi,net 等连接的管理 )
        ConnectivityManager cManager = AppUtils.getConnectivityManager();
        // 版本兼容处理
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            // 获取网络连接管理的对象
            NetworkInfo nInfo = cManager.getActiveNetworkInfo();
            // 判断是否为 null
            if (nInfo != null) {
                // 判断当前网络是否已经连接
                if (nInfo.getState() == State.CONNECTED) {
                    return true;
                }
            }
        } else {
            // 获取当前活跃的网络 ( 连接的网络信息 )
            Network network = cManager.getActiveNetwork();
            // 判断是否为 null
            if (network != null) {
                return true;
            }
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "isConnect");
    }
    return false;
}
 
Example #28
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取设备序列号
 * @return 设备序列号
 */
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public static String getSerialNumber() {
    try {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? Build.getSerial() : Build.SERIAL;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getSerialNumber");
    }
    return null;
}
 
Example #29
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 通过 IMSI 获取中国运营商简称
 * @param imsi IMSI 码
 * @return 中国运营商简称
 */
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public static String getChinaOperatorByIMSI(final String imsi) {
    if (imsi != null) {
        if (imsi.startsWith("46000") || imsi.startsWith("46002") || imsi.startsWith("46007")) {
            return "中国移动";
        } else if (imsi.startsWith("46001") || imsi.startsWith("46006")) {
            return "中国联通";
        } else if (imsi.startsWith("46003") || imsi.startsWith("46005") || imsi.startsWith("46011")) {
            return "中国电信";
        }
    }
    return null;
}
 
Example #30
Source File: PhoneUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 MEID 码
 * @param slotIndex 卡槽索引
 * @return MEID 码
 */
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public static String getMEID(final int slotIndex) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        try {
            if (slotIndex == -1) return AppUtils.getTelephonyManager().getMeid();
            return AppUtils.getTelephonyManager().getMeid(slotIndex);
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "getMEID");
        }
    }
    return null;
}