android.annotation.TargetApi Java Examples

The following examples show how to use android.annotation.TargetApi. 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: EmbedBottomSheet.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
public boolean checkInlinePermissions() {
    if (parentActivity == null) {
        return false;
    }
    if (Build.VERSION.SDK_INT < 23 || Settings.canDrawOverlays(parentActivity)) {
        return true;
    } else {
        new AlertDialog.Builder(parentActivity).setTitle(LocaleController.getString("AppName", R.string.AppName))
                .setMessage(LocaleController.getString("PermissionDrawAboveOtherApps", R.string.PermissionDrawAboveOtherApps))
                .setPositiveButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (parentActivity != null) {
                            parentActivity.startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + parentActivity.getPackageName())));
                        }
                    }
                }).show();
    }
    return false;
}
 
Example #2
Source File: KeyboardAwareLinearLayout.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(VERSION_CODES.LOLLIPOP)
private int getViewInset() {
  try {
    Field attachInfoField = View.class.getDeclaredField("mAttachInfo");
    attachInfoField.setAccessible(true);
    Object attachInfo = attachInfoField.get(this);
    if (attachInfo != null) {
      Field stableInsetsField = attachInfo.getClass().getDeclaredField("mStableInsets");
      stableInsetsField.setAccessible(true);
      Rect insets = (Rect)stableInsetsField.get(attachInfo);
      return insets.bottom;
    }
  } catch (NoSuchFieldException nsfe) {
    Log.w(TAG, "field reflection error when measuring view inset", nsfe);
  } catch (IllegalAccessException iae) {
    Log.w(TAG, "access reflection error when measuring view inset", iae);
  }
  return 0;
}
 
Example #3
Source File: NotificationChannels.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(26)
private static boolean updateExistingChannel(@NonNull NotificationManager notificationManager,
                                             @NonNull String channelId,
                                             @NonNull String newChannelId,
                                             @NonNull ChannelUpdater updater)
{
  NotificationChannel existingChannel = notificationManager.getNotificationChannel(channelId);
  if (existingChannel == null) {
    Log.w(TAG, "Tried to update a channel, but it didn't exist.");
    return false;
  }

  notificationManager.deleteNotificationChannel(existingChannel.getId());

  NotificationChannel newChannel = copyChannel(existingChannel, newChannelId);
  updater.update(newChannel);
  notificationManager.createNotificationChannel(newChannel);
  return true;
}
 
Example #4
Source File: NotificationChannels.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(26)
private static void onUpgrade(@NonNull NotificationManager notificationManager, int oldVersion, int newVersion) {
  Log.i(TAG, "Upgrading channels from " + oldVersion + " to " + newVersion);

  if (oldVersion < Version.MESSAGES_CATEGORY) {
    notificationManager.deleteNotificationChannel("messages");
    notificationManager.deleteNotificationChannel("calls");
    notificationManager.deleteNotificationChannel("locked_status");
    notificationManager.deleteNotificationChannel("backups");
    notificationManager.deleteNotificationChannel("other");
  }

  if (oldVersion < Version.CALLS_PRIORITY_BUMP) {
    notificationManager.deleteNotificationChannel("calls_v2");
  }
}
 
Example #5
Source File: LoginActivity.java    From Build-an-AI-Startup-with-PyTorch with MIT License 6 votes vote down vote up
private boolean mayRequestContacts() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                .setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.M)
                    public void onClick(View v) {
                        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                    }
                });
    } else {
        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
    }
    return false;
}
 
Example #6
Source File: Util.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether it may be possible to load the given URIs based on the network security
 * policy's cleartext traffic permissions.
 *
 * @param uris A list of URIs that will be loaded.
 * @return Whether it may be possible to load the given URIs.
 */
@TargetApi(24)
public static boolean checkCleartextTrafficPermitted(Uri... uris) {
  if (Util.SDK_INT < 24) {
    // We assume cleartext traffic is permitted.
    return true;
  }
  for (Uri uri : uris) {
    if ("http".equals(uri.getScheme())
        && !NetworkSecurityPolicy.getInstance()
            .isCleartextTrafficPermitted(Assertions.checkNotNull(uri.getHost()))) {
      // The security policy prevents cleartext traffic.
      return false;
    }
  }
  return true;
}
 
