Java Code Examples for android.annotation.TargetApi

The following are top voted examples for showing how to use android.annotation.TargetApi. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DisplayingBitmaps   File: ImageCache.java   Source Code and License 8 votes vote down vote up
/**
 * Get the size in bytes of a bitmap in a BitmapDrawable. Note that from Android 4.4 (KitKat)
 * onward this returns the allocated memory size of the bitmap which can be larger than the
 * actual bitmap data byte count (in the case it was re-used).
 *
 * @param value
 * @return size in bytes
 */
@TargetApi(VERSION_CODES.KITKAT)
public static int getBitmapSize(BitmapDrawable value) {
    Bitmap bitmap = value.getBitmap();

    // From KitKat onward use getAllocationByteCount() as allocated bytes can potentially be
    // larger than bitmap byte count.
    if (Utils.hasKitKat()) {
        return bitmap.getAllocationByteCount();
    }

    if (Utils.hasHoneycombMR1()) {
        return bitmap.getByteCount();
    }

    // Pre HC-MR1
    return bitmap.getRowBytes() * bitmap.getHeight();
}
 
Example 2
Project: ceji_android   File: PlatformUtil.java   Source Code and License 8 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static <A, B, C> void executeTask(AsyncTask<A, B, C> task, A... params ) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    }
    else {
        task.execute(params);
    }
}
 
Example 3
Project: QMUI_Android   File: QMUIDeviceHelper.java   Source Code and License 7 votes vote down vote up
@TargetApi(19)
private static boolean checkOp(Context context, int op) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= Build.VERSION_CODES.KITKAT) {
        AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
            int property = (Integer) method.invoke(manager, op,
                    Binder.getCallingUid(), context.getPackageName());
            return AppOpsManager.MODE_ALLOWED == property;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}
 
Example 4
Project: Android-Practice   File: ImageGridFragment.java   Source Code and License 6 votes vote down vote up
@TargetApi(VERSION_CODES.JELLY_BEAN)
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    final Intent i = new Intent(getActivity(), ImageDetailActivity.class);
    i.putExtra(ImageDetailActivity.EXTRA_IMAGE, (int) id);
    if (Utils.hasJellyBean()) {
        // makeThumbnailScaleUpAnimation() looks kind of ugly here as the loading spinner may
        // show plus the thumbnail image in GridView is cropped. so using
        // makeScaleUpAnimation() instead.
        ActivityOptions options =
                ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight());
        getActivity().startActivity(i, options.toBundle());
    } else {
        startActivity(i);
    }
}
 
Example 5
Project: CoolClock   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.tv_setting:
            Intent intent = new Intent(this, SettingActivity.class);
            startActivityForResult(intent, SETTING_REQUEST_CODE);
            tv_setting.setVisibility(View.GONE);
            break;
        case R.id.rel_main:
            localWakeLock.isHeld();
            switchMode(MODE_SETTING_OTHER);
            break;
        case R.id.tv_time:
            switchMode(MODE_SETTING_OTHER);
            break;
    }
}
 
Example 6
Project: stynico   File: MD5_jni.java   Source Code and License 6 votes vote down vote up
/** 打开通知栏消息 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void openNotify(AccessibilityEvent event)
{
	if (event.getParcelableData() == null || !(event.getParcelableData() instanceof Notification))
	{
		return;
	}
	// 将微信的通知栏消息打开
	Notification notification = (Notification) event.getParcelableData();
	PendingIntent pendingIntent = notification.contentIntent;
	try
	{
		pendingIntent.send();
	} catch (PendingIntent.CanceledException e)
	{
		e.printStackTrace();
	}
}
 
Example 7
Project: HeadlineNews   File: SDCardUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 获取SD卡信息
 *
 * @return SDCardInfo
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static String getSDCardInfo() {
    if (!isSDCardEnable()) return null;
    SDCardInfo sd = new SDCardInfo();
    sd.isExist = true;
    StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getPath());
    sd.totalBlocks = sf.getBlockCountLong();
    sd.blockByteSize = sf.getBlockSizeLong();
    sd.availableBlocks = sf.getAvailableBlocksLong();
    sd.availableBytes = sf.getAvailableBytes();
    sd.freeBlocks = sf.getFreeBlocksLong();
    sd.freeBytes = sf.getFreeBytes();
    sd.totalBytes = sf.getTotalBytes();
    return sd.toString();
}
 
Example 8
Project: JewelryUI   File: JazzyViewPager.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void manageLayer(View v, boolean enableHardware) {
	if (!API_11) return;
	int layerType = enableHardware ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE;
	if (layerType != v.getLayerType())
		v.setLayerType(layerType, null);
}
 
Example 9
Project: permissionUtil   File: PermissionUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 检查单个权限是否被允许,(当应用第一次安装的时候,不会有rational的值,此时返回均是denied)
 *
 * @param permission The name of the permission being checked.
 * @return PermissionUtil.PERMISSION_GRANTED / PERMISSION_DENIED / PERMISSION_RATIONAL or {@code null}
 *         if context is not instanceof Activity.
 */
