Here are the examples of the java api @android.annotation.SuppressLint(MissingPermission) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
398 Examples
19
Source : BasicInfoUtils.java
with Apache License 2.0
from ZhuoKeTeam
with Apache License 2.0
from ZhuoKeTeam
@SuppressLint("MissingPermission")
private static String getOCCID() {
TelephonyManager tm = (TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getSimSerialNumber() : null;
}
19
Source : BeepManager.java
with MIT License
from yuzhiqiang1993
with MIT License
from yuzhiqiang1993
/**
* 开启响铃和震动
*/
@SuppressLint("MissingPermission")
public synchronized void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
19
Source : MobileInfo.java
with Apache License 2.0
from yangxch
with Apache License 2.0
from yangxch
@SuppressLint("MissingPermission")
public static String GetIMEI(Context context) {
String IMEI;
try {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mTelephonyMgr.getDeviceId() + "";
if (IMEI != null && IMEI.equals("null")) {
IMEI = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
return IMEI;
} catch (Exception e) {
// TODO: handle exception
return "";
}
}
19
Source : MobileInfo.java
with Apache License 2.0
from yangxch
with Apache License 2.0
from yangxch
@SuppressLint("MissingPermission")
public static String GetIMSI(Context context) {
try {
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String IMSI = mTelephonyMgr.getSubscriberId() + "";
if (IMSI.equals("") || IMSI.equals("null")) {
// 获取不到IMSI返回串码
IMSI = GetIMEI(context);
}
return IMSI;
} catch (Exception e) {
// TODO: handle exception
return "";
}
}
19
Source : PhoneInfoUtils.java
with Apache License 2.0
from y1xian
with Apache License 2.0
from y1xian
// 获取sim卡iccid
@SuppressLint("MissingPermission")
public static String getIccid() {
String iccid = "N/A";
iccid = telephonyManager.getSimSerialNumber();
return iccid;
}
19
Source : LocationUtils.java
with Apache License 2.0
from y1xian
with Apache License 2.0
from y1xian
/**
* 注销
*/
@SuppressLint("MissingPermission")
public static void unregister() {
if (mLocationManager != null) {
if (myLocationListener != null) {
mLocationManager.removeUpdates(myLocationListener);
myLocationListener = null;
}
mLocationManager = null;
}
}
19
Source : PhotoEditFragment.java
with Apache License 2.0
from xuexiangjys
with Apache License 2.0
from xuexiangjys
/**
* 保存图片
*/
@SuppressLint("MissingPermission")
@Permission(STORAGE)
private void saveImage() {
getMessageLoader("保存中...").show();
mPhotoEditor.saveAsFile(Utils.getImageSavePath(), new PhotoEditor.OnSaveListener() {
@Override
public void onSuccess(@NonNull String imagePath) {
getMessageLoader().dismiss();
if (photoEditorView != null) {
photoEditorView.getSource().setImageBitmap(ImageUtils.getBitmap(imagePath));
}
}
@Override
public void onFailure(@NonNull Exception exception) {
getMessageLoader().dismiss();
XToastUtils.error(exception);
}
});
}
19
Source : BeepManager.java
with GNU General Public License v3.0
from umerov1999
with GNU General Public License v3.0
from umerov1999
@SuppressLint("MissingPermission")
public synchronized void playBeepSoundAndVibrate() {
if (beepEnabled) {
playBeepSound();
}
if (vibrateEnabled) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
vibrator.vibrate(VIBRATE_DURATION);
}
}
}
19
Source : Dispatcher.java
with GNU General Public License v3.0
from umerov1999
with GNU General Public License v3.0
from umerov1999
@SuppressLint("MissingPermission")
void performRetry(BitmapHunter hunter) {
if (hunter.isCancelled())
return;
if (service.isShutdown()) {
performError(hunter, false);
return;
}
NetworkInfo networkInfo = null;
if (scansNetworkChanges) {
ConnectivityManager connectivityManager = getService(context, CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
}
if (hunter.shouldRetry(airplaneMode, networkInfo)) {
if (hunter.getPicreplacedo().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_RETRYING, getLogIdsForHunter(hunter));
}
if (hunter.getException() instanceof NetworkRequestHandler.ContentLengthException) {
hunter.networkPolicy |= NetworkPolicy.NO_CACHE.index;
}
hunter.future = service.submit(hunter);
} else {
// Mark for replay only if we observe network info changes and support replay.
boolean willReplay = scansNetworkChanges && hunter.supportsReplay();
performError(hunter, willReplay);
if (willReplay) {
markForReplay(hunter);
}
}
}
19
Source : CrashUtils.java
with Apache License 2.0
from tianshaojie
with Apache License 2.0
from tianshaojie
/**
* Initialization
* <p>Must hold {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />}</p>
*
* @param onCrashListener The crash listener.
*/
@SuppressLint("MissingPermission")
public static void init(final OnCrashListener onCrashListener) {
init("", onCrashListener);
}
19
Source : CrashUtils.java
with Apache License 2.0
from tianshaojie
with Apache License 2.0
from tianshaojie
/**
* Initialization.
* <p>Must hold {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />}</p>
*/
@SuppressLint("MissingPermission")
public static void init() {
init("");
}
19
Source : LocationPickerActivity.java
with GNU Affero General Public License v3.0
from threema-ch
with GNU Affero General Public License v3.0
from threema-ch
@SuppressLint("MissingPermission")
private void initMap() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
finish();
return;
}
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap1) {
mapboxMap = mapboxMap1;
mapboxMap.setStyle(new Style.Builder().fromUrl(MAP_STYLE_URL), new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
// Map is set up and the style has loaded. Now you can add data or make other mapView adjustments
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
setupLocationComponent(style);
if (locationComponent.getLastKnownLocation() == null) {
mapboxMap.animateCamera(CameraUpdateFactory.zoomTo(1));
showLocationNotAvailable();
}
}
updatePois();
}
});
mapboxMap.getUiSettings().setAttributionEnabled(false);
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.setOnMarkerClickListener(marker -> {
for (Poi poi : places) {
if (poi.getId() == Long.valueOf(marker.getSnippet())) {
returnData(poi);
return true;
}
}
return false;
});
mapboxMap.addOnMoveListener(new MapboxMap.OnMoveListener() {
@Override
public void onMoveBegin(@NonNull MoveGestureDetector detector) {
}
@Override
public void onMove(@NonNull MoveGestureDetector detector) {
}
@Override
public void onMoveEnd(@NonNull MoveGestureDetector detector) {
updatePois();
}
});
mapboxMap.addOnCameraIdleListener(new MapboxMap.OnCameraIdleListener() {
@Override
public void onCameraIdle() {
updatePois();
}
});
}
});
}
19
Source : CameraXModule.java
with GNU Affero General Public License v3.0
from threema-ch
with GNU Affero General Public License v3.0
from threema-ch
// TODO(b/124269166): Rethink how we can handle permissions here.
@SuppressLint("MissingPermission")
public void setCameraLensFacing(@Nullable Integer lensFacing) {
// Setting same lens facing is a no-op, so check for that first
if (!Objects.equals(mCameraLensFacing, lensFacing)) {
// If we're not bound to a lifecycle, just update the camera that will be opened when we
// attach to a lifecycle.
mCameraLensFacing = lensFacing;
if (mCurrentLifecycle != null) {
// Re-bind to lifecycle with new camera
bindToLifecycle(mCurrentLifecycle);
}
}
}
19
Source : CameraXModule.java
with GNU Affero General Public License v3.0
from threema-ch
with GNU Affero General Public License v3.0
from threema-ch
// TODO(b/124269166): Rethink how we can handle permissions here.
@SuppressLint("MissingPermission")
private void rebindToLifecycle() {
if (mCurrentLifecycle != null) {
bindToLifecycle(mCurrentLifecycle);
}
}
19
Source : CameraView.java
with GNU Affero General Public License v3.0
from threema-ch
with GNU Affero General Public License v3.0
from threema-ch
// TODO(b/124269166): Rethink how we can handle permissions here.
@SuppressLint("MissingPermission")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Since bindToLifecycle will depend on the measured dimension, only call it when measured
// dimension is not 0x0
if (getMeasuredWidth() > 0 && getMeasuredHeight() > 0) {
mCameraModule.bindToLifecycleAfterViewMeasured();
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
19
Source : CameraView.java
with GNU Affero General Public License v3.0
from threema-ch
with GNU Affero General Public License v3.0
from threema-ch
// TODO(b/124269166): Rethink how we can handle permissions here.
@SuppressLint("MissingPermission")
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// In case that the CameraView size is always set as 0x0, we still need to trigger to force
// binding to lifecycle
mCameraModule.bindToLifecycleAfterViewMeasured();
mCameraModule.invalidateView();
super.onLayout(changed, left, top, right, bottom);
}
19
Source : ConnectorUtils.java
with Apache License 2.0
from ThanosFisherman
with Apache License 2.0
from ThanosFisherman
@SuppressLint("MissingPermission")
public final clreplaced ConnectorUtils {
private static final int MAX_PRIORITY = 99999;
public static boolean isAlreadyConnected(@Nullable WifiManager wifiManager, @Nullable String bssid) {
if (bssid != null && wifiManager != null) {
if (wifiManager.getConnectionInfo() != null && wifiManager.getConnectionInfo().getBSSID() != null && wifiManager.getConnectionInfo().getIpAddress() != 0 && Objects.equals(bssid, wifiManager.getConnectionInfo().getBSSID())) {
wifiLog("Already connected to: " + wifiManager.getConnectionInfo().getSSID() + " BSSID: " + wifiManager.getConnectionInfo().getBSSID());
return true;
}
}
return false;
}
public static boolean isAlreadyConnected2(@Nullable WifiManager wifiManager, @Nullable String ssid) {
if (ssid != null && wifiManager != null) {
if (wifiManager.getConnectionInfo() != null && wifiManager.getConnectionInfo().getSSID() != null && wifiManager.getConnectionInfo().getIpAddress() != 0 && Objects.equals(ssid, wifiManager.getConnectionInfo().getSSID())) {
wifiLog("Already connected to: " + wifiManager.getConnectionInfo().getSSID() + " BSSID: " + wifiManager.getConnectionInfo().getBSSID());
return true;
}
}
return false;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static boolean isConnectedToNetworkLollipop(@Nullable ConnectivityManager connectivityManager) {
// final ConnectivityManager connMgr =
// (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null)
return false;
boolean isWifiConn = false;
for (Network network : connectivityManager.getAllNetworks()) {
final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo != null && ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
isWifiConn |= networkInfo.isConnected();
}
}
return isWifiConn;
}
public static boolean isAlreadyConnected(@Nullable ConnectivityManager connectivityManager) {
if (isLollipopOrLater()) {
return isConnectedToNetworkLollipop(connectivityManager);
}
return of(connectivityManager).next(manager -> manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)).next(NetworkInfo::getState).next(state -> state == NetworkInfo.State.CONNECTED).getBoolean();
}
public static boolean isAlreadyConnected(@Nullable WifiManager wifiManager, @Nullable ConnectivityManager connectivityManager, @Nullable String ssid) {
boolean result = isAlreadyConnected(connectivityManager);
if (result) {
if (ssid != null && wifiManager != null) {
String quotedSsid = ssid;
if (VersionUtils.isJellyBeanOrLater()) {
quotedSsid = SSIDUtils.convertToQuotedString(ssid);
}
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String tempSSID = wifiInfo.getSSID();
result = tempSSID != null && tempSSID.equals(quotedSsid);
}
}
return result;
}
@SuppressWarnings("UnusedReturnValue")
private static boolean checkForExcessOpenNetworkAndSave(@NonNull final ContentResolver resolver, @NonNull final WifiManager wifiMgr) {
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
sortByPriority(configurations);
boolean modified = false;
int tempCount = 0;
final int numOpenNetworksKept = isJellyBeanOrLater() ? Settings.Secure.getInt(resolver, Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT, 10) : Settings.Secure.getInt(resolver, Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10);
for (int i = configurations.size() - 1; i >= 0; i--) {
final WifiConfiguration config = configurations.get(i);
if (Objects.equals(ConfigSecurities.SECURITY_NONE, ConfigSecurities.getSecurity(config))) {
tempCount++;
if (tempCount >= numOpenNetworksKept) {
modified = true;
wifiMgr.removeNetwork(config.networkId);
}
}
}
return !modified || wifiMgr.saveConfiguration();
}
private static int getMaxPriority(@Nullable final WifiManager wifiManager) {
if (wifiManager == null) {
return 0;
}
final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
int pri = 0;
for (final WifiConfiguration config : configurations) {
if (config.priority > pri) {
pri = config.priority;
}
}
return pri;
}
private static int shiftPriorityAndSave(@Nullable final WifiManager wifiMgr) {
if (wifiMgr == null) {
return 0;
}
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
sortByPriority(configurations);
final int size = configurations.size();
for (int i = 0; i < size; i++) {
final WifiConfiguration config = configurations.get(i);
config.priority = i;
wifiMgr.updateNetwork(config);
}
wifiMgr.saveConfiguration();
return size;
}
@Nullable
private static String trimQuotes(@Nullable String str) {
if (str != null && !str.isEmpty()) {
return str.replaceAll("^\"*", "").replaceAll("\"*$", "");
}
return str;
}
@SuppressWarnings("unused")
public static int getPowerPercentage(int power) {
int i;
if (power <= -93) {
i = 0;
} else if (-25 <= power && power <= 0) {
i = 100;
} else {
i = 125 + power;
}
return i;
}
public static boolean isHexWepKey(@Nullable String wepKey) {
final int preplacedwordLen = wepKey == null ? 0 : wepKey.length();
return (preplacedwordLen == 10 || preplacedwordLen == 26 || preplacedwordLen == 58) && wepKey.matches("[0-9A-Fa-f]*");
}
private static void sortByPriority(@NonNull final List<WifiConfiguration> configurations) {
Collections.sort(configurations, (o1, o2) -> o1.priority - o2.priority);
}
@SuppressWarnings("unused")
public static int frequencyToChannel(int freq) {
if (2412 <= freq && freq <= 2484) {
return (freq - 2412) / 5 + 1;
} else if (5170 <= freq && freq <= 5825) {
return (freq - 5170) / 5 + 34;
} else {
return -1;
}
}
static void registerReceiver(@NonNull final Context context, @Nullable final BroadcastReceiver receiver, @NonNull final IntentFilter filter) {
if (receiver != null) {
try {
context.registerReceiver(receiver, filter);
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
}
static void unregisterReceiver(@NonNull final Context context, @Nullable final BroadcastReceiver receiver) {
if (receiver != null) {
try {
context.unregisterReceiver(receiver);
} catch (IllegalArgumentException ignored) {
}
}
}
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
static boolean connectToWifi(@NonNull final Context context, @Nullable final WifiManager wifiManager, @Nullable final ConnectivityManager connectivityManager, @NonNull WeakHandler handler, @NonNull final ScanResult scanResult, @NonNull final String preplacedword, @NonNull WifiConnectionCallback wifiConnectionCallback) {
if (wifiManager == null || connectivityManager == null) {
return false;
}
if (isAndroidQOrLater()) {
return connectAndroidQ(wifiManager, connectivityManager, handler, wifiConnectionCallback, scanResult, preplacedword);
}
return connectPreAndroidQ(context, wifiManager, scanResult, preplacedword);
}
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
static boolean connectToWifiHidden(@NonNull final Context context, @Nullable final WifiManager wifiManager, @Nullable final ConnectivityManager connectivityManager, @NonNull WeakHandler handler, // @NonNull final ScanResult scanResult,
@NonNull final String ssid, @Nullable final String type, @NonNull final String preplacedword, @NonNull WifiConnectionCallback wifiConnectionCallback) {
if (wifiManager == null || connectivityManager == null || type == null) {
return false;
}
if (isAndroidQOrLater()) {
return connectAndroidQHidden(wifiManager, connectivityManager, handler, wifiConnectionCallback, ssid, type, preplacedword);
}
return connectPreAndroidQHidden(context, wifiManager, ssid, type, preplacedword);
}
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
private static boolean connectPreAndroidQ(@NonNull final Context context, @Nullable final WifiManager wifiManager, @NonNull final ScanResult scanResult, @NonNull final String preplacedword) {
if (wifiManager == null) {
return false;
}
WifiConfiguration config = ConfigSecurities.getWifiConfiguration(wifiManager, scanResult);
if (config != null && preplacedword.isEmpty()) {
wifiLog("PreplacedWORD WAS EMPTY. TRYING TO CONNECT TO EXISTING NETWORK CONFIGURATION");
return connectToConfiguredNetwork(wifiManager, config, true);
}
if (!cleanPreviousConfiguration(wifiManager, config)) {
wifiLog("COULDN'T REMOVE PREVIOUS CONFIG, CONNECTING TO EXISTING ONE");
return connectToConfiguredNetwork(wifiManager, config, true);
}
final String security = ConfigSecurities.getSecurity(scanResult);
if (Objects.equals(ConfigSecurities.SECURITY_NONE, security)) {
checkForExcessOpenNetworkAndSave(context.getContentResolver(), wifiManager);
}
config = new WifiConfiguration();
config.SSID = convertToQuotedString(scanResult.SSID);
config.BSSID = scanResult.BSSID;
ConfigSecurities.setupSecurity(config, security, preplacedword);
int id = wifiManager.addNetwork(config);
wifiLog("Network ID: " + id);
if (id == -1) {
return false;
}
if (!wifiManager.saveConfiguration()) {
wifiLog("Couldn't save wifi config");
return false;
}
// We have to retrieve the WifiConfiguration after save
config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
if (config == null) {
wifiLog("Error getting wifi config after save. (config == null)");
return false;
}
return connectToConfiguredNetwork(wifiManager, config, true);
}
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
private static boolean connectPreAndroidQHidden(@NonNull final Context context, @Nullable final WifiManager wifiManager, @NonNull final String ssid, @NonNull final String type, @NonNull final String preplacedword) {
if (wifiManager == null) {
return false;
}
//
WifiConfiguration config;
final String security = ConfigSecurities.getSecurity(type);
if (Objects.equals(ConfigSecurities.SECURITY_NONE, security)) {
checkForExcessOpenNetworkAndSave(context.getContentResolver(), wifiManager);
}
config = new WifiConfiguration();
config.SSID = convertToQuotedString(ssid);
ConfigSecurities.setupSecurityHidden(config, security, preplacedword);
int id = wifiManager.addNetwork(config);
wifiLog("Hidden-Network ID: " + id);
if (id == -1) {
return false;
}
if (!wifiManager.saveConfiguration()) {
wifiLog("Couldn't save wifi config");
return false;
}
// We have to retrieve the WifiConfiguration after save
config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
if (config == null) {
wifiLog("Error getting wifi config after save. (config == null)");
return false;
}
return connectToConfiguredNetwork(wifiManager, config, true);
}
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
private static boolean connectToConfiguredNetwork(@Nullable WifiManager wifiManager, @Nullable WifiConfiguration config, boolean rereplacedociate) {
if (config == null || wifiManager == null) {
return false;
}
if (isMarshmallowOrLater()) {
return disableAllButOne(wifiManager, config) && (rereplacedociate ? wifiManager.rereplacedociate() : wifiManager.reconnect());
}
// Make it the highest priority.
int newPri = getMaxPriority(wifiManager) + 1;
if (newPri > MAX_PRIORITY) {
newPri = shiftPriorityAndSave(wifiManager);
config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
if (config == null) {
return false;
}
}
// Set highest priority to this configured network
config.priority = newPri;
int networkId = wifiManager.updateNetwork(config);
if (networkId == -1) {
return false;
}
// Do not disable others
if (!wifiManager.enableNetwork(networkId, false)) {
return false;
}
if (!wifiManager.saveConfiguration()) {
return false;
}
// We have to retrieve the WifiConfiguration after save.
config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
return config != null && disableAllButOne(wifiManager, config) && (rereplacedociate ? wifiManager.rereplacedociate() : wifiManager.reconnect());
}
@RequiresApi(Build.VERSION_CODES.Q)
private static boolean connectAndroidQ(@Nullable WifiManager wifiManager, @Nullable ConnectivityManager connectivityManager, @NonNull WeakHandler handler, @NonNull WifiConnectionCallback wifiConnectionCallback, @NonNull ScanResult scanResult, @NonNull String preplacedword) {
if (connectivityManager == null) {
return false;
}
WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder().setSsid(scanResult.SSID).setBssid(MacAddress.fromString(scanResult.BSSID));
final String security = ConfigSecurities.getSecurity(scanResult);
ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, preplacedword);
final NetworkRequest networkRequest = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).setNetworkSpecifier(wifiNetworkSpecifierBuilder.build()).addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED).build();
// cleanup previous connections just in case
DisconnectCallbackHolder.getInstance().disconnect();
final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
wifiLog("AndroidQ+ connected to wifi ");
// TODO: should this actually be in the success listener on WifiUtils?
// We could preplaced the networkrequest maybe?
// bind so all api calls are performed over this new network
// if we don't bind, connection with the wifi network is immediately dropped
DisconnectCallbackHolder.getInstance().bindProcessToNetwork(network);
connectivityManager.setNetworkPreference(ConnectivityManager.DEFAULT_NETWORK_PREFERENCE);
// On some Android 10 devices, connection is made and than immediately lost due to a firmware bug,
// read more here: https://github.com/ThanosFisherman/WifiUtils/issues/63.
handler.postDelayed(() -> {
if (isAlreadyConnected(wifiManager, of(scanResult).next(scanResult1 -> scanResult1.BSSID).get())) {
wifiConnectionCallback.successfulConnect();
} else {
wifiConnectionCallback.errorConnect(ConnectionErrorCode.ANDROID_10_IMMEDIATELY_DROPPED_CONNECTION);
}
}, 500);
}
@Override
public void onUnavailable() {
super.onUnavailable();
wifiLog("AndroidQ+ could not connect to wifi");
wifiConnectionCallback.errorConnect(ConnectionErrorCode.USER_CANCELLED);
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
wifiLog("onLost");
// cancel connecting if needed, this prevents 'request loops' on some oneplus/redmi phones
DisconnectCallbackHolder.getInstance().unbindProcessFromNetwork();
DisconnectCallbackHolder.getInstance().disconnect();
}
};
DisconnectCallbackHolder.getInstance().addNetworkCallback(networkCallback, connectivityManager);
wifiLog("connecting with Android 10");
DisconnectCallbackHolder.getInstance().requestNetwork(networkRequest);
return true;
}
// FIXME: we should use WifiNetworkSuggestion api to connect WLAN on Android 10, I`ll fix it soon.
@RequiresApi(Build.VERSION_CODES.Q)
private static boolean connectAndroidQHidden(@Nullable WifiManager wifiManager, @Nullable ConnectivityManager connectivityManager, @NonNull WeakHandler handler, @NonNull WifiConnectionCallback wifiConnectionCallback, @NonNull String ssid, @NonNull String type, String preplacedword) {
if (connectivityManager == null) {
return false;
}
WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder().setIsHiddenSsid(true).setSsid(ssid);
final String security = ConfigSecurities.getSecurity(type);
ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, preplacedword);
final NetworkRequest networkRequest = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED).setNetworkSpecifier(wifiNetworkSpecifierBuilder.build()).build();
// // cleanup previous connections just in case
DisconnectCallbackHolder.getInstance().disconnect();
final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
wifiLog("AndroidQ+ connected to wifi ");
// TODO: should this actually be in the success listener on WifiUtils?
// We could preplaced the networkrequest maybe?
// bind so all api calls are performed over this new network
// if we don't bind, connection with the wifi network is immediately dropped
DisconnectCallbackHolder.getInstance().bindProcessToNetwork(network);
connectivityManager.setNetworkPreference(ConnectivityManager.DEFAULT_NETWORK_PREFERENCE);
// On some Android 10 devices, connection is made and than immediately lost due to a firmware bug,
// read more here: https://github.com/ThanosFisherman/WifiUtils/issues/63.
handler.postDelayed(() -> {
if (isAlreadyConnected(wifiManager, ssid)) {
wifiConnectionCallback.successfulConnect();
} else {
wifiConnectionCallback.errorConnect(ConnectionErrorCode.ANDROID_10_IMMEDIATELY_DROPPED_CONNECTION);
}
}, 500);
}
@Override
public void onUnavailable() {
super.onUnavailable();
wifiLog("AndroidQ+ could not connect to wifi");
wifiConnectionCallback.errorConnect(ConnectionErrorCode.USER_CANCELLED);
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
wifiLog("onLost");
// cancel connecting if needed, this prevents 'request loops' on some oneplus/redmi phones
DisconnectCallbackHolder.getInstance().unbindProcessFromNetwork();
DisconnectCallbackHolder.getInstance().disconnect();
}
@Override
public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties linkProperties) {
super.onLinkPropertiesChanged(network, linkProperties);
wifiLog("onLost");
}
};
DisconnectCallbackHolder.getInstance().addNetworkCallback(networkCallback, connectivityManager);
wifiLog("connecting with Android 10");
DisconnectCallbackHolder.getInstance().requestNetwork(networkRequest);
return true;
}
private static boolean disableAllButOne(@Nullable final WifiManager wifiManager, @Nullable final WifiConfiguration config) {
if (wifiManager == null) {
return false;
}
@Nullable
final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
if (configurations == null || config == null || configurations.isEmpty()) {
return false;
}
boolean result = false;
for (WifiConfiguration wifiConfig : configurations) {
if (wifiConfig == null) {
continue;
}
if (wifiConfig.networkId == config.networkId) {
result = wifiManager.enableNetwork(wifiConfig.networkId, true);
} else {
wifiManager.disableNetwork(wifiConfig.networkId);
}
}
wifiLog("disableAllButOne " + result);
return result;
}
@SuppressWarnings("UnusedReturnValue")
private static boolean disableAllButOne(@Nullable final WifiManager wifiManager, @Nullable final ScanResult scanResult) {
if (wifiManager == null) {
return false;
}
@Nullable
final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
if (configurations == null || scanResult == null || configurations.isEmpty()) {
return false;
}
boolean result = false;
for (WifiConfiguration wifiConfig : configurations) {
if (wifiConfig == null) {
continue;
}
if (Objects.equals(scanResult.BSSID, wifiConfig.BSSID) && Objects.equals(scanResult.SSID, trimQuotes(wifiConfig.SSID))) {
result = wifiManager.enableNetwork(wifiConfig.networkId, true);
} else {
wifiManager.disableNetwork(wifiConfig.networkId);
}
}
return result;
}
public static boolean reEnableNetworkIfPossible(@Nullable final WifiManager wifiManager, @Nullable final ScanResult scanResult) {
if (wifiManager == null) {
return false;
}
@Nullable
final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
if (configurations == null || scanResult == null || configurations.isEmpty()) {
return false;
}
boolean result = false;
for (WifiConfiguration wifiConfig : configurations) if (Objects.equals(scanResult.BSSID, wifiConfig.BSSID) && Objects.equals(scanResult.SSID, trimQuotes(wifiConfig.SSID))) {
result = wifiManager.enableNetwork(wifiConfig.networkId, true);
break;
}
wifiLog("reEnableNetworkIfPossible " + result);
return result;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
static void connectWps(@Nullable final WifiManager wifiManager, @NonNull WeakHandler handler, @NonNull final ScanResult scanResult, @NonNull String pin, long timeOutMillis, @NonNull final ConnectionWpsListener connectionWpsListener) {
if (wifiManager == null) {
connectionWpsListener.isSuccessful(false);
return;
}
final WpsInfo wpsInfo = new WpsInfo();
final Runnable handlerTimeoutRunnable = new Runnable() {
@Override
public void run() {
wifiManager.cancelWps(null);
wifiLog("Connection with WPS has timed out");
cleanPreviousConfiguration(wifiManager, scanResult);
connectionWpsListener.isSuccessful(false);
handler.removeCallbacks(this);
}
};
final WifiManager.WpsCallback wpsCallback = new WifiManager.WpsCallback() {
@Override
public void onStarted(String pin) {
}
@Override
public void onSucceeded() {
handler.removeCallbacks(handlerTimeoutRunnable);
wifiLog("CONNECTED With WPS successfully");
connectionWpsListener.isSuccessful(true);
}
@Override
public void onFailed(int reason) {
handler.removeCallbacks(handlerTimeoutRunnable);
final String reasonStr;
switch(reason) {
case 3:
reasonStr = "WPS_OVERLAP_ERROR";
break;
case 4:
reasonStr = "WPS_WEP_PROHIBITED";
break;
case 5:
reasonStr = "WPS_TKIP_ONLY_PROHIBITED";
break;
case 6:
reasonStr = "WPS_AUTH_FAILURE";
break;
case 7:
reasonStr = "WPS_TIMED_OUT";
break;
default:
reasonStr = String.valueOf(reason);
}
wifiLog("FAILED to connect with WPS. Reason: " + reasonStr);
cleanPreviousConfiguration(wifiManager, scanResult);
reenableAllHotspots(wifiManager);
connectionWpsListener.isSuccessful(false);
}
};
wifiLog("Connecting with WPS...");
wpsInfo.setup = WpsInfo.KEYPAD;
wpsInfo.BSSID = scanResult.BSSID;
wpsInfo.pin = pin;
wifiManager.cancelWps(null);
if (!cleanPreviousConfiguration(wifiManager, scanResult)) {
disableAllButOne(wifiManager, scanResult);
}
handler.postDelayed(handlerTimeoutRunnable, timeOutMillis);
wifiManager.startWps(wpsInfo, wpsCallback);
}
@RequiresPermission(ACCESS_WIFI_STATE)
static boolean disconnectFromWifi(@NonNull final WifiManager wifiManager) {
return wifiManager.disconnect();
}
@RequiresPermission(ACCESS_WIFI_STATE)
static boolean removeWifi(@NonNull final WifiManager wifiManager, @NonNull final String ssid) {
final WifiConfiguration wifiConfiguration = ConfigSecurities.getWifiConfiguration(wifiManager, ssid);
return cleanPreviousConfiguration(wifiManager, wifiConfiguration);
}
@RequiresPermission(allOf = { ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE })
static boolean cleanPreviousConfiguration(@Nullable final WifiManager wifiManager, @NonNull final ScanResult scanResult) {
if (wifiManager == null) {
return false;
}
// On Android 6.0 (API level 23) and above if my app did not create the configuration in the first place, it can not remove it either.
final WifiConfiguration config = ConfigSecurities.getWifiConfiguration(wifiManager, scanResult);
wifiLog("Attempting to remove previous network config...");
if (config == null) {
return true;
}
if (wifiManager.removeNetwork(config.networkId)) {
wifiManager.saveConfiguration();
return true;
}
return false;
}
static boolean cleanPreviousConfiguration(@Nullable final WifiManager wifiManager, @Nullable final WifiConfiguration config) {
// On Android 6.0 (API level 23) and above if my app did not create the configuration in the first place, it can not remove it either.
if (wifiManager == null) {
return false;
}
wifiLog("Attempting to remove previous network config...");
if (config == null) {
return true;
}
if (wifiManager.removeNetwork(config.networkId)) {
wifiManager.saveConfiguration();
return true;
}
return false;
}
static void reenableAllHotspots(@Nullable WifiManager wifi) {
if (wifi == null) {
return;
}
final List<WifiConfiguration> configurations = wifi.getConfiguredNetworks();
if (configurations != null && !configurations.isEmpty()) {
for (final WifiConfiguration config : configurations) {
wifi.enableNetwork(config.networkId, false);
}
}
}
@Nullable
static ScanResult matchScanResultSsid(@NonNull String ssid, @NonNull Iterable<ScanResult> results) {
for (ScanResult result : results) {
if (Objects.equals(result.SSID, ssid)) {
return result;
}
}
return null;
}
@Nullable
static ScanResult matchScanResult(@NonNull String ssid, @NonNull String bssid, @NonNull Iterable<ScanResult> results) {
for (ScanResult result : results) {
if (Objects.equals(result.SSID, ssid) && Objects.equals(result.BSSID, bssid)) {
return result;
}
}
return null;
}
@Nullable
static ScanResult matchScanResultBssid(@NonNull String bssid, @NonNull Iterable<ScanResult> results) {
for (ScanResult result : results) {
if (Objects.equals(result.BSSID, bssid)) {
return result;
}
}
return null;
}
}
19
Source : CalendarAdapterImpl.java
with BSD 3-Clause "New" or "Revised" License
from synyx
with BSD 3-Clause "New" or "Revised" License
from synyx
@SuppressLint("MissingPermission")
private Cursor loadRoomCalendarById(long id) {
String[] mProjection = { //
CalendarContract.Calendars._ID, //
CalendarContract.Calendars.OWNER_ACCOUNT, //
CalendarContract.Calendars.NAME, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME };
String selection = CalendarContract.Calendars._ID + " = ?";
String[] selectionArgs = { String.valueOf(id) };
return contentResolver.query(CalendarContract.Calendars.CONTENT_URI, mProjection, selection, selectionArgs, null);
}
19
Source : QrcodeActivity.java
with Apache License 2.0
from Straas
with Apache License 2.0
from Straas
@SuppressLint("MissingPermission")
public clreplaced QrcodeActivity extends AppCompatActivity implements Callback, OnSuccessListener<Barcode> {
public static final int LOADER_ID = 0;
public static final String KEY_QR_CODE_VALUE = "key_qr_code";
public static final String TAG = QrcodeActivity.clreplaced.getSimpleName();
private SurfaceHolder mSurfaceHolder;
private CameraSource mCameraSource;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowreplacedleEnabled(false);
SurfaceView surfaceView = findViewById(R.id.surfaceview);
surfaceView.getHolder().addCallback(this);
getSupportLoaderManager().initLoader(LOADER_ID, null, new LoaderCallbacks<CameraSource>() {
@Override
public Loader<CameraSource> onCreateLoader(int id, Bundle args) {
return new CameraSourceLoader(QrcodeActivity.this);
}
@Override
public void onLoadFinished(Loader<CameraSource> loader, CameraSource data) {
((CameraSourceLoader) loader).getBarcodeScanTask().addOnSuccessListener(QrcodeActivity.this, QrcodeActivity.this);
mCameraSource = data;
if (mSurfaceHolder != null) {
startCameraSource();
}
}
@Override
public void onLoaderReset(Loader<CameraSource> loader) {
}
});
}
@Override
protected void onPause() {
super.onPause();
getSupportLoaderManager().getLoader(LOADER_ID).stopLoading();
mCameraSource = null;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.gereplacedemId()) {
case android.R.id.home:
// Because of this issue: http://stackoverflow.com/a/29464116
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSuccess(Barcode barcode) {
Intent intent = new Intent();
intent.putExtra(KEY_QR_CODE_VALUE, barcode.displayValue);
setResult(RESULT_OK, intent);
finish();
}
private void startCameraSource() {
if (mCameraSource != null) {
try {
mCameraSource.start(mSurfaceHolder);
} catch (IOException e) {
e.printStackTrace();
Intent intent = new Intent();
intent.putExtra(TAG, e.getMessage());
setResult(RESULT_CANCELED, intent);
finish();
}
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
startCameraSource();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mSurfaceHolder = null;
}
}
19
Source : GPSService.java
with MIT License
from smtrz
with MIT License
from smtrz
@SuppressLint("MissingPermission")
private void startLocationUpdate() {
// Getting all the paramters.
initLocationRequest();
// Requesting Location Updates..
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
19
Source : SDDeviceUtil.java
with Apache License 2.0
from SiberiaDante
with Apache License 2.0
from SiberiaDante
/**
* 获取IMSI码
* <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
*
* @return IMSI码
*/
@SuppressLint("MissingPermission")
public static String getIMSI() {
TelephonyManager tm = (TelephonyManager) SDAndroidLib.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getSubscriberId() : null;
}
19
Source : USSDController.java
with Apache License 2.0
from romellfudi
with Apache License 2.0
from romellfudi
/**
* Invoke a dial-up calling a ussd number and
* you had a overlay progress widget
*
* @param ussdPhoneNumber ussd number
* @param simSlot simSlot number to use
* @param map Map of Login and problem messages
* @param callbackInvoke a callback object from return answer
*/
@SuppressLint("MissingPermission")
public void callUSSDOverlayInvoke(String ussdPhoneNumber, int simSlot, HashMap<String, HashSet<String>> map, CallbackInvoke callbackInvoke) {
this.callbackInvoke = callbackInvoke;
this.map = map;
if (verifyAccesibilityAccess(context) && verifyOverLay(context)) {
dialUp(ussdPhoneNumber, simSlot);
} else {
this.callbackInvoke.over("Check your accessibility | overlay permission");
}
}
19
Source : USSDController.java
with Apache License 2.0
from romellfudi
with Apache License 2.0
from romellfudi
/**
* Invoke a dial-up calling a ussd number
*
* @param ussdPhoneNumber ussd number
* @param simSlot simSlot number to use
* @param map Map of Login and problem messages
* @param callbackInvoke a callback object from return answer
*/
@SuppressLint("MissingPermission")
public void callUSSDInvoke(String ussdPhoneNumber, int simSlot, HashMap<String, HashSet<String>> map, CallbackInvoke callbackInvoke) {
this.callbackInvoke = callbackInvoke;
this.map = map;
if (verifyAccesibilityAccess(context)) {
dialUp(ussdPhoneNumber, simSlot);
} else {
this.callbackInvoke.over("Check your accessibility");
}
}
19
Source : RScanCamera.java
with BSD 3-Clause "New" or "Revised" License
from rhymelph
with BSD 3-Clause "New" or "Revised" License
from rhymelph
@SuppressLint("MissingPermission")
void open(@NonNull final MethodChannel.Result result) throws CameraAccessException {
// Used to steam image byte data to dart side.
imageStreamReader = ImageReader.newInstance(previewSize.getWidth(), previewSize.getHeight(), ImageFormat.YUV_420_888, 2);
cameraManager.openCamera(cameraName, new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice device) {
cameraDevice = device;
try {
startPreview();
} catch (CameraAccessException e) {
result.error("CameraAccess", e.getMessage(), null);
close();
return;
}
Map<String, Object> reply = new HashMap<>();
reply.put("textureId", flutterTexture.id());
reply.put("previewWidth", previewSize.getWidth());
reply.put("previewHeight", previewSize.getHeight());
result.success(reply);
}
@Override
public void onClosed(@NonNull CameraDevice camera) {
// rScanMessenger.sendCameraClosingEvent();
super.onClosed(camera);
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
close();
// rScanMessenger.send(DartMessenger.EventType.ERROR, "The camera was disconnected.");
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int errorCode) {
close();
// String errorDescription;
// switch (errorCode) {
// case ERROR_CAMERA_IN_USE:
// errorDescription = "The camera device is in use already.";
// break;
// case ERROR_MAX_CAMERAS_IN_USE:
// errorDescription = "Max cameras in use";
// break;
// case ERROR_CAMERA_DISABLED:
// errorDescription = "The camera device could not be opened due to a device policy.";
// break;
// case ERROR_CAMERA_DEVICE:
// errorDescription = "The camera device has encountered a fatal error";
// break;
// case ERROR_CAMERA_SERVICE:
// errorDescription = "The camera service has encountered a fatal error.";
// break;
// default:
// errorDescription = "Unknown camera error";
// }
// rScanMessenger.send(DartMessenger.EventType.ERROR, errorDescription);
}
}, null);
}
19
Source : EasyWayLocation.java
with Apache License 2.0
from prabhat1707
with Apache License 2.0
from prabhat1707
/**
* Stops the location updates when they aren't needed anymore so that battery can be saved
*/
@SuppressLint("MissingPermission")
public void endUpdates() {
if (locationCallback != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
}
19
Source : PhoneUtils.java
with BSD 2-Clause "Simplified" License
from pppscn
with BSD 2-Clause "Simplified" License
from pppscn
/**
* 读取电话号码
* <p>
* Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
* OR
* {@link android.Manifest.permission#READ_SMS}
* <p>
*
* @return 电话号码
*/
@SuppressLint("MissingPermission")
public static String getPhoneNumber() {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return null;
}
return tm != null ? tm.getLine1Number() : null;
} catch (Exception ignored) {
}
return null;
}
19
Source : NetStateUtil.java
with Apache License 2.0
from pop1234o
with Apache License 2.0
from pop1234o
/**
* 获取本机串号imei
*
* @param context
* @return
*/
@SuppressLint("MissingPermission")
public static String getIMEI(Activity context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 doreplacedentation
// for Activity#requestPermissions for more details.
return telephonyManager.getDeviceId();
// }
// return null;
}
19
Source : LocationChangeListener.java
with MIT License
from pinsondg
with MIT License
from pinsondg
@SuppressLint("MissingPermission")
@Override
public boolean onMyLocationButtonClick() {
fragment.ButtonClicked = true;
return fragment.ButtonClicked;
}
19
Source : SystemLocationCore.java
with BSD 3-Clause "New" or "Revised" License
from Parrot-Developers
with BSD 3-Clause "New" or "Revised" License
from Parrot-Developers
/**
* Starts monitoring location.
* <p>
* If all authorizations are granted, this method ensures monitoring is started using the appropriate provider(s)
* depending on restrictions currently imposed by {@link #mWifiEnforcementTokens} and {@link #mWifiDenialTokens}.
* <p>
* This method may stop and restart monitoring as appropriate to enforce such current restrictions. It does nothing
* in case monitoring is already starting and fulfills those restrictions.
*/
@SuppressLint("MissingPermission")
private void startMonitoring() {
if (!checkAuthorization()) {
return;
}
if ((mWifiEnforcementTokens.isEmpty() && !mWifiDenialTokens.isEmpty()) || mFusedLocationClient == null) {
if (mLocationType != LocationType.GPS_ONLY) {
stopMonitoring();
startGpsMonitoring();
}
} else if (mLocationType == LocationType.GPS_ONLY || mLocationType == LocationType.STOPPED) {
stopMonitoring();
startFusedMonitoring();
}
}
19
Source : AndroidGpsLocationClient.java
with BSD 2-Clause "Simplified" License
from onaio
with BSD 2-Clause "Simplified" License
from onaio
@SuppressLint("MissingPermission")
@Nullable
@Override
public Location getLastLocation() {
Location lastLocationFromProvider = locationManager.getLastKnownLocation(getProvider());
return lastLocationFromProvider != null && (lastLocation == null || lastLocationFromProvider.getTime() > lastLocation.getTime()) ? lastLocationFromProvider : lastLocation;
}
19
Source : PseudoContextWrapper.java
with Apache License 2.0
from oasisfeng
with Apache License 2.0
from oasisfeng
@Override
@SuppressLint("MissingPermission")
public void sendStickyBroadcast(Intent intent) {
mBase.sendStickyBroadcast(intent);
}
19
Source : PseudoContextWrapper.java
with Apache License 2.0
from oasisfeng
with Apache License 2.0
from oasisfeng
@Override
@SuppressLint("MissingPermission")
public void removeStickyBroadcast(Intent intent) {
mBase.removeStickyBroadcast(intent);
}
19
Source : ControllerV1_NativeCalls.java
with Apache License 2.0
from nu-art
with Apache License 2.0
from nu-art
@Override
@SuppressLint("MissingPermission")
public void onAllPermissionsGranted(int requestCode) {
callsModule.enable();
}
19
Source : ControllerV1_Contacts.java
with Apache License 2.0
from nu-art
with Apache License 2.0
from nu-art
@Override
@SuppressLint("MissingPermission")
public void onAllPermissionsGranted(int requestCode) {
logInfo("permissions granted");
recycler.invalidateDataModel();
}
19
Source : RequestLocationResultObservable.java
with Apache License 2.0
from niqo01
with Apache License 2.0
from niqo01
@SuppressLint("MissingPermission")
@Override
protected Task<Void> run(ObservableTaskCallback<LocationResult> callback) {
ResultCallback resultCallback = new ResultCallback(callback);
callback.setDisposeListener(() -> client.removeLocationUpdates(resultCallback));
return client.requestLocationUpdates(this.request, resultCallback, null);
}
19
Source : RequestLocationAvailabilityObservable.java
with Apache License 2.0
from niqo01
with Apache License 2.0
from niqo01
@SuppressLint("MissingPermission")
@Override
protected Task<Void> run(ObservableTaskCallback<LocationAvailability> callback) {
ResultCallback resultCallback = new ResultCallback(callback);
callback.setDisposeListener(() -> client.removeLocationUpdates(resultCallback));
return client.requestLocationUpdates(this.request, resultCallback, null);
}
19
Source : AndroidLocationProvider.java
with Apache License 2.0
from neXenio
with Apache License 2.0
from neXenio
@SuppressLint("MissingPermission")
public static void requestLastKnownLocation() {
final AndroidLocationProvider instance = getInstance();
if (!instance.hasLocationPermission()) {
return;
}
Log.d(TAG, "Requesting last known location");
instance.fusedLocationClient.getLastLocation().addOnSuccessListener(getInstance().activity, new OnSuccessListener<android.location.Location>() {
@Override
public void onSuccess(android.location.Location androidLocation) {
if (androidLocation != null) {
instance.onLocationUpdateReceived(androidLocation);
} else {
Log.w(TAG, "Unable to get last known location");
}
}
});
}
19
Source : ReplayRouteLocationEngine.java
with MIT License
from maplibre
with MIT License
from maplibre
@SuppressLint("MissingPermission")
@Override
@Nullable
public Location getLastLocation() {
return lastLocation;
}
19
Source : ReplayRouteLocationEngine.java
with MIT License
from maplibre
with MIT License
from maplibre
@SuppressLint("MissingPermission")
public void moveTo(Point point) {
Location lastLocation = getLastLocation();
if (lastLocation == null) {
return;
}
startRoute(point, lastLocation);
}
19
Source : MapboxFusedLocationEngineImpl.java
with MIT License
from mapbox
with MIT License
from mapbox
@SuppressLint("MissingPermission")
@Override
public void requestLocationUpdates(@NonNull LocationEngineRequest request, @NonNull LocationListener listener, @Nullable Looper looper) throws SecurityException {
super.requestLocationUpdates(request, listener, looper);
// Start network provider along with gps
if (shouldStartNetworkProvider(request.getPriority())) {
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, request.getInterval(), request.getDisplacement(), listener, looper);
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
}
}
19
Source : MapboxFusedLocationEngineImpl.java
with MIT License
from mapbox
with MIT License
from mapbox
@SuppressLint("MissingPermission")
@Override
public void requestLocationUpdates(@NonNull LocationEngineRequest request, @NonNull PendingIntent pendingIntent) throws SecurityException {
super.requestLocationUpdates(request, pendingIntent);
// Start network provider along with gps
if (shouldStartNetworkProvider(request.getPriority())) {
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, request.getInterval(), request.getDisplacement(), pendingIntent);
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
}
}
19
Source : MainActivity.java
with MIT License
from mapbox
with MIT License
from mapbox
@SuppressLint("MissingPermission")
@Override
public void onResume() {
super.onResume();
locationEngine.requestLocationUpdates(locationEngineRequest, locationEngineCallback, null);
}
19
Source : MainActivity.java
with MIT License
from mapbox
with MIT License
from mapbox
@SuppressLint("MissingPermission")
@Override
public void onPermissionResult(boolean granted) {
if (granted) {
mapboxTelemetry.enable();
}
}
19
Source : CrashReportHandle.java
with GNU General Public License v3.0
from liaoheng
with GNU General Public License v3.0
from liaoheng
/**
* @author liaoheng
* @version 2018-04-23 23:25
*/
@SuppressLint("MissingPermission")
public clreplaced CrashReportHandle {
private static boolean isFirebasereplacedytics;
public static void init(Context context) {
initFirebasereplacedytics();
if (check(context)) {
disable(context);
} else {
enable(context);
SentryAndroid.init(context, options -> options.setDebug(BuildConfig.DEBUG));
}
}
private static void initFirebasereplacedytics() {
try {
Clreplaced.forName("com.google.firebase.replacedytics.Firebasereplacedytics");
isFirebasereplacedytics = true;
} catch (ClreplacedNotFoundException ignored) {
isFirebasereplacedytics = false;
}
}
public static void enable(Context context) {
try {
if (isFirebasereplacedytics) {
Firebasereplacedytics.getInstance(context).setreplacedyticsCollectionEnabled(true);
}
} catch (Throwable ignored) {
}
}
public static void disable(Context context) {
try {
if (isFirebasereplacedytics) {
Firebasereplacedytics.getInstance(context).setreplacedyticsCollectionEnabled(false);
}
} catch (Throwable ignored) {
}
}
public static String loadFailed(Context context, String TAG, Throwable throwable) {
String error = context.getString(R.string.network_request_error);
if (throwable == null) {
L.alog().e(TAG, error);
} else {
if (throwable instanceof GlideException) {
GlideException e = (GlideException) throwable;
error = context.getString(R.string.load_image_error);
List<Throwable> causes = e.getCauses();
if (causes != null) {
for (Throwable t : causes) {
if (t instanceof SocketTimeoutException) {
error = context.getString(R.string.connection_timed_out);
break;
}
}
}
} else {
if (throwable instanceof SocketTimeoutException) {
error = context.getString(R.string.connection_timed_out);
}
}
L.alog().e(TAG, throwable);
collectException(context, TAG, throwable);
}
return error;
}
public static void saveWallpaper(Context context, String TAG, Throwable t) {
L.alog().e(TAG, t, "save wallpaper error");
if (BingWallpaperUtils.isEnableLogProvider(context)) {
LogDebugFileUtils.get().e(TAG, "Save wallpaper error: %s", t);
}
collectException(context, TAG, t);
}
public static void collectException(Context context, String TAG, Throwable t) {
collectException(context, TAG, null, t);
}
public static void collectException(Context context, String TAG, Config config, Throwable t) {
if (check(context)) {
return;
}
if (t instanceof LockSetWallpaperException) {
return;
}
if (t instanceof SSLHandshakeException) {
return;
}
if (t instanceof MalformedJsonException) {
return;
}
if (t instanceof ConnectException) {
return;
}
if (t instanceof SocketException) {
return;
}
if (t instanceof SocketTimeoutException) {
return;
}
if (t instanceof UnknownHostException) {
return;
}
try {
Sentry.setTag("tag", TAG);
Sentry.setExtra("Feedback info", BingWallpaperUtils.getSystemInfo(context));
if (config != null) {
Sentry.setExtra("Config", config.toString());
}
Sentry.captureException(t);
} catch (Exception ignored) {
}
}
private static boolean check(Context context) {
return !Settings.isCrashReport(context) || BuildConfig.DEBUG;
}
}
19
Source : RingtoneLoaderTask.java
with Apache License 2.0
from kevalpatel2106
with Apache License 2.0
from kevalpatel2106
@SafeVarargs
@SuppressLint("MissingPermission")
@Override
@NonNull
protected final HashMap<String, Uri> doInBackground(ArrayList<Integer>... voids) {
HashMap<String, Uri> ringTones = new HashMap<>();
for (int type : voids[0]) {
switch(type) {
case RingtonePickerDialog.Builder.TYPE_RINGTONE:
ringTones.putAll(RingtoneUtils.getRingTone(mApplication));
break;
case RingtonePickerDialog.Builder.TYPE_ALARM:
ringTones.putAll(RingtoneUtils.getAlarmTones(mApplication));
break;
case RingtonePickerDialog.Builder.TYPE_MUSIC:
ringTones.putAll(RingtoneUtils.getMusic(mApplication));
break;
case RingtonePickerDialog.Builder.TYPE_NOTIFICATION:
ringTones.putAll(RingtoneUtils.getNotificationTones(mApplication));
break;
default:
throw new IllegalArgumentException("Invalid ringtone type.");
}
}
return ringTones;
}
19
Source : GPSTracker.java
with MIT License
from JavaCafe01
with MIT License
from JavaCafe01
@SuppressLint("MissingPermission")
public Location getLocation() {
if (Utils.permissionsGranted(mContext)) {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled rip
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lareplacedude = location.getLareplacedude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lareplacedude = location.getLareplacedude();
longitude = location.getLongitude();
}
}
}
}
}
} else {
view.setText(R.string.perm_notgranted);
}
return location;
}
19
Source : Location.java
with MIT License
from IramML
with MIT License
from IramML
@SuppressLint("MissingPermission")
private void getLocation() {
validatePermissionsLocation();
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
19
Source : LensEnginePreview.java
with Apache License 2.0
from HMS-MLKit
with Apache License 2.0
from HMS-MLKit
@SuppressLint("MissingPermission")
private void startLensEngine() throws IOException {
if (this.startRequested) {
this.lensEngine.run();
this.startRequested = false;
}
}
19
Source : LensEngine.java
with Apache License 2.0
from HMS-MLKit
with Apache License 2.0
from HMS-MLKit
/**
* Turn on the camera and start sending preview frames to the replacedyzer for detection.
*
* @throws IOException IO Exception
*/
@SuppressLint("MissingPermission")
@RequiresPermission(Manifest.permission.CAMERA)
public synchronized LensEngine run() throws IOException {
if (this.camera != null) {
return this;
}
this.camera = this.createCamera();
this.surfaceTexture = new SurfaceTexture(this.TEXTURE_NAME);
this.camera.setPreviewTexture(this.surfaceTexture);
this.usingSurfaceTexture = true;
this.camera.startPreview();
return this;
}
19
Source : LensEngine.java
with Apache License 2.0
from HMS-MLKit
with Apache License 2.0
from HMS-MLKit
/**
* Manages the camera and allows UI updates on top of it (e.g. overlaying extra Graphics or
* displaying extra information). This receives preview frames from the camera at a specified rate,
* sending those frames to child clreplacedes' detectors / clreplacedifiers as fast as it is able to process.
*/
@SuppressLint("MissingPermission")
public clreplaced LensEngine {
private static final String TAG = "LensEngine";
protected Activity activity;
private Camera camera;
private Thread transactingThread;
private final FrameTransactingRunnable transactingRunnable;
private final Object transactorLock = new Object();
private ImageTransactor frameTransactor;
private CameraSelector selector;
private final Map<byte[], ByteBuffer> bytesToByteBuffer = new IdenreplacedyHashMap<>();
private GraphicOverlay overlay;
public LensEngine(Activity activity, CameraConfiguration configuration, GraphicOverlay graphicOverlay) {
this.activity = activity;
this.transactingRunnable = new FrameTransactingRunnable();
this.selector = new CameraSelector(activity, configuration);
this.overlay = graphicOverlay;
this.overlay.clear();
}
/**
* Stop the camera and release the resources of the camera and replacedyzer.
*/
public void release() {
synchronized (this.transactorLock) {
this.stop();
this.transactingRunnable.release();
if (this.frameTransactor != null) {
this.frameTransactor.stop();
this.frameTransactor = null;
}
}
}
/**
* Turn on the camera and start sending preview frames to the replacedyzer for detection.
*
* @throws IOException IO Exception
*/
@SuppressLint("MissingPermission")
@RequiresPermission(Manifest.permission.CAMERA)
public synchronized LensEngine run() throws IOException {
if (this.camera != null) {
return this;
}
this.camera = this.createCamera();
this.camera.startPreview();
this.initializeOverlay();
this.transactingThread = new Thread(this.transactingRunnable);
this.transactingRunnable.setActive(true);
this.transactingThread.start();
return this;
}
/**
* Take pictures.
*
* @param pictureCallback Callback function after obtaining photo data.
*/
public synchronized void takePicture(android.hardware.Camera.PictureCallback pictureCallback) {
synchronized (this.transactorLock) {
if (this.camera != null) {
this.camera.takePicture(null, null, null, pictureCallback);
}
}
}
public synchronized Camera getCamera() {
return this.camera;
}
private void initializeOverlay() {
if (this.overlay != null) {
int min;
int max;
if (this.frameTransactor.isFaceDetection()) {
min = CameraConfiguration.DEFAULT_HEIGHT;
max = CameraConfiguration.DEFAULT_WIDTH;
} else {
Size size = this.getPreviewSize();
min = Math.min(size.getWidth(), size.getHeight());
max = Math.max(size.getWidth(), size.getHeight());
}
if (this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
this.overlay.setCameraInfo(min, max, this.getFacing());
} else {
this.overlay.setCameraInfo(max, min, this.getFacing());
}
this.overlay.clear();
}
}
/**
* Get camera preview size.
*
* @return Size Size of camera preview.
*/
public Size getPreviewSize() {
return this.selector.getPreviewSize();
}
public int getFacing() {
return this.selector.getFacing();
}
/**
* Turn off the camera and stop transmitting frames to the replacedyzer.
*/
public synchronized void stop() {
this.transactingRunnable.setActive(false);
if (this.transactingThread != null) {
try {
this.transactingThread.join();
} catch (InterruptedException e) {
Log.d(LensEngine.TAG, "Frame transacting thread interrupted on release.");
}
this.transactingThread = null;
}
if (this.camera != null) {
this.camera.stopPreview();
this.camera.setPreviewCallbackWithBuffer(null);
try {
this.camera.setPreviewDisplay(null);
this.camera.setPreviewTexture(null);
} catch (Exception e) {
Log.e(LensEngine.TAG, "Failed to clear camera preview: " + e);
}
this.camera.release();
this.camera = null;
}
this.bytesToByteBuffer.clear();
}
@SuppressLint("InlinedApi")
private Camera createCamera() throws IOException {
Camera camera = this.selector.createCamera();
camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback());
camera.addCallbackBuffer(this.createPreviewBuffer(this.selector.getPreviewSize()));
camera.addCallbackBuffer(this.createPreviewBuffer(this.selector.getPreviewSize()));
camera.addCallbackBuffer(this.createPreviewBuffer(this.selector.getPreviewSize()));
camera.addCallbackBuffer(this.createPreviewBuffer(this.selector.getPreviewSize()));
return camera;
}
/**
* Create a buffer for the camera preview callback. The size of the buffer is based on the camera preview size and the camera image format.
*
* @param previewSize
* @return Image data from the camera
*/
@SuppressLint("InlinedApi")
private byte[] createPreviewBuffer(Size previewSize) {
int bitsPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.NV21);
long sizeInBits = (long) previewSize.getHeight() * previewSize.getWidth() * bitsPerPixel;
int bufferSize = (int) Math.ceil(sizeInBits / 8.0d) + 1;
byte[] byteArray = new byte[bufferSize];
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
if (!buffer.hasArray() || (buffer.array() != byteArray)) {
throw new IllegalStateException("Failed to create valid buffer for lensEngine.");
}
this.bytesToByteBuffer.put(byteArray, buffer);
return byteArray;
}
private clreplaced CameraPreviewCallback implements Camera.PreviewCallback {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
LensEngine.this.transactingRunnable.setNextFrame(data, camera);
}
}
public void setMachineLearningFrameTransactor(ImageTransactor transactor) {
synchronized (this.transactorLock) {
if (this.frameTransactor != null) {
this.frameTransactor.stop();
}
this.frameTransactor = transactor;
}
}
/**
* It is used to receive the frame captured by the camera and preplaced it to the replacedyzer.
*/
private clreplaced FrameTransactingRunnable implements Runnable {
private final Object lock = new Object();
private boolean active = true;
private ByteBuffer pendingFrameData;
FrameTransactingRunnable() {
}
/**
* Frees the transactor and can safely perform this operation only after the replacedociated thread has completed.
*/
@SuppressLint("replacedert")
void release() {
synchronized (this.lock) {
replacedert (LensEngine.this.transactingThread.getState() == State.TERMINATED);
}
}
void setActive(boolean active) {
synchronized (this.lock) {
this.active = active;
this.lock.notifyAll();
}
}
/**
* Sets the frame data received from the camera. Adds a previously unused frame buffer (if exit) back to the camera.
*/
void setNextFrame(byte[] data, Camera camera) {
synchronized (this.lock) {
if (this.pendingFrameData != null) {
camera.addCallbackBuffer(this.pendingFrameData.array());
this.pendingFrameData = null;
}
if (!LensEngine.this.bytesToByteBuffer.containsKey(data)) {
Log.d(LensEngine.TAG, "Skipping frame. Could not find ByteBuffer replacedociated with the image " + "data from the camera.");
return;
}
this.pendingFrameData = LensEngine.this.bytesToByteBuffer.get(data);
this.lock.notifyAll();
}
}
@SuppressLint("InlinedApi")
@SuppressWarnings("GuardedBy")
@Override
public void run() {
ByteBuffer data;
while (true) {
synchronized (this.lock) {
while (this.active && (this.pendingFrameData == null)) {
try {
// Waiting for next frame.
this.lock.wait();
} catch (InterruptedException e) {
Log.w(LensEngine.TAG, "Frame transacting loop terminated.", e);
return;
}
}
if (!this.active) {
this.pendingFrameData = null;
return;
}
data = this.pendingFrameData;
this.pendingFrameData = null;
}
try {
synchronized (LensEngine.this.transactorLock) {
Log.d(LensEngine.TAG, "Process an image");
LensEngine.this.frameTransactor.process(data, new FrameMetadata.Builder().setWidth(LensEngine.this.selector.getPreviewSize().getWidth()).setHeight(LensEngine.this.selector.getPreviewSize().getHeight()).setRotation(LensEngine.this.selector.getRotation()).setCameraFacing(LensEngine.this.selector.getFacing()).build(), LensEngine.this.overlay);
}
} catch (Throwable t) {
Log.e(LensEngine.TAG, "Exception thrown from receiver.", t);
} finally {
LensEngine.this.camera.addCallbackBuffer(data.array());
}
}
}
}
}
See More Examples