Example #7
Source File: DirectionalViewPager.java    From YCScrollPager with Apache License 2.0 6 votes vote down vote up
/**
 * 设置viewPager滑动动画持续时间
 * API>19
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public void setAnimationDuration(final int during){
    try {
        // viewPager平移动画事件
        Field mField = ViewPager.class.getDeclaredField("mScroller");
        mField.setAccessible(true);
        // 动画效果与ViewPager的一致
        Interpolator interpolator = new Interpolator() {
            @Override
            public float getInterpolation(float t) {
                t -= 1.0f;
                return t * t * t * t * t + 1.0f;
            }
        };
        FixedSpeedScroller scroller = new FixedSpeedScroller(getContext(),
                interpolator, mRecentTouchTime);
        scroller.setDuration(during);
        mField.set(this, scroller);
    } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
        e.printStackTrace();
    }
}
 
Example #8
Source File: MeizuUtils.java    From SoloPi with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 19) {
        AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            Class clazz = AppOpsManager.class;
            Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
            return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } else {
        Log.e(TAG, "Below API 19 cannot invoke!");
    }
    return false;
}
 
Example #9
Source File: LoginActivity.java    From Watch-Me-Build-a-Finance-Startup with MIT License 6 votes vote down vote up
private boolean mayRequestContacts() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                .setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.M)
                    public void onClick(View v) {
                        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                    }
                });
    } else {
        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
    }
    return false;
}
 
Example #10
Source File: TrackSelectionParameters.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@TargetApi(19)
private void setPreferredTextLanguageAndRoleFlagsToCaptioningManagerSettingsV19(
    Context context) {
  if (Util.SDK_INT < 23 && Looper.myLooper() == null) {
    // Android platform bug (pre-Marshmallow) that causes RuntimeExceptions when
    // CaptioningService is instantiated from a non-Looper thread. See [internal: b/143779904].
    return;
  }
  CaptioningManager captioningManager =
      (CaptioningManager) context.getSystemService(Context.CAPTIONING_SERVICE);
  if (captioningManager == null || !captioningManager.isEnabled()) {
    return;
  }
  preferredTextRoleFlags = C.ROLE_FLAG_CAPTION | C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND;
  Locale preferredLocale = captioningManager.getLocale();
  if (preferredLocale != null) {
    preferredTextLanguage = Util.getLocaleLanguageTag(preferredLocale);
  }
}
 
Example #11
Source File: QikuUtils.java    From SoloPi with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean checkOp(Context context, int op) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 19) {
        AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            Class clazz = AppOpsManager.class;
            Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
            return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } else {
        Log.e("", "Below API 19 cannot invoke!");
    }
    return false;
}
 
Example #12
Source File: AppNetworkMgr.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 判断当前网络的具体类型是否是EHRPD
 *
 * @param context 上下文
 * @return false:当前网络的具体类型是否是EHRPD。false:当前没有网络连接或者具体类型不是EHRPD
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static boolean isEHRPDBySubtype(Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        return false;
    } else {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_EHRPD;
    }
}
 
Example #13
Source File: HookLoader.java    From QNotified with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 根据包名构建目标Context,并调用getPackageCodePath()来定位apk
 *
 * @param context           context参数
 * @param modulePackageName 当前模块包名
 * @return return apk file
 */