@TargetApi(Build.VERSION_CODES.M)
public int checkSinglePermission(String permission) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return PERMISSION_GRANTED;
    }

    if (mActivity == null) {
        mActivity = getTopActivity();
    }

    if (mActivity != null) {
        if (mActivity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
            return PERMISSION_GRANTED;
        } else {
            if (mActivity.shouldShowRequestPermissionRationale(permission)) {
                return PERMISSION_RATIONAL;
            } else {
                return PERMISSION_DENIED;
            }
        }
    } else {
        Log.e(TAG, "TopActivity not find");
        return -1;
    }
}
 
Example 10
Project: GitHub   File: SystemBarTintManager.java   Source Code and License 6 votes vote down vote up
@TargetApi(14)
private boolean hasNavBar(Context context) {
    Resources res = context.getResources();
    int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
    if (resourceId != 0) {
        boolean hasNav = res.getBoolean(resourceId);
        // check override flag (see static block)
        if ("1".equals(sNavBarOverride)) {
            hasNav = false;
        } else if ("0".equals(sNavBarOverride)) {
            hasNav = true;
        }
        return hasNav;
    } else { // fallback
        return !ViewConfiguration.get(context).hasPermanentMenuKey();
    }
}
 
Example 11
Project: OSchina_resources_android   File: ImageGalleryActivity.java   Source Code and License 6 votes vote down vote up
@SuppressLint("ObsoleteSdkInt")
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
@SuppressWarnings("deprecation")
private synchronized Point getDisplayDimens() {
    if (mDisplayDimens != null) {
        return mDisplayDimens;
    }
    Point displayDimens;
    WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    assert windowManager != null;
    Display display = windowManager.getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        displayDimens = new Point();
        display.getSize(displayDimens);
    } else {
        displayDimens = new Point(display.getWidth(), display.getHeight());
    }

    // In this we can only get 85% width and 60% height
    //displayDimens.y = (int) (displayDimens.y * 0.60f);
    //displayDimens.x = (int) (displayDimens.x * 0.85f);

    mDisplayDimens = displayDimens;
    return mDisplayDimens;
}
 
Example 12
Project: WebPager   File: PagerWebViewClient.java   Source Code and License 6 votes vote down vote up
@TargetApi(24)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
	Log.d(TAG, "shouldOverrideUrlLoading() called with: request = [" + request.getUrl() + "]");
	if (pager.webviewClient != null) {
		if (pager.webviewClient.shouldOverrideUrlLoading(view, request)) {
			return true;
		}
	}

	if (handleUrlLoading(view, request.getUrl().toString())) {
		return true;
	}

	return super.shouldOverrideUrlLoading(view, request);
}
 
Example 13
Project: MobileAppForPatient   File: AppUtility.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param context
 * @param title
 * @param message
 * @param isCritical
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void sendNotification(Context context, String title, String message, boolean isCritical) {
    Intent broadCastIntent = new Intent(context, DashboardActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), broadCastIntent, 0);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.app_icon)
            .setContentIntent(pIntent)
            .setAutoCancel(true).setContentTitle("" + title);
    if (!TextUtils.isEmpty(message)) {
        mBuilder.setContentText(message);
    }
    if (isCritical) {
        mBuilder.setVibrate(new long[]{100, 250}).setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setColor(Color.RED);
    } else {
        mBuilder.setColor(Color.GREEN);
    }
    mBuilder.setContentIntent(pIntent);
    mNotificationManager.notify(0, mBuilder.build());
}
 
Example 14
Project: Saiy-PS   File: SaiyTextToSpeech.java   Source Code and License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private SaiyVoice getEngineDefaultSaiyVoice() {

    final Voice voice = getDefaultVoice();

    if (voice != null) {
        final SaiyVoice saiyVoice = new SaiyVoice(voice);
        saiyVoice.setEngine(getInitialisedEngine());
        saiyVoice.setGender(saiyVoice.getName());

        if (DEBUG) {
            MyLog.i(CLS_NAME, "getEngineDefaultSaiyVoice: setting Gender: " + saiyVoice.getGender().name());
        }

        return saiyVoice;
    } else {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "getEngineDefaultSaiyVoice: voice null");
        }
        return null;
    }
}
 
Example 15
Project: PreviewSeekBar   File: CustomTimeBar.java   Source Code and License 6 votes vote down vote up
@TargetApi(21)
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
    super.onInitializeAccessibilityNodeInfo(info);
    info.setClassName(com.google.android.exoplayer2.ui.DefaultTimeBar.class.getCanonicalName());
    info.setContentDescription(getProgressText());
    if (duration <= 0) {
        return;
    }
    if (Util.SDK_INT >= 21) {
        info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD);
        info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD);
    } else if (Util.SDK_INT >= 16) {
        info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
    }
}
 
Example 16
Project: ChatExchange-old   File: FloatingActionButton.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the shadow color and radius to mimic the native elevation.
 *
 * <p><b>API 21+</b>: Sets the native elevation of this view, in pixels. Updates margins to
 * make the view hold its position in layout across different platform versions.</p>
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void setElevationCompat(float elevation) {
    mShadowColor = 0x26000000;
    mShadowRadius = Math.round(elevation / 2);
    mShadowXOffset = 0;
    mShadowYOffset = Math.round(mFabSize == SIZE_NORMAL ? elevation : elevation / 2);

    if (Util.hasLollipop()) {
        super.setElevation(elevation);
        mUsingElevationCompat = true;
        mShowShadow = false;
        updateBackground();

        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        if (layoutParams != null) {
            setLayoutParams(layoutParams);
        }
    } else {
        mShowShadow = true;
        updateBackground();
    }
}
 
Example 17
Project: android-chessclock   File: TimePickerView.java   Source Code and License 6 votes vote down vote up
/**
 * Set the reference of seconds picker, its digit format and register value change listener.
 *
 * @param pickerVisible if false, removes the spinner widget.
 */
@TargetApi(11)
protected void setupSecondPicker(boolean pickerVisible) {
    mSecondPicker = (NumberPicker) findViewById(R.id.seconds);
    if (pickerVisible) {
        mSecondPicker.setMinValue(0);
        mSecondPicker.setMaxValue(59);
        mSecondPicker.setFormatter(TWO_DIGIT_FORMATTER);
        mSecondPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                mCurrentSecond = newVal;
            }
        });
    } else {
        mHourPicker.setVisibility(View.GONE);
    }
}
 
Example 18
Project: Android-Practice   File: ImageCache.java   Source Code and License 6 votes vote down vote up
/**
 * @param candidate - Bitmap to check
 * @param targetOptions - Options that have the out* value populated
 * @return true if <code>candidate</code> can be used for inBitmap re-use with
 *      <code>targetOptions</code>
 */
@TargetApi(VERSION_CODES.KITKAT)
private static boolean canUseForInBitmap(
        Bitmap candidate, BitmapFactory.Options targetOptions) {
    //BEGIN_INCLUDE(can_use_for_inbitmap)
    if (!Utils.hasKitKat()) {
        // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
        return candidate.getWidth() == targetOptions.outWidth
                && candidate.getHeight() == targetOptions.outHeight
                && targetOptions.inSampleSize == 1;
    }

    // From Android 4.4 (KitKat) onward we can re-use if the byte size of the new bitmap
    // is smaller than the reusable bitmap candidate allocation byte count.
    int width = targetOptions.outWidth / targetOptions.inSampleSize;
    int height = targetOptions.outHeight / targetOptions.inSampleSize;
    int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
    return byteCount <= candidate.getAllocationByteCount();
    //END_INCLUDE(can_use_for_inbitmap)
}
 
Example 19
Project: FlickLauncher   File: LauncherAppWidgetProviderInfo.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public Drawable getIcon(Context context, IconCache cache) {
    if (isCustomWidget) {
        return cache.getFullResIcon(provider.getPackageName(), icon);
    }
    return super.loadIcon(context,
            LauncherAppState.getInstance().getInvariantDeviceProfile().fillResIconDpi);
}
 