@TargetApi(Build.VERSION_CODES.FROYO)
private File findApkFile(Context context, String modulePackageName) {
    if (context == null) {
        return null;
    }
    try {
        Context moudleContext = context.createPackageContext(modulePackageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
        String apkPath = moudleContext.getPackageCodePath();
        return new File(apkPath);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #14
Source File: MainActivity.java    From VehicleInfoOCR with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(19)
public void doFade() {
    if(canDoTransitions && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // Get the root view and create a transition
        // Start recording changes to the view hierarchy
        TransitionManager.beginDelayedTransition(superContainer, mFade);
    }
}
 
Example #15
Source File: CallMultiActivity.java    From webrtc_android with MIT License 5 votes vote down vote up
@TargetApi(19)
private static int getSystemUiVisibility() {
    int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        flags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
    }
    return flags;
}
 
Example #16
Source File: MainActivity.java    From WebSocketClient with Apache License 2.0 5 votes vote down vote up
/**
 * 获取通知权限,监测是否开启了系统通知
 *
 * @param context
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private boolean isNotificationEnabled(Context context) {

    String CHECK_OP_NO_THROW = "checkOpNoThrow";
    String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    ApplicationInfo appInfo = context.getApplicationInfo();
    String pkg = context.getApplicationContext().getPackageName();
    int uid = appInfo.uid;

    Class appOpsClass = null;
    try {
        appOpsClass = Class.forName(AppOpsManager.class.getName());
        Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                String.class);
        Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

        int value = (Integer) opPostNotificationValue.get(Integer.class);
        return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #17
Source File: AndroidChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@GuardedBy("lock")
private void configureNetworkMonitoring() {
  // Android N added the registerDefaultNetworkCallback API to listen to changes in the device's
  // default network. For earlier Android API levels, use the BroadcastReceiver API.
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && connectivityManager != null) {
    final DefaultNetworkCallback defaultNetworkCallback = new DefaultNetworkCallback();
    connectivityManager.registerDefaultNetworkCallback(defaultNetworkCallback);
    unregisterRunnable =
        new Runnable() {
          @TargetApi(Build.VERSION_CODES.LOLLIPOP)
          @Override
          public void run() {
            connectivityManager.unregisterNetworkCallback(defaultNetworkCallback);
          }
        };
  } else {
    final NetworkReceiver networkReceiver = new NetworkReceiver();
    IntentFilter networkIntentFilter =
        new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    context.registerReceiver(networkReceiver, networkIntentFilter);
    unregisterRunnable =
        new Runnable() {
          @TargetApi(Build.VERSION_CODES.LOLLIPOP)
          @Override
          public void run() {
            context.unregisterReceiver(networkReceiver);
          }
        };
  }
}
 
Example #18
Source File: StatusBarUtil.java    From FimiX8-RE with MIT License 5 votes vote down vote up
@TargetApi(19)
private static void transparentStatusBar(Activity activity) {
    if (VERSION.SDK_INT >= 21) {
        activity.getWindow().addFlags(Integer.MIN_VALUE);
        activity.getWindow().clearFlags(NTLMConstants.FLAG_UNIDENTIFIED_9);
        activity.getWindow().addFlags(NTLMConstants.FLAG_UNIDENTIFIED_10);
        activity.getWindow().setStatusBarColor(0);
        return;
    }
    activity.getWindow().addFlags(NTLMConstants.FLAG_UNIDENTIFIED_9);
}
 
Example #19
Source File: KeyboardUtils.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Unregister soft input changed listener.
 *
 * @param activity The activity.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void unregisterSoftInputChangedListener(final Activity activity) {
    final View contentView = activity.findViewById(android.R.id.content);
    contentView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
    onSoftInputChangedListener = null;
    onGlobalLayoutListener = null;
}
 
Example #20
Source File: VoIPActivity.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == 101) {
        if(VoIPService.getSharedInstance()==null){
            finish();
            return;
        }
        if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            VoIPService.getSharedInstance().acceptIncomingCall();
            callAccepted();
        } else {
            if(!shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)){
                VoIPService.getSharedInstance().declineIncomingCall();
                VoIPHelper.permissionDenied(this, new Runnable(){
                    @Override
                    public void run(){
                        finish();
                    }
                });
                return;
            }
            acceptSwipe.reset();
        }
    }

}
 
Example #21
Source File: GestureListener.java    From input-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a human-readable string listing all the stylus buttons that were pressed when the
 * input MotionEvent occurred.
 */
@TargetApi(21)
private static String getButtonsPressed(MotionEvent e){
    String buttons = "";

    if(e.isButtonPressed(MotionEvent.BUTTON_PRIMARY)){
        buttons += " primary";
    }

    if(e.isButtonPressed(MotionEvent.BUTTON_SECONDARY)){
        buttons += " secondary";
    }

    if(e.isButtonPressed(MotionEvent.BUTTON_TERTIARY)){
        buttons += " tertiary";
    }

    if(e.isButtonPressed(MotionEvent.BUTTON_BACK)){
        buttons += " back";
    }

    if(e.isButtonPressed(MotionEvent.BUTTON_FORWARD)){
        buttons += " forward";
    }

    if (buttons.equals("")){
        buttons = "none";
    }

    return buttons;
}
 
Example #22
Source File: ThemeActivity.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void showPermissionAlert(boolean byButton) {
    if (getParentActivity() == null) {
        return;
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
    if (byButton) {
        builder.setMessage(LocaleController.getString("PermissionNoLocationPosition", R.string.PermissionNoLocationPosition));
    } else {
        builder.setMessage(LocaleController.getString("PermissionNoLocation", R.string.PermissionNoLocation));
    }
    builder.setNegativeButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), new DialogInterface.OnClickListener() {
        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (getParentActivity() == null) {
                return;
            }
            try {
                Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + ApplicationLoader.applicationContext.getPackageName()));
                getParentActivity().startActivity(intent);
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
    });
    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
    showDialog(builder.create());
}
 