Example 20
Project: ESDLA-Quiz   File: GameActivity.java   Source Code and License 5 votes vote down vote up
/**
 * SoundPool creator with the new constructor available since API 21
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void createNewSoundPool() {
    Log.d(this.getClass().getSimpleName(), "New soundpool constructor");

    AudioAttributes attr = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();

    soundPool = new SoundPool.Builder().setMaxStreams(1).setAudioAttributes(attr).build();
    correctSound = soundPool.load(this, R.raw.correct_sound, 1);
    wrongSound = soundPool.load(this, R.raw.wrong_sound, 1);
}
 
Example 21
Project: DateTimePicker   File: TextInputTimePickerView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TextInputTimePickerView(Context context, AttributeSet attrs, int defStyle,
                               int defStyleRes) {
    super(context, attrs, defStyle, defStyleRes);

    attrHandler(context, attrs, defStyle, defStyleRes);
}
 
Example 22
Project: ChatShala   File: Utility.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
    {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    }
    else {
        return true;
    }
}
 
Example 23
Project: x5webview-cordova-plugin   File: X5CookieManager.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public X5CookieManager(WebView webview) {
        webView = webview;
        cookieManager = CookieManager.getInstance();

        //REALLY? Nobody has seen this UNTIL NOW?
//        cookieManager.setAcceptFileSchemeCookies(true);
        cookieManager.setAcceptCookie(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setAcceptThirdPartyCookies(webView, true);
        }
    }
 
Example 24
Project: libRtmp   File: AndroidUntil.java   Source Code and License 5 votes vote down vote up
@TargetApi(18)
public static AudioRecord getAudioRecord() {
    int frequency = Options.getInstance().audio.frequency;
    int audioEncoding = Options.getInstance().audio.encoding;
    int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    if(Options.getInstance().audio.channelCount == 2) {
        channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
    }
    int audioSource = MediaRecorder.AudioSource.MIC;
    if(Options.getInstance().audio.aec) {
        audioSource = MediaRecorder.AudioSource.VOICE_COMMUNICATION;
    }
    return new AudioRecord(audioSource, frequency,
            channelConfiguration, audioEncoding, getRecordBufferSize());
}
 
Example 25
Project: StackCardsView   File: ChoreographerCompat.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
Choreographer.FrameCallback getFrameCallback() {
  if (mFrameCallback == null) {
    mFrameCallback = new Choreographer.FrameCallback() {
      @Override
      public void doFrame(long frameTimeNanos) {
        FrameCallback.this.doFrame(frameTimeNanos);
      }
    };
  }
  return mFrameCallback;
}
 
Example 26
Project: cwac-document   File: DocumentFileCompat.java   Source Code and License 5 votes vote down vote up
/**
 * Create a {@link DocumentFileCompat} representing the document tree rooted at
 * the given {@link Uri}. This is only useful on devices running
 * {@link android.os.Build.VERSION_CODES#LOLLIPOP} or later, and will return
 * {@code null} when called on earlier platform versions.
 *
 * @param treeUri the {@link Intent#getData()} from a successful
 *            {@link Intent#ACTION_OPEN_DOCUMENT_TREE} request.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static DocumentFileCompat fromTreeUri(Context context, Uri treeUri) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 21) {
        return new TreeDocumentFile(null, context,
                DocumentsContractApi21.prepareTreeUri(treeUri));
    } else {
        return null;
    }
}
 
Example 27
Project: simple-share-android   File: SystemBarTintManager.java   Source Code and License 5 votes vote down vote up
/**
 * Apply the specified alpha to the system navigation bar.
 *
 * @param alpha The alpha to use
 */
@TargetApi(11)
public void setNavigationBarAlpha(float alpha) {
    if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mNavBarTintView.setAlpha(alpha);
    }
}
 
Example 28
Project: FastAndroid   File: SingleCallActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(23)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
            boolean permissionGranted;
            if (mediaType == RongCallCommon.CallMediaType.AUDIO) {
                permissionGranted = PermissionCheckUtil.checkPermissions(this, AUDIO_CALL_PERMISSIONS);
            } else {
                permissionGranted = PermissionCheckUtil.checkPermissions(this, VIDEO_CALL_PERMISSIONS);

            }
            if (permissionGranted) {
                if (startForCheckPermissions) {
                    startForCheckPermissions = false;
                    RongCallClient.getInstance().onPermissionGranted();
                } else {
                    setupIntent();
                }
            } else {
                if (startForCheckPermissions) {
                    startForCheckPermissions = false;
                    RongCallClient.getInstance().onPermissionDenied();
                } else {
                    finish();
                }
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
 
Example 29
Project: Spyglass   File: ThrowsThrowable.java   Source Code and License 5 votes vote down vote up
@RequiresApi(21)
@TargetApi(21)
public ThrowsThrowable(
		final Context context,
		final AttributeSet attrs,
		final int defStyleAttr,
		final int defStyleRes) {

	super(context, attrs, defStyleAttr, defStyleRes);
	init(attrs, defStyleAttr, defStyleRes);
}
 
Example 30
Project: RetroMusicPlayer   File: TaggerUtils.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getExtSdCardFolder(final File file) {
    String[] extSdPaths = getExtSdCardPaths();
    try {
        for (String extSdPath : extSdPaths) {
            if (file.getCanonicalPath().startsWith(extSdPath)) {
                return extSdPath;
            }
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}
 
Example 31
Project: rongyunDemo   File: ProgressWheel.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void setAnimationEnabled() {
    int currentApiVersion = Build.VERSION.SDK_INT;

    float animationValue;
    if (currentApiVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        animationValue = Settings.Global.getFloat(getContext().getContentResolver(),
                         Settings.Global.ANIMATOR_DURATION_SCALE, 1);
    } else {
        animationValue = Settings.System.getFloat(getContext().getContentResolver(),
                         Settings.System.ANIMATOR_DURATION_SCALE, 1);
    }

    shouldAnimate = animationValue != 0;
}
 
Example 32
Project: HandyGridView   File: HandyGridView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
public void scrollListBy(int deltaY) {
    if (SdkVerUtils.isAbove19()) {
        super.scrollListBy(deltaY);
    } else {
        ReflectUtil.invokeMethod(this, "trackMotionScroll", new Object[]{-deltaY, -deltaY}, new Class[]{int.class, int.class});
    }
}
 
Example 33
Project: MaterialOCR   File: EglUtils.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private static int getMaxTextureEgl14() {
    EGLDisplay dpy = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
    int[] vers = new int[2];
    EGL14.eglInitialize(dpy, vers, 0, vers, 1);

    int[] configAttr = {
            EGL14.EGL_COLOR_BUFFER_TYPE, EGL14.EGL_RGB_BUFFER,
            EGL14.EGL_LEVEL, 0,
            EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
            EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT,
            EGL14.EGL_NONE
    };
    EGLConfig[] configs = new EGLConfig[1];
    int[] numConfig = new int[1];
    EGL14.eglChooseConfig(dpy, configAttr, 0,
            configs, 0, 1, numConfig, 0);
    if (numConfig[0] == 0) {
        return 0;
    }
    EGLConfig config = configs[0];

    int[] surfAttr = {
            EGL14.EGL_WIDTH, 64,
            EGL14.EGL_HEIGHT, 64,
            EGL14.EGL_NONE
    };
    EGLSurface surf = EGL14.eglCreatePbufferSurface(dpy, config, surfAttr, 0);

    int[] ctxAttrib = {
            EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
            EGL14.EGL_NONE
    };
    EGLContext ctx = EGL14.eglCreateContext(dpy, config, EGL14.EGL_NO_CONTEXT, ctxAttrib, 0);

    EGL14.eglMakeCurrent(dpy, surf, surf, ctx);

    int[] maxSize = new int[1];
    GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxSize, 0);

    EGL14.eglMakeCurrent(dpy, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE,
            EGL14.EGL_NO_CONTEXT);
    EGL14.eglDestroySurface(dpy, surf);
    EGL14.eglDestroyContext(dpy, ctx);
    EGL14.eglTerminate(dpy);

    return maxSize[0];
}
 
Example 34
Project: bigjpg-app   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(23)
private boolean checkPermissions() {
    if (C.SDK < 23 || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        return true;
    }

    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    return false;
}
 
Example 35
Project: JD-Test   File: PercentFrameLayout.java   Source Code and License 5 votes vote down vote up
@RequiresApi(19)
@TargetApi(19)
public LayoutParams(LayoutParams source) {
    // The copy constructor used here is only supported on API 19+.
    this((FrameLayout.LayoutParams) source);
    mPercentLayoutInfo = source.mPercentLayoutInfo;
}
 
Example 36
Project: android_ui   File: CircularNumberPicker.java   Source Code and License 5 votes vote down vote up
/**
 */
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) {
	super.onInitializeAccessibilityNodeInfo(info);
	info.setClassName(CircularNumberPicker.class.getName());
}
 
Example 37
Project: Saiy-PS   File: SaiyTextToSpeech.java   Source Code and License 5 votes vote down vote up
/**
 * Automatically select the user's default voice.
 *
 * @param language   the {@link Locale} language
 * @param region     the {@link Locale} region
 * @param conditions the {@link SelfAwareConditions}
 * @param params     the {@link SelfAwareParameters}
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setDefaultVoice(@NonNull final String language, @NonNull final String region,
                             @NonNull final SelfAwareConditions conditions,
                             @NonNull final SelfAwareParameters params) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "setDefaultVoice");
    }

    final Pair<SaiyVoice, Locale> voicePair = new TTSVoice(language, region, conditions, params, null)
            .buildVoice();

    if (voicePair.first != null) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "setDefaultVoice: Setting Voice: " + voicePair.first.toString());
        }

        final SaiyVoice saiyVoice = new SaiyVoice(voicePair.first);
        saiyVoice.setEngine(getInitialisedEngine());
        saiyVoice.setGender(saiyVoice.getName());

        final String gsonString = new GsonBuilder().disableHtmlEscaping().create().toJson(saiyVoice);

        if (DEBUG) {
            MyLog.i(CLS_NAME, "setDefaultVoice: gsonString: " + gsonString);
        }

        SPH.setDefaultTTSVoice(mContext, gsonString);

    } else {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "setDefaultVoice: Unable to establish a default voice");
        }
    }
}
 
Example 38
Project: egma-shapi   File: SoundPoolAudioEffectEngine.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private SoundPool createSoundPoolLollipop() {
    final AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_GAME)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();
    return new SoundPool.Builder()
            .setAudioAttributes(audioAttributes)
            .setMaxStreams(4)
            .build();
}
 
Example 39
Project: igrow-android   File: BluetoothLeScanL21Proxy.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void startLeScan() {
    List<ScanFilter> filters = new ArrayList<ScanFilter>();
    ScanFilter filter = new ScanFilter.Builder().build();
    filters.add(filter);

    ScanSettings settings = new ScanSettings.Builder().setScanMode(SCAN_MODE_LOW_LATENCY)
            .build();

    mBluetoothLeScanner.startScan(filters, settings, mLeScanCallback);
}
 
Example 40
Project: android_ui   File: WebViewWidget.java   Source Code and License 5 votes vote down vote up
/**
 */
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) {
	super.onInitializeAccessibilityEvent(event);
	event.setClassName(WebViewWidget.class.getName());
}
 