Example #23
Source File: PopWebViewSecurity.java    From PoupoLayer with MIT License 5 votes vote down vote up
@TargetApi(11)
public static final void removeJavascriptInterfaces(WebView webView) {
    try {
        if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 17) {
            webView.removeJavascriptInterface("searchBoxJavaBridge_");
            webView.removeJavascriptInterface("accessibility");
            webView.removeJavascriptInterface("accessibilityTraversal");
        }
    } catch (Throwable tr) {
        tr.printStackTrace();
    }
}
 
Example #24
Source File: SecurePreferences.java    From FimiX8-RE with MIT License 5 votes vote down vote up
@TargetApi(11)
public android.content.SharedPreferences.Editor putStringSet(String key, Set<String> values) {
    Set<String> encryptedValues = new HashSet(values.size());
    for (String value : values) {
        encryptedValues.add(SecurePreferences.this.encrypt(value));
    }
    this.mEditor.putStringSet(SecurePreferences.hashPrefKey(key), encryptedValues);
    return this;
}
 
Example #25
Source File: SystemWebChromeClient.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(8)
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
    if (consoleMessage.message() != null)
        LOG.d(LOG_TAG, "%s: Line %d : %s" , consoleMessage.sourceId() , consoleMessage.lineNumber(), consoleMessage.message());
     return super.onConsoleMessage(consoleMessage);
}
 
Example #26
Source File: SecurePreferences.java    From FimiX8-RE with MIT License 5 votes vote down vote up
@TargetApi(9)
public void apply() {
    if (VERSION.SDK_INT >= 9) {
        this.mEditor.apply();
    } else {
        commit();
    }
}
 
Example #27
Source File: SimpleExoPlayer.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the {@link PlaybackParams} governing audio playback.
 *
 * @deprecated Use {@link #setPlaybackParameters(PlaybackParameters)}.
 * @param params The {@link PlaybackParams}, or null to clear any previously set parameters.
 */
@Deprecated
@TargetApi(23)
public void setPlaybackParams(@Nullable PlaybackParams params) {
  PlaybackParameters playbackParameters;
  if (params != null) {
    params.allowDefaults();
    playbackParameters = new PlaybackParameters(params.getSpeed(), params.getPitch());
  } else {
    playbackParameters = null;
  }
  setPlaybackParameters(playbackParameters);
}
 
Example #28
Source File: MessageListItem.java    From zom-android-matrix with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.N)
public Locale getCurrentLocale(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
        return getResources().getConfiguration().getLocales().get(0);
    } else{
        //noinspection deprecation
        return getResources().getConfiguration().locale;
    }
}
 
Example #29
Source File: SystemWebViewEngine.java    From xmall with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private void enableRemoteDebugging() {
    try {
        WebView.setWebContentsDebuggingEnabled(true);
    } catch (IllegalArgumentException e) {
        LOG.d(TAG, "You have one job! To turn on Remote Web Debugging! YOU HAVE FAILED! ");
        e.printStackTrace();
    }
}
 
Example #30
Source File: RequestManagerRetriever.java    From giffun with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public RequestManager get(Activity activity) {
    if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        android.app.FragmentManager fm = activity.getFragmentManager();
        return fragmentGet(activity, fm);
    }
}