Example 41
Project: android_ui   File: FrameLayoutWidget.java   Source Code and License 5 votes vote down vote up
/**
 */
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) {
	super.onInitializeAccessibilityNodeInfo(info);
	info.setClassName(FrameLayoutWidget.class.getName());
}
 
Example 42
Project: Spyglass   File: WithDefaultToFloat.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
@RequiresApi(21)
public WithDefaultToFloat(
		final Context context,
		final AttributeSet attrs,
		final int defStyleAttr,
		final int defStyleRes) {

	super(context, attrs, defStyleAttr, defStyleRes);
	init(attrs, defStyleAttr, defStyleRes);
}
 
Example 43
Project: aos-Video   File: PlayerService.java   Source Code and License 5 votes vote down vote up
/**
 * set now playing card to stop
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void stopNowPlayingCard() {
    if(mSession==null)
        return;
    if (DBG) Log.d(TAG, "stopNowPlayingCard");

    PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
            .setActions(getAvailableActions());
    stateBuilder.setState(PlaybackState.STATE_STOPPED, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1.0f);
    mSession.setPlaybackState(stateBuilder.build());
}
 
Example 44
Project: easyfilemanager   File: IconUtils.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Drawable applyTintList(Context context, int drawableId, int tintColorId) {
    final Drawable icon = getDrawable(context, drawableId);
    icon.mutate();
    DrawableCompat.setTintList(DrawableCompat.wrap(icon), ContextCompat.getColorStateList(context, tintColorId));
    return icon;
}
 
Example 45
Project: RX_Demo   File: BaseActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
    Window win = getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}
 
Example 46
Project: FloatingApps   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public void checkPermissionOverlay() {
    if (!Settings.canDrawOverlays(this)) {
        Toast.makeText(getApplicationContext(), "not overlay", Toast.LENGTH_LONG).show();
        Intent intentSettings = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        startActivityForResult(intentSettings, OVERLAY_PERMISSION_REQ_CODE);
    }
}
 
Example 47
Project: cuckoo   File: DelegationProcessor.java   Source Code and License 5 votes vote down vote up
@TargetApi(24)
private Modifier[] getModifiers(TypeElement originalClass) {
    List<Modifier> modifiers = originalClass.getModifiers()
            .stream()
            .filter(modifier -> modifier != Modifier.ABSTRACT)
            .collect(Collectors.toList());

    modifiers.add(0, Modifier.FINAL);
    return modifiers.stream().toArray(Modifier[]::new);
}
 
Example 48
Project: LiuAGeAndroid   File: SystemBarTintManager.java   Source Code and License 5 votes vote down vote up
/**
 * Apply the specified alpha to the system status bar.
 *
 * @param alpha The alpha to use
 */
@TargetApi(11)
public void setStatusBarAlpha(float alpha) {
    if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mStatusBarTintView.setAlpha(alpha);
    }
}
 
Example 49
Project: TYT   File: DynamicGridView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void animateWobbleInverse(View v) {
    ObjectAnimator animator = createBaseWobble(v);
    animator.setFloatValues(2, -2);
    animator.start();
    mWobbleAnimators.add(animator);
}
 
Example 50
Project: AndroidTvDemo   File: AndroidMediaFormat.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public String toString() {
    StringBuilder out = new StringBuilder(128);
    out.append(getClass().getName());
    out.append('{');
    if (mMediaFormat != null) {
        out.append(mMediaFormat.toString());
    } else {
        out.append("null");
    }
    out.append('}');
    return out.toString();
}
 
Example 51
Project: GitHub   File: ButterKnife.java   Source Code and License 5 votes vote down vote up
/**
 * Apply the specified {@code value} across the {@code array} of views using the {@code property}.
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // http://b.android.com/213630
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@UiThread
public static <T extends View, V> void apply(@NonNull T[] array,
    @NonNull Property<? super T, V> setter, V value) {
  //noinspection ForLoopReplaceableByForEach
  for (int i = 0, count = array.length; i < count; i++) {
    setter.set(array[i], value);
  }
}
 
Example 52
Project: PlusGram   File: ChatAttachAlert.java   Source Code and License 5 votes vote down vote up
@TargetApi(16)
public void showCamera() {
    if (cameraView == null) {
        cameraView = new CameraView(baseFragment.getParentActivity());
        container.addView(cameraView, 1, LayoutHelper.createFrame(80, 80));
        cameraView.setDelegate(new CameraView.CameraViewDelegate() {
            @Override
            public void onCameraInit() {
                int count = attachPhotoRecyclerView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = attachPhotoRecyclerView.getChildAt(a);
                    if (child instanceof PhotoAttachCameraCell) {
                        child.setVisibility(View.INVISIBLE);
                        break;
                    }
                }

                String current = cameraView.getCameraSession().getCurrentFlashMode();
                String next = cameraView.getCameraSession().getNextFlashMode();
                if (current.equals(next)) {
                    for (int a = 0; a < 2; a++) {
                        flashModeButton[a].setVisibility(View.INVISIBLE);
                        flashModeButton[a].setAlpha(0.0f);
                        flashModeButton[a].setTranslationY(0.0f);
                    }
                } else {
                    setCameraFlashModeIcon(flashModeButton[0], cameraView.getCameraSession().getCurrentFlashMode());
                    for (int a = 0; a < 2; a++) {
                        flashModeButton[a].setVisibility(a == 0 ? View.VISIBLE : View.INVISIBLE);
                        flashModeButton[a].setAlpha(a == 0 && cameraOpened ? 1.0f : 0.0f);
                        flashModeButton[a].setTranslationY(0.0f);
                    }
                }
                switchCameraButton.setImageResource(cameraView.isFrontface() ? R.drawable.camera_revert1 : R.drawable.camera_revert2);
                switchCameraButton.setVisibility(cameraView.hasFrontFaceCamera() ? View.VISIBLE : View.INVISIBLE);
            }
        });

        cameraIcon = new FrameLayout(baseFragment.getParentActivity());
        container.addView(cameraIcon, 2, LayoutHelper.createFrame(80, 80));

        ImageView cameraImageView = new ImageView(baseFragment.getParentActivity());
        cameraImageView.setScaleType(ImageView.ScaleType.CENTER);
        cameraImageView.setImageResource(R.drawable.instant_camera);
        cameraIcon.addView(cameraImageView, LayoutHelper.createFrame(80, 80, Gravity.RIGHT | Gravity.BOTTOM));
    }
    cameraView.setTranslationX(cameraViewLocation[0]);
    cameraView.setTranslationY(cameraViewLocation[1]);
    cameraIcon.setTranslationX(cameraViewLocation[0]);
    cameraIcon.setTranslationY(cameraViewLocation[1]);
}
 
Example 53
Project: revolution-irc   File: DrawerNavigationView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
    if (mNavList == null)
        mNavList = findViewById(R.id.nav_list);
    mNavList.setPadding(insets.getSystemWindowInsetLeft(),
            0,
            insets.getSystemWindowInsetRight(),
            insets.getSystemWindowInsetBottom());
    ((DrawerMenuListAdapter) mNavList.getAdapter()).setHeaderPaddingTop(insets.getSystemWindowInsetTop());
    return super.dispatchApplyWindowInsets(insets);
}
 
Example 54
Project: Hotspot-master-devp   File: StickyListHeadersListView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
    if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
        return mList.getCheckedItemIds();
    }
    return null;
}
 
Example 55
Project: AndroidOpen   File: OverlayFragment.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void animateRevealHide(final View viewRoot) {
    View fab = MainActivity.of(getActivity()).fab;
    int cx = fab.getLeft() + (fab.getWidth()/2); //middle of button
    int cy = fab.getTop() + (fab.getHeight()/2); //middle of button
    int radius = (int) Math.sqrt(Math.pow(cx, 2) + Math.pow(cy, 2)); //hypotenuse to top left

    Animator anim = ViewAnimationUtils.createCircularReveal(viewRoot, cx, cy, radius, 0);
    anim.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            viewRoot.setVisibility(View.INVISIBLE);
        }
    });
    //anim.setInterpolator(new AccelerateInterpolator());
    anim.setDuration(Navigator.ANIM_DURATION);
    anim.start();

    Integer colorTo = getResources().getColor(R.color.primaryColor);
    Integer colorFrom = getResources().getColor(android.R.color.white);
    ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
    colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animator) {
            overlayLayout.setBackgroundColor((Integer)animator.getAnimatedValue());
        }

    });
    colorAnimation.setInterpolator(new AccelerateInterpolator(2));
    colorAnimation.setDuration(Navigator.ANIM_DURATION);
    colorAnimation.start();
}
 
Example 56
Project: Spyglass   File: WithDefaultToNull.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
@RequiresApi(21)
public WithDefaultToNull(
		final Context context,
		final AttributeSet attrs,
		final int defStyleAttr,
		final int defStyleRes) {

	super(context, attrs, defStyleAttr, defStyleRes);
	init(attrs, defStyleAttr, defStyleRes);
}
 
Example 57
Project: TaipeiTechRefined   File: CourseDetailActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setStatusBarColor(int color) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        if (color == Color.BLACK
                && window.getNavigationBarColor() == Color.BLACK) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }
        window.setStatusBarColor(color);
    }
}
 
Example 58
Project: PlusGram   File: Glow.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void setEdgeGlowColor(Object edgeEffect, @ColorInt int color) {
    if (edgeEffect instanceof EdgeEffectCompat) {
        // EdgeEffectCompat
        try {
            edgeEffect = EDGE_EFFECT_COMPAT_FIELD_EDGE_EFFECT.get(edgeEffect);
        } catch (IllegalAccessException e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
            return;
        }
    }

    if (edgeEffect == null) return;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        // EdgeGlow below Android 4 then old EdgeEffect
        try {
            final Drawable mEdge = (Drawable) EDGE_GLOW_FIELD_EDGE.get(edgeEffect);
            final Drawable mGlow = (Drawable) EDGE_GLOW_FIELD_GLOW.get(edgeEffect);
            mEdge.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            mGlow.setColorFilter(color, PorterDuff.Mode.SRC_IN);
            mEdge.setCallback(null); // free up any references
            mGlow.setCallback(null); // free up any references
        } catch (Exception ex) {
            if (BuildConfig.DEBUG) ex.printStackTrace();
        }
    } else {
        // EdgeEffect
        ((EdgeEffect) edgeEffect).setColor(color);
    }
}
 
Example 59
Project: tumbviewer   File: ImageViewerActivity.java   Source Code and License 5 votes vote down vote up
@TargetApi(21)
private void setSharedElementCallback(final View view) {
    SharedElementCallback callback = new SharedElementCallback() {
        @Override
        public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
            names.clear();
            sharedElements.clear();
            names.add(view.getTransitionName());
            sharedElements.put(view.getTransitionName(), view);
        }
    };
    setEnterSharedElementCallback(callback);
}
 
Example 60
Project: CXJPadProject   File: NotificationUtils.java   Source Code and License 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @SuppressWarnings("deprecation")
    public static void createNotification(Context context, Class<?> cls, String title, String content, String ticker, int id){
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent detailIntent = context.getPackageManager().getLaunchIntentForPackage(CommonUtils
                .getPackageName(context));
        detailIntent.setPackage((String)null);
        detailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0,
                detailIntent, 0);
        int smallicon = SharedPreferencesUtil.getIntData(context, ZhiChiConstant
                .SOBOT_NOTIFICATION_SMALL_ICON, ResourceUtils.getIdByName(context, "drawable", "sobot_logo_small_icon"));
        int largeicon = SharedPreferencesUtil.getIntData(context, ZhiChiConstant
                .SOBOT_NOTIFICATION_LARGE_ICON, ResourceUtils.getIdByName(context, "drawable", "sobot_logo_icon"));
        // 通过Notification.Builder来创建通知,注意API Level
        // API11之后才支持
//        int smallicon = ResourceUtils.getIdByName(context, "drawable", "sobot_logo_small_icon");
//        int largeicon = ResourceUtils.getIdByName(context, "drawable", "sobot_logo_icon");

        BitmapDrawable bd = (BitmapDrawable) context.getResources().getDrawable(largeicon);
        Bitmap bitmap = bd.getBitmap();
        Notification notify2 = new Notification.Builder(context)
                .setSmallIcon(smallicon) // 设置状态栏中的小图片,尺寸一般建议在24×24,这个图片同样也是在下拉状态栏中所显示,如果在那里需要更换更大的图片,可以使用setLargeIcon(Bitmap
                // icon)
                .setLargeIcon(bitmap)
                .setTicker(ticker)// 设置在status
                // bar上显示的提示文字
                .setContentTitle(title)// 设置在下拉status
                // bar后Activity,本例子中的NotififyMessage的TextView中显示的标题
                .setContentText(content)// TextView中显示的详细内容
                .setContentIntent(pendingIntent2) // 关联PendingIntent
                //.setNumber(1) // 在TextView的右方显示的数字,可放大图片看,在最右侧。这个number同时也起到一个序列号的左右,如果多个触发多个通知(同一ID),可以指定显示哪一个。
                .getNotification(); // 需要注意build()是在API level
        // 16及之后增加的,在API11中可以使用getNotificatin()来代替
        notify2.flags |= Notification.FLAG_AUTO_CANCEL;
        /*String ss = SharedPreferencesUtil.getStringData(context,ConstantUtils.ALLOW_NOTIFICATION,"true");
        LogUtils.i("notification--------" + ss);
        if(SharedPreferencesUtil.getStringData(context,ConstantUtils.ALLOW_NOTIFICATION,"true").equals("true")) {
            LogUtils.i("notification--------info--open" + ss);
            if((SharedPreferencesUtil.getStringData(context,ConstantUtils.ALLOW_VIBRATE,"true").equals("true"))
                    && (SharedPreferencesUtil.getStringData(context,ConstantUtils.ALLOW_SOUND,"true").equals("true"))){
                notify2.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;
                LogUtils.i("notification--------all--open" + ss);
            }else if(SharedPreferencesUtil.getStringData(context,ConstantUtils.ALLOW_SOUND,"true").equals("true")) {
                notify2.defaults = Notification.DEFAULT_SOUND;
                LogUtils.i("notification--------sound--open" + ss);
            }else if(SharedPreferencesUtil.getStringData(context,ConstantUtils.ALLOW_VIBRATE,"true").equals("true")) {
                notify2.defaults = Notification.DEFAULT_VIBRATE;
                LogUtils.i("notification--------shake--open" + ss);
            }
        }*/
        notify2.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND;
        manager.notify(id, notify2);
    }