Java Examples for android.graphics.drawable.Icon

The following java examples will help you to understand the usage of android.graphics.drawable.Icon. These source code samples are taken from different open source projects.

Example 1
Project: VirtualApp-master  File: NotificationFixer.java View source code
private static void fixNotificationIcon(Context context, Notification notification, Notification.Builder builder) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        //noinspection deprecation
        builder.setSmallIcon(notification.icon);
        //noinspection deprecation
        builder.setLargeIcon(notification.largeIcon);
    } else {
        Icon icon = notification.getSmallIcon();
        if (icon != null) {
            Bitmap bitmap = drawableToBitMap(icon.loadDrawable(context));
            if (bitmap != null) {
                Icon newIcon = Icon.createWithBitmap(bitmap);
                builder.setSmallIcon(newIcon);
            }
        }
        Icon largeIcon = notification.getLargeIcon();
        if (largeIcon != null) {
            Bitmap bitmap = drawableToBitMap(largeIcon.loadDrawable(context));
            if (bitmap != null) {
                Icon newIcon = Icon.createWithBitmap(bitmap);
                builder.setLargeIcon(newIcon);
            }
        }
    }
}
Example 2
Project: platform_frameworks_base-master  File: ShortcutManagerTest1.java View source code
public void testSetDynamicShortcuts() {
    setCaller(CALLING_PACKAGE_1, USER_0);
    final Icon icon1 = Icon.createWithResource(getTestContext(), R.drawable.icon1);
    final Icon icon2 = Icon.createWithBitmap(BitmapFactory.decodeResource(getTestContext().getResources(), R.drawable.icon2));
    final ShortcutInfo si1 = makeShortcut("shortcut1", "Title 1", makeComponent(ShortcutActivity.class), icon1, makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class, "key1", "val1", "nest", makeBundle("key", 123)), /* weight */
    10);
    final ShortcutInfo si2 = makeShortcut("shortcut2", "Title 2", /* activity */
    null, icon2, makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class), /* weight */
    12);
    final ShortcutInfo si3 = makeShortcut("shortcut3");
    assertTrue(mManager.setDynamicShortcuts(list(si1, si2)));
    assertShortcutIds(assertAllNotKeyFieldsOnly(mManager.getDynamicShortcuts()), "shortcut1", "shortcut2");
    assertEquals(2, mManager.getRemainingCallCount());
    // TODO: Check fields
    assertTrue(mManager.setDynamicShortcuts(list(si1)));
    assertShortcutIds(assertAllNotKeyFieldsOnly(mManager.getDynamicShortcuts()), "shortcut1");
    assertEquals(1, mManager.getRemainingCallCount());
    assertTrue(mManager.setDynamicShortcuts(list()));
    assertEquals(0, mManager.getDynamicShortcuts().size());
    assertEquals(0, mManager.getRemainingCallCount());
    dumpsysOnLogcat();
    // Need to advance the clock for reset to work.
    mInjectedCurrentTimeMillis++;
    mService.resetThrottlingInner(UserHandle.USER_SYSTEM);
    dumpsysOnLogcat();
    assertTrue(mManager.setDynamicShortcuts(list(si2, si3)));
    assertEquals(2, mManager.getDynamicShortcuts().size());
    // TODO Check max number
    mRunningUsers.put(USER_10, true);
    runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
        assertTrue(mManager.setDynamicShortcuts(list(makeShortcut("s1"))));
    });
}
Example 3
Project: shortbread-master  File: AdvancedShortcutActivityGenerated.java View source code
public static List<List<ShortcutInfo>> createShortcuts(Context context) {
    List<ShortcutInfo> enabledShortcuts = new ArrayList<>();
    List<ShortcutInfo> disabledShortcuts = new ArrayList<>();
    enabledShortcuts.add(new ShortcutInfo.Builder(context, "ID_2").setShortLabel("SHORT_LABEL").setLongLabel("LONG_LABEL").setIcon(Icon.createWithResource(context, 123)).setDisabledMessage("DISABLED_MESSAGE").setIntents(TaskStackBuilder.create(context).addParentStack(AdvancedShortcutActivity.class).addNextIntent(new Intent(context, AdvancedShortcutActivity.class).setAction("ACTION")).getIntents()).setRank(1).build());
    return Arrays.asList(enabledShortcuts, disabledShortcuts);
}
Example 4
Project: AndroidStudyDemo-master  File: DirectShareService.java View source code
@Override
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
    ComponentName componentName = new ComponentName(getPackageName(), ShareActivity.class.getCanonicalName());
    ArrayList<ChooserTarget> targets = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Bundle extras = new Bundle();
        extras.putInt("directsharekey", i);
        targets.add(new ChooserTarget("name_" + i, Icon.createWithResource(this, R.mipmap.ic_logo), 0.5f, componentName, extras));
    }
    return targets;
}
Example 5
Project: shortcut-helper-master  File: ShortcutHelper.java View source code
public ShortcutHelper createShortcut(@NonNull CharSequence shortLabel, @NonNull CharSequence longLabel, @NonNull int iconResource, @NonNull Intent intent) {
    if (Build.VERSION.SDK_INT < 25) {
        return this;
    }
    String shortcutId = shortLabel.toString().replaceAll("\\s+", "").toLowerCase() + "_shortcut";
    ShortcutInfo shortcut = new ShortcutInfo.Builder(mActivity, shortcutId).setShortLabel(shortLabel).setLongLabel(longLabel).setIcon(Icon.createWithResource(mActivity, iconResource)).setIntent(intent).build();
    mShortcutInfos.add(shortcut);
    return this;
}
Example 6
Project: robolectric-master  File: ShadowNotificationBuilderTest.java View source code
@Test
@Config(minSdk = M)
public void withBigPictureStyle() {
    Bitmap bigPicture = BitmapFactory.decodeResource(RuntimeEnvironment.application.getResources(), R.drawable.an_image);
    Icon bigLargeIcon = Icon.createWithBitmap(bigPicture);
    Notification notification = builder.setStyle(new Notification.BigPictureStyle(builder).bigPicture(bigPicture).bigLargeIcon(bigLargeIcon)).build();
    assertThat(shadowOf(notification).getBigPicture()).isEqualTo(bigPicture);
}
Example 7
Project: cw-omnibus-master  File: VideoPlayerActivity.java View source code
private RemoteAction buildRemoteAction(int requestCode, int iconId, int titleId, int descId) {
    Intent i = new Intent(this, RemoteActionReceiver.class).putExtra(EXTRA_REQUEST, requestCode);
    PendingIntent pi = PendingIntent.getBroadcast(this, requestCode, i, 0);
    Icon icon = Icon.createWithResource(this, iconId);
    String title = getString(titleId);
    String desc = getString(descId);
    return (new RemoteAction(icon, title, desc, pi));
}
Example 8
Project: status-master  File: NotificationData.java View source code
private void init(Notification notification, int id, String packageName) {
    category = NotificationCompat.getCategory(notification);
    title = getTitle(notification);
    subtitle = getSubtitle(notification);
    this.packageName = packageName;
    group = NotificationCompat.getGroup(notification);
    priority = notification.priority;
    this.id = id;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        this.color = notification.color;
    isAlert = notification.vibrate != null || notification.sound != null;
    Bundle extras = NotificationCompat.getExtras(notification);
    iconRes = extras.getInt(NotificationCompat.EXTRA_SMALL_ICON, 0);
    if (iconRes == 0 && Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        iconRes = notification.icon;
    if (iconRes == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        unloadedIcon = extras.getParcelable(NotificationCompat.EXTRA_SMALL_ICON);
        if (unloadedIcon == null)
            unloadedIcon = notification.getSmallIcon();
    }
    Object parcelable = extras.getParcelable(NotificationCompat.EXTRA_LARGE_ICON);
    if (parcelable != null) {
        if (parcelable instanceof Bitmap)
            largeIcon = (Bitmap) parcelable;
        else {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && parcelable instanceof Icon) {
                    //throws a ClassNotFoundException? :P
                    unloadedLargeIcon = (Icon) parcelable;
                }
            } catch (Exception ignored) {
            }
        }
    }
    if (largeIcon == null) {
        parcelable = extras.getParcelable(NotificationCompat.EXTRA_LARGE_ICON_BIG);
        if (parcelable instanceof Bitmap)
            largeIcon = (Bitmap) parcelable;
        else {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && parcelable instanceof Icon) {
                    //throws a ClassNotFoundException? :P
                    unloadedLargeIcon = (Icon) parcelable;
                }
            } catch (Exception ignored) {
            }
        }
    }
    if (largeIcon == null && Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        largeIcon = notification.largeIcon;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        unloadedLargeIcon = notification.getLargeIcon();
    intent = notification.contentIntent;
    actions = new ActionData[NotificationCompat.getActionCount(notification)];
    for (int i = 0; i < actions.length; i++) {
        actions[i] = new ActionData(NotificationCompat.getAction(notification, i), packageName);
    }
}
Example 9
Project: pluginframework-master  File: INotificationManagerHookHandle.java View source code
private boolean isPluginNotification(Notification notification) {
    if (notification == null) {
        return false;
    }
    if (notification.contentView != null && !TextUtils.equals(mHostContext.getPackageName(), notification.contentView.getPackage())) {
        return true;
    }
    if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
        if (notification.tickerView != null && !TextUtils.equals(mHostContext.getPackageName(), notification.tickerView.getPackage())) {
            return true;
        }
    }
    if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
        if (notification.bigContentView != null && !TextUtils.equals(mHostContext.getPackageName(), notification.bigContentView.getPackage())) {
            return true;
        }
    }
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
        if (notification.headsUpContentView != null && !TextUtils.equals(mHostContext.getPackageName(), notification.headsUpContentView.getPackage())) {
            return true;
        }
    }
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
        android.graphics.drawable.Icon icon = notification.getSmallIcon();
        if (icon != null) {
            try {
                Object mString1Obj = FieldUtils.readField(icon, "mString1", true);
                if (mString1Obj instanceof String) {
                    String mString1 = ((String) mString1Obj);
                    if (PluginManager.getInstance().isPluginPackage(mString1)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "fix Icon.smallIcon", e);
            }
        }
    }
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
        android.graphics.drawable.Icon icon = notification.getLargeIcon();
        if (icon != null) {
            try {
                Object mString1Obj = FieldUtils.readField(icon, "mString1", true);
                if (mString1Obj instanceof String) {
                    String mString1 = ((String) mString1Obj);
                    if (PluginManager.getInstance().isPluginPackage(mString1)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "fix Icon.smallIcon", e);
            }
        }
    }
    try {
        Bundle mExtras = (Bundle) FieldUtils.readField(notification, "extras", true);
        for (String s : mExtras.keySet()) {
            if (mExtras.get(s) != null && mExtras.get(s) instanceof ApplicationInfo) {
                ApplicationInfo applicationInfo = (ApplicationInfo) mExtras.get(s);
                return !TextUtils.equals(mHostContext.getPackageName(), applicationInfo.packageName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
Example 10
Project: Phonograph-master  File: AppShortcutIconGenerator.java View source code
private static Icon generateUserThemedIcon(Context context, int iconId) {
    //Get background color from context's theme
    final TypedValue typedColorBackground = new TypedValue();
    context.getTheme().resolveAttribute(android.R.attr.colorBackground, typedColorBackground, true);
    //Return an Icon of iconId with those colors
    return generateThemedIcon(context, iconId, ThemeStore.primaryColor(context), typedColorBackground.data);
}
Example 11
Project: Bigbang-master  File: TotleSwitchTile.java View source code
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick() {
    Log.d(LOG_TAG, "onClick state = " + Integer.toString(getQsTile().getState()));
    Icon icon;
    String title;
    if (toggleState == STATE_ON) {
        toggleState = STATE_OFF;
        title = getResources().getString(R.string.notify_total_switch_off);
        icon = Icon.createWithResource(getApplicationContext(), R.drawable.notify_off);
        // 更改成非活跃状态
        getQsTile().setState(Tile.STATE_INACTIVE);
    } else {
        toggleState = STATE_ON;
        title = getResources().getString(R.string.notify_total_switch_on);
        icon = Icon.createWithResource(getApplicationContext(), R.drawable.notify_on);
        //更改成活跃状态
        getQsTile().setState(Tile.STATE_ACTIVE);
    }
    //设置图标
    getQsTile().setIcon(icon);
    getQsTile().setLabel(title);
    //更新Tile
    getQsTile().updateTile();
    Intent intent = new Intent();
    intent.setClass(this, TotalSwitchActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivityAndCollapse(intent);
}
Example 12
Project: FileSpace-Android-master  File: QuickSettingsTileService.java View source code
private void syncTile(final boolean active) {
    final Icon loopIcon = getTileIcon();
    final String loopTitle = getTileTitle();
    final int loopTileState = getTileState(active);
    final Tile qsTile = getQsTile();
    if (qsTile != null) {
        qsTile.setLabel(loopTitle);
        qsTile.setIcon(loopIcon);
        qsTile.setState(loopTileState);
        qsTile.updateTile();
    }
}
Example 13
Project: conversation-master  File: ContactChooserTargetService.java View source code
@Override
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
    Intent intent = new Intent(this, XmppConnectionService.class);
    intent.setAction("contact_chooser");
    startService(intent);
    bindService(intent, this, Context.BIND_AUTO_CREATE);
    ArrayList<ChooserTarget> chooserTargets = new ArrayList<>();
    try {
        waitForService();
        final ArrayList<Conversation> conversations = new ArrayList<>();
        if (!mXmppConnectionService.areMessagesInitialized()) {
            return chooserTargets;
        }
        mXmppConnectionService.populateWithOrderedConversations(conversations, false);
        final ComponentName componentName = new ComponentName(this, ShareWithActivity.class);
        final int pixel = (int) (48 * getResources().getDisplayMetrics().density);
        for (int i = 0; i < Math.min(conversations.size(), MAX_TARGETS); ++i) {
            final Conversation conversation = conversations.get(i);
            final String name = conversation.getName();
            final Icon icon = Icon.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation, pixel));
            final float score = 1 - (1.0f / MAX_TARGETS) * i;
            final Bundle extras = new Bundle();
            extras.putString("uuid", conversation.getUuid());
            chooserTargets.add(new ChooserTarget(name, icon, score, componentName, extras));
        }
    } catch (InterruptedException e) {
    }
    unbindService(this);
    return chooserTargets;
}
Example 14
Project: android-DirectShare-master  File: SampleChooserTargetService.java View source code
@Override
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
    ComponentName componentName = new ComponentName(getPackageName(), SendMessageActivity.class.getCanonicalName());
    // The list of Direct Share items. The system will show the items the way they are sorted
    // in this list.
    ArrayList<ChooserTarget> targets = new ArrayList<>();
    for (int i = 0; i < Contact.CONTACTS.length; ++i) {
        Contact contact = Contact.byId(i);
        Bundle extras = new Bundle();
        extras.putInt(Contact.ID, i);
        targets.add(new ChooserTarget(// The name of this target.
        contact.getName(), // The icon to represent this target.
        Icon.createWithResource(this, contact.getIcon()), // low scores when there are too many Direct Share items.
        0.5f, // The name of the component to be launched if this target is chosen.
        componentName, // chosen.
        extras));
    }
    return targets;
}
Example 15
Project: platform_packages_apps_packageinstaller-master  File: GrantPermissionsActivity.java View source code
private boolean showNextPermissionGroupGrantRequest() {
    final int groupCount = mRequestGrantPermissionGroups.size();
    int currentIndex = 0;
    for (GroupState groupState : mRequestGrantPermissionGroups.values()) {
        if (groupState.mState == GroupState.STATE_UNKNOWN) {
            CharSequence appLabel = mAppPermissions.getAppLabel();
            Spanned message = Html.fromHtml(getString(R.string.permission_warning_template, appLabel, groupState.mGroup.getDescription()), 0);
            // Set the permission message as the title so it can be announced.
            setTitle(message);
            // Set the new grant view
            // TODO: Use a real message for the action. We need group action APIs
            Resources resources;
            try {
                resources = getPackageManager().getResourcesForApplication(groupState.mGroup.getIconPkg());
            } catch (NameNotFoundException e) {
                resources = Resources.getSystem();
            }
            int icon = groupState.mGroup.getIconResId();
            mViewHandler.updateUi(groupState.mGroup.getName(), groupCount, currentIndex, Icon.createWithResource(resources, icon), message, groupState.mGroup.isUserSet());
            return true;
        }
        currentIndex++;
    }
    return false;
}
Example 16
Project: WAM-master  File: ShortcutsManager.java View source code
private void addDummyShortcut() {
    mSystemShortcutManager.removeAllDynamicShortcuts();
    Bitmap profilePhoto = Utils.drawableToBitmap(Utils.context.getDrawable(Resources.getDrawable("ic_shortcut_contact")));
    shortcuts.add(0, new ShortcutInfo.Builder(context, "none").setShortLabel("Disabled for this build").setIcon(Icon.createWithBitmap(profilePhoto)).setIntent(new Intent(context, HomeActivity.class).setAction(Intent.ACTION_ASSIST)).build());
    mSystemShortcutManager.addDynamicShortcuts(shortcuts);
}
Example 17
Project: muzei-master  File: NextArtworkTileService.java View source code
private void updateTile() {
    Tile tile = getQsTile();
    if (tile == null) {
        // We'll update the tile next time onStartListening is called.
        return;
    }
    if (!mWallpaperActive) {
        // If the wallpaper isn't active, the quick tile will activate it
        tile.setState(Tile.STATE_INACTIVE);
        tile.setLabel(getString(R.string.action_activate));
        tile.setIcon(Icon.createWithResource(this, R.drawable.ic_stat_muzei));
        tile.updateTile();
        return;
    }
    // Else, the wallpaper is active so we query on whether the 'Next Artwork' command
    // is available
    Cursor data = getContentResolver().query(MuzeiContract.Sources.CONTENT_URI, new String[] { MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND }, MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED + "=1", null, null);
    if (data == null) {
        return;
    }
    boolean supportsNextArtwork = false;
    if (data.moveToFirst()) {
        supportsNextArtwork = data.getInt(0) != 0;
    }
    data.close();
    if (supportsNextArtwork) {
        tile.setState(Tile.STATE_ACTIVE);
        tile.setLabel(getString(R.string.action_next_artwork));
        tile.setIcon(Icon.createWithResource(this, R.drawable.ic_notif_full_next_artwork));
    } else {
        tile.setState(Tile.STATE_UNAVAILABLE);
        tile.setLabel(getString(R.string.action_next_artwork));
        tile.setIcon(Icon.createWithResource(this, R.drawable.ic_notif_full_next_artwork));
    }
    tile.updateTile();
}
Example 18
Project: react-native-quick-actions-master  File: AppShortcutsModule.java View source code
@ReactMethod
@TargetApi(25)
public void setShortcutItems(ReadableArray items) {
    if (!isShortcutSupported() || items.size() == 0) {
        return;
    }
    Context context = getReactApplicationContext();
    mShortcutItems = new ArrayList<>(items.size());
    List<ShortcutInfo> shortcuts = new ArrayList<>(items.size());
    for (int i = 0; i < items.size(); i++) {
        ShortcutItem item = ShortcutItem.fromReadableMap(items.getMap(i));
        mShortcutItems.add(item);
        int iconResId = context.getResources().getIdentifier(item.icon, "drawable", context.getPackageName());
        Intent intent = new Intent(context, getCurrentActivity().getClass());
        intent.setAction(ACTION_SHORTCUT);
        intent.putExtra(SHORTCUT_TYPE, item.type);
        shortcuts.add(new ShortcutInfo.Builder(context, "id" + i).setShortLabel(item.title).setLongLabel(item.title).setIcon(Icon.createWithResource(context, iconResId)).setIntent(intent).build());
    }
    getReactApplicationContext().getSystemService(ShortcutManager.class).setDynamicShortcuts(shortcuts);
}
Example 19
Project: android-examples-master  File: MainActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /** App Shortcuts are great for exposing actions of your app and bring back users into your flow
         * they can be static or dynamic
         * static are set in stone once you define them (you can only update them with an app redeploy)
         * dynamic can be changed on the fly
         */
    final ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
    /**
         * Dynamic Shortcuts
         * By setting a custom rank to a dynamic shortcut we can control the order they appear when revealed:
         * the higher the rank, the most top the shortcut goes.
         * the rank of a static shortcut cannot be changed they will be shown in the order they're defined in the shortcuts.xml file.
         */
    ShortcutInfo browserShortcut = new ShortcutInfo.Builder(this, "shortcut_browser").setShortLabel("google.com").setLongLabel("open google.com").setDisabledMessage("dynamic shortcut disable").setIcon(Icon.createWithResource(this, R.drawable.ic_open_in_browser)).setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"))).setRank(0).build();
    ShortcutInfo dynamicShortcut = new ShortcutInfo.Builder(this, "dynamic shortcut").setShortLabel("Dynamic").setLongLabel("Open dynamic shortcut").setIcon(Icon.createWithResource(this, R.drawable.ic_dynamic)).setIntents(new Intent[] { new Intent(Intent.ACTION_MAIN, Uri.EMPTY, this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK), new Intent(DynamicShortcutActivity.ACTION) }).setRank(1).build();
    shortcutManager.setDynamicShortcuts(Arrays.asList(browserShortcut, dynamicShortcut));
    /**
         * updating the shortcuts
         * we can updates the shortcut by making the use of updateShortcuts() method.
         */
    Button updateShortcutsBtn = (Button) findViewById(R.id.update_shortcuts);
    updateShortcutsBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(android.R.color.holo_red_light, getTheme()));
            String label = "open google.com";
            SpannableStringBuilder colouredLabel = new SpannableStringBuilder(label);
            colouredLabel.setSpan(colorSpan, 0, label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            ShortcutInfo browserShortcut = new ShortcutInfo.Builder(MainActivity.this, "shortcut_browser").setShortLabel(colouredLabel).setRank(1).build();
            ShortcutInfo dynamicShortcut = new ShortcutInfo.Builder(MainActivity.this, "dynamic shortcut").setRank(0).build();
            shortcutManager.updateShortcuts(Arrays.asList(browserShortcut, dynamicShortcut));
            Toast.makeText(MainActivity.this, "Shortcuts Updated :)", Toast.LENGTH_SHORT).show();
        }
    });
    /**
         * Disabling app shortcut
         * disableShortcuts(List) will remove the specified dynamic shortcuts and also make any
         * specified pinned shortcuts un-launchable.
         */
    Button disableShortcutBtn = (Button) findViewById(R.id.disable_shortcut);
    disableShortcutBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            shortcutManager.disableShortcuts(Arrays.asList("dynamic shortcut"));
            Toast.makeText(MainActivity.this, "Dynamic shortcut Disabled !!", Toast.LENGTH_SHORT).show();
        }
    });
}
Example 20
Project: CumulusTV-master  File: CumulusVideoPlayback.java View source code
@Override
public void run() {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        JsonChannel jsonChannel = ChannelDatabase.getInstance(getApplicationContext()).findChannelByMediaUrl(urlStream);
        if (jsonChannel == null) {
            // Don't create a shortcut because we don't have metadata
            return;
        }
        Log.d(TAG, "Adding dynamic shortcut to " + jsonChannel.getName());
        String logo = ChannelDatabase.getNonNullChannelLogo(jsonChannel);
        try {
            Bitmap logoBitmap = Glide.with(getApplicationContext()).load(logo).asBitmap().into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
            ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
            shortcutManager.removeAllDynamicShortcuts();
            Intent playVideo = new Intent(getApplicationContext(), CumulusVideoPlayback.class);
            playVideo.setAction("play");
            playVideo.putExtra(KEY_VIDEO_URL, urlStream);
            ShortcutInfo shortcut = new ShortcutInfo.Builder(CumulusVideoPlayback.this, "id1").setShortLabel(jsonChannel.getName() + "").setLongLabel(jsonChannel.getNumber() + " - " + jsonChannel.getName()).setIcon(Icon.createWithBitmap(logoBitmap)).setIntent(playVideo).build();
            shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));
        } catch (InterruptedExceptionExecutionException |  e) {
            e.printStackTrace();
        }
    }
}
Example 21
Project: Aerlink-for-Android-master  File: NotificationServiceHandler.java View source code
private void onNotificationReceived(NotificationData notificationData) {
    Log.d(LOG_TAG, "Notification received");
    // Build pending intent for when the user swipes the card away
    Intent deleteIntent = new Intent(Constants.IA_DELETE);
    deleteIntent.putExtra(Constants.IE_NOTIFICATION_UID, notificationData.getUID());
    PendingIntent deleteAction = PendingIntent.getBroadcast(mContext, mNotificationNumber, deleteIntent, 0);
    Notification.Builder notificationBuilder = new Notification.Builder(mContext).setContentTitle(notificationData.getTitle()).setContentText(notificationData.getMessage()).setSmallIcon(notificationData.getAppIcon()).setGroup(notificationData.getAppId()).setDeleteIntent(deleteAction).setPriority(Notification.PRIORITY_MAX);
    if (notificationData.isUnknown() && !notificationData.getAppId().isEmpty()) {
        Bitmap bitmap = loadImageFromStorage(notificationData.getAppId());
        if (bitmap != null) {
            Log.i(LOG_TAG, "Icon loaded");
            Icon icon = Icon.createWithBitmap(bitmap);
            notificationBuilder.setSmallIcon(icon);
        } else {
            Bitmap background = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.bg_notification);
            Notification.WearableExtender wearableExtender = new Notification.WearableExtender().setBackground(background);
            notificationBuilder.extend(wearableExtender);
            Log.i(LOG_TAG, "Requesting icon");
            String dataString = (char) 0x01 + notificationData.getAppId();
            Command iconCommand = new Command(ALSConstants.SERVICE_UUID, ALSConstants.CHARACTERISTIC_UTILS_ACTION, dataString.getBytes());
            mServiceUtils.addCommandToQueue(iconCommand);
        }
    } else {
        Bitmap background;
        if (notificationData.getBackground() != -1) {
            background = BitmapFactory.decodeResource(mContext.getResources(), notificationData.getBackground());
        } else {
            background = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
            background.eraseColor(notificationData.getBackgroundColor());
        }
        Notification.WearableExtender wearableExtender = new Notification.WearableExtender().setBackground(background);
        notificationBuilder.extend(wearableExtender);
    }
    // Build positive action intent only if available
    if (notificationData.getPositiveAction() != null) {
        Intent positiveIntent = new Intent(Constants.IA_POSITIVE);
        positiveIntent.putExtra(Constants.IE_NOTIFICATION_UID, notificationData.getUID());
        PendingIntent positiveActionIntent = PendingIntent.getBroadcast(mContext, mNotificationNumber, positiveIntent, 0);
        Icon icon = Icon.createWithResource(mContext, R.drawable.ic_action_accept);
        Notification.Action positiveAction = new Notification.Action.Builder(icon, notificationData.getPositiveAction(), positiveActionIntent).build();
        notificationBuilder.addAction(positiveAction);
    }
    // Build negative action intent only if available
    if (notificationData.getNegativeAction() != null) {
        Intent negativeIntent = new Intent(Constants.IA_NEGATIVE);
        negativeIntent.putExtra(Constants.IE_NOTIFICATION_UID, notificationData.getUID());
        PendingIntent negativeActionIntent = PendingIntent.getBroadcast(mContext, mNotificationNumber, negativeIntent, 0);
        Icon icon = Icon.createWithResource(mContext, R.drawable.ic_action_remove);
        Notification.Action negativeAction = new Notification.Action.Builder(icon, notificationData.getNegativeAction(), negativeActionIntent).build();
        notificationBuilder.addAction(negativeAction);
    }
    if (!notificationData.isPreExisting()) {
        if (!notificationData.isSilent()) {
            notificationBuilder.setVibrate(VIBRATION_PATTERN);
        } else {
            notificationBuilder.setVibrate(SILENT_VIBRATION_PATTERN);
        }
    }
    // Build and notify
    Notification notification = notificationBuilder.build();
    mServiceUtils.notify(notificationData.getUIDString(), NOTIFICATION_REGULAR, notification);
    mNotificationNumber++;
}
Example 22
Project: Android-Plugin-Framework-master  File: AndroidAppINotificationManager.java View source code
private static void resolveRemoteViews(Notification notification) {
    String hostPackageName = FairyGlobal.getApplication().getPackageName();
    if (Build.VERSION.SDK_INT >= 23) {
        Icon mSmallIcon = (Icon) RefInvoker.getField(notification, Notification.class, "mSmallIcon");
        Icon mLargeIcon = (Icon) RefInvoker.getField(notification, Notification.class, "mLargeIcon");
        if (mSmallIcon != null) {
            RefInvoker.setField(mSmallIcon, Icon.class, "mString1", hostPackageName);
        }
        if (mLargeIcon != null) {
            RefInvoker.setField(mLargeIcon, Icon.class, "mString1", hostPackageName);
        }
    }
    if (Build.VERSION.SDK_INT >= 21) {
        int layoutId = 0;
        if (notification.tickerView != null) {
            layoutId = new HackRemoteViews(notification.tickerView).getLayoutId();
        }
        if (layoutId == 0) {
            if (notification.contentView != null) {
                layoutId = new HackRemoteViews(notification.contentView).getLayoutId();
            }
        }
        if (layoutId == 0) {
            if (notification.bigContentView != null) {
                layoutId = new HackRemoteViews(notification.bigContentView).getLayoutId();
            }
        }
        if (layoutId == 0) {
            if (notification.headsUpContentView != null) {
                layoutId = new HackRemoteViews(notification.headsUpContentView).getLayoutId();
            }
        }
        if (layoutId == 0) {
            return;
        }
        //检查资源布局资源Id是否属于宿主
        if (ResourceUtil.isMainResId(layoutId)) {
            return;
        }
        //检查资源布局资源Id是否属于系统
        if (layoutId >> 24 == 0x1f) {
            return;
        }
        if ("Xiaomi".equals(Build.MANUFACTURER)) {
            LogUtil.e("Xiaomi, not support, caused by MiuiResource");
            if (notification.contentView != null) {
                //重置layout,避免crash
                new HackRemoteViews(notification.contentView).setLayoutId(android.R.layout.test_list_item);
            }
            notification.bigContentView = null;
            notification.headsUpContentView = null;
            notification.tickerView = null;
            return;
        }
        ApplicationInfo newInfo = new ApplicationInfo();
        String packageName = null;
        if (notification.tickerView != null) {
            packageName = notification.tickerView.getPackage();
            new HackRemoteViews(notification.tickerView).setApplicationInfo(newInfo);
        }
        if (notification.contentView != null) {
            if (packageName == null) {
                packageName = notification.contentView.getPackage();
            }
            new HackRemoteViews(notification.contentView).setApplicationInfo(newInfo);
        }
        if (notification.bigContentView != null) {
            if (packageName == null) {
                packageName = notification.bigContentView.getPackage();
            }
            new HackRemoteViews(notification.bigContentView).setApplicationInfo(newInfo);
        }
        if (notification.headsUpContentView != null) {
            if (packageName == null) {
                packageName = notification.headsUpContentView.getPackage();
            }
            new HackRemoteViews(notification.headsUpContentView).setApplicationInfo(newInfo);
        }
        ApplicationInfo applicationInfo = FairyGlobal.getApplication().getApplicationInfo();
        newInfo.packageName = applicationInfo.packageName;
        newInfo.sourceDir = applicationInfo.sourceDir;
        newInfo.dataDir = applicationInfo.dataDir;
        if (packageName != null && !packageName.equals(hostPackageName)) {
            PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByPluginId(packageName);
            newInfo.packageName = pluginDescriptor.getPackageName();
            //要确保publicSourceDir这个路径可以被SystemUI应用读取,
            newInfo.publicSourceDir = prepareNotificationResourcePath(pluginDescriptor.getInstalledPath(), FairyGlobal.getApplication().getExternalCacheDir().getAbsolutePath() + "/notification_res.apk");
        } else if (packageName != null && packageName.equals(hostPackageName)) {
            //如果packageName是宿主,由于前面已经判断出,layoutid不是来自插件,则尝试查找notifications的目标页面,如果目标是插件,则尝试使用此插件作为通知栏的资源来源
            if (notification.contentIntent != null) {
                //只处理contentIntent,其他不管
                Intent intent = new HackPendingIntent(notification.contentIntent).getIntent();
                if (intent != null && intent.getAction() != null && intent.getAction().contains(PluginIntentResolver.CLASS_SEPARATOR)) {
                    String className = intent.getAction().split(PluginIntentResolver.CLASS_SEPARATOR)[0];
                    PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(className);
                    newInfo.packageName = pluginDescriptor.getPackageName();
                    //要确保publicSourceDir这个路径可以被SystemUI应用读取,
                    newInfo.publicSourceDir = prepareNotificationResourcePath(pluginDescriptor.getInstalledPath(), FairyGlobal.getApplication().getExternalCacheDir().getAbsolutePath() + "/notification_res.apk");
                }
            }
        }
    } else if (Build.VERSION.SDK_INT >= 11) {
        if (notification.tickerView != null) {
            new HackRemoteViews(notification.tickerView).setPackage(hostPackageName);
        }
        if (notification.contentView != null) {
            new HackRemoteViews(notification.contentView).setPackage(hostPackageName);
        }
    }
}
Example 23
Project: ContractionTimer-master  File: QuickTileService.java View source code
private void updateTile() {
    final String[] projection = { BaseColumns._ID, ContractionContract.Contractions.COLUMN_NAME_START_TIME, ContractionContract.Contractions.COLUMN_NAME_END_TIME };
    final String selection = ContractionContract.Contractions.COLUMN_NAME_START_TIME + ">?";
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final long averagesTimeFrame = Long.parseLong(preferences.getString(Preferences.AVERAGE_TIME_FRAME_PREFERENCE_KEY, getString(R.string.pref_average_time_frame_default)));
    final long timeCutoff = System.currentTimeMillis() - averagesTimeFrame;
    final String[] selectionArgs = { Long.toString(timeCutoff) };
    final Cursor data = getContentResolver().query(ContractionContract.Contractions.CONTENT_URI, projection, selection, selectionArgs, null);
    // Get the average duration and frequency
    String averages = null;
    if (data != null && data.moveToFirst()) {
        double averageDuration = 0;
        double averageFrequency = 0;
        int numDurations = 0;
        int numFrequencies = 0;
        while (!data.isAfterLast()) {
            final int startTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME);
            final long startTime = data.getLong(startTimeColumnIndex);
            final int endTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME);
            if (!data.isNull(endTimeColumnIndex)) {
                final long endTime = data.getLong(endTimeColumnIndex);
                final long curDuration = endTime - startTime;
                averageDuration = (curDuration + numDurations * averageDuration) / (numDurations + 1);
                numDurations++;
            }
            if (data.moveToNext()) {
                final int prevContractionStartTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME);
                final long prevContractionStartTime = data.getLong(prevContractionStartTimeColumnIndex);
                final long curFrequency = startTime - prevContractionStartTime;
                averageFrequency = (curFrequency + numFrequencies * averageFrequency) / (numFrequencies + 1);
                numFrequencies++;
            }
        }
        final long averageDurationInSeconds = (long) (averageDuration / 1000);
        String formattedAverageDuration = DateUtils.formatElapsedTime(averageDurationInSeconds);
        final long averageFrequencyInSeconds = (long) (averageFrequency / 1000);
        String formattedAverageFrequency = DateUtils.formatElapsedTime(averageFrequencyInSeconds);
        averages = getString(R.string.tile_label, formattedAverageDuration, formattedAverageFrequency);
    }
    // Set the status of the contraction toggle button
    // Need to use a separate cursor as there could be running contractions
    // outside of the average time frame
    final Cursor allData = getContentResolver().query(ContractionContract.Contractions.CONTENT_URI, projection, null, null, null);
    contractionOngoing = allData != null && allData.moveToFirst() && allData.isNull(allData.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME));
    latestContractionId = contractionOngoing ? allData.getLong(allData.getColumnIndex(BaseColumns._ID)) : 0;
    // Close the cursors
    if (data != null)
        data.close();
    if (allData != null)
        allData.close();
    Tile tile = getQsTile();
    String backupLabel;
    if (contractionOngoing) {
        tile.setState(Tile.STATE_ACTIVE);
        tile.setIcon(Icon.createWithResource(this, R.drawable.ic_tile_stop));
        tile.setContentDescription(getString(R.string.appwidget_contraction_stop));
        backupLabel = getString(R.string.notification_timing);
    } else {
        tile.setState(Tile.STATE_INACTIVE);
        tile.setIcon(Icon.createWithResource(this, R.drawable.ic_tile_start));
        tile.setContentDescription(getString(R.string.appwidget_contraction_start));
        backupLabel = getString(R.string.app_name);
    }
    tile.setLabel(averages != null ? averages : backupLabel);
    tile.updateTile();
}
Example 24
Project: Espresso-master  File: OnboardingActivity.java View source code
private void enableShortcuts() {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        ShortcutManager manager = getSystemService(ShortcutManager.class);
        ShortcutInfo addPkg = new ShortcutInfo.Builder(this, "shortcut_add_package").setLongLabel(getString(R.string.shortcut_label_add_package)).setShortLabel(getString(R.string.shortcut_label_add_package)).setIcon(Icon.createWithResource(this, R.drawable.ic_shortcut_add)).setIntent(new Intent(OnboardingActivity.this, AddPackageActivity.class).setAction(Intent.ACTION_VIEW).addCategory(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION)).build();
        ShortcutInfo scanCode = new ShortcutInfo.Builder(this, "shortcut_scan_code").setIcon(Icon.createWithResource(this, R.drawable.ic_shortcut_filter_center_focus)).setLongLabel(getString(R.string.shortcut_label_scan_code)).setShortLabel(getString(R.string.shortcut_label_scan_code)).setIntent(new Intent(OnboardingActivity.this, AddPackageActivity.class).setAction("io.github.marktony.espresso.mvp.addpackage.AddPackageActivity").addCategory(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION)).build();
        ShortcutInfo search = new ShortcutInfo.Builder(this, "shortcut_search").setIcon(Icon.createWithResource(this, R.drawable.ic_shortcut_search)).setLongLabel(getString(R.string.shortcut_label_search)).setShortLabel(getString(R.string.shortcut_label_search)).setIntent(new Intent(OnboardingActivity.this, SearchActivity.class).setAction(Intent.ACTION_VIEW).addCategory(ShortcutInfo.SHORTCUT_CATEGORY_CONVERSATION)).build();
        manager.setDynamicShortcuts(Arrays.asList(addPkg, scanCode, search));
    }
}
Example 25
Project: android-sdk-sources-for-api-level-23-master  File: BaseStatusBar.java View source code
protected StatusBarIconView createIcon(StatusBarNotification sbn) {
    // Construct the icon.
    Notification n = sbn.getNotification();
    final StatusBarIconView iconView = new StatusBarIconView(mContext, sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId()), n);
    iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    final Icon smallIcon = n.getSmallIcon();
    if (smallIcon == null) {
        handleNotificationError(sbn, "No small icon in notification from " + sbn.getPackageName());
        return null;
    }
    final StatusBarIcon ic = new StatusBarIcon(sbn.getUser(), sbn.getPackageName(), smallIcon, n.iconLevel, n.number, n.tickerText);
    if (!iconView.set(ic)) {
        handleNotificationError(sbn, "Couldn't create icon: " + ic);
        return null;
    }
    return iconView;
}
Example 26
Project: prim-ftpd-master  File: ServicesStartStopUtil.java View source code
private static void createStatusbarNotification(Context ctxt) {
    LOGGER.debug("createStatusbarNotification()");
    // create pending intent
    Intent notificationIntent = new Intent(ctxt, PrimitiveFtpdActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(ctxt, 0, notificationIntent, 0);
    Intent stopIntent = new Intent(ctxt, ServicesStartingService.class);
    PendingIntent pendingStopIntent = PendingIntent.getService(ctxt, 0, stopIntent, 0);
    // create notification
    int icon = R.drawable.ic_notification;
    CharSequence tickerText = ctxt.getText(R.string.serverRunning);
    CharSequence contentTitle = ctxt.getText(R.string.notificationTitle);
    CharSequence contentText = tickerText;
    // use main icon as large one
    Bitmap largeIcon = BitmapFactory.decodeResource(ctxt.getResources(), R.drawable.ic_launcher);
    long when = System.currentTimeMillis();
    Notification.Builder builder = new Notification.Builder(ctxt).setTicker(tickerText).setContentTitle(contentTitle).setContentText(contentText).setSmallIcon(icon).setLargeIcon(largeIcon).setContentIntent(contentIntent).setWhen(when);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // TODO check icon for android 7
        Notification.Action stopAction = new Notification.Action.Builder(Icon.createWithResource("", R.drawable.ic_stop_white_24dp), ctxt.getString(R.string.stopService), pendingStopIntent).build();
        builder.addAction(stopAction);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        builder.addAction(R.drawable.ic_stop_white_24dp, ctxt.getString(R.string.stopService), pendingStopIntent);
    }
    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification = builder.build();
    } else {
        notification = builder.getNotification();
    }
    notification.flags |= Notification.FLAG_NO_CLEAR;
    // notification manager
    NotificationUtil.createStatusbarNotification(ctxt, notification);
}
Example 27
Project: container-master  File: NotificationUtils.java View source code
static void fixNotificationIcon(Context context, Notification notification) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        //noinspection deprecation
        notification.icon = context.getApplicationInfo().icon;
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Icon smallIcon = notification.getSmallIcon();
        if (smallIcon != null) {
            Bitmap bitmap = drawableToBitMap(smallIcon.loadDrawable(context));
            if (bitmap != null) {
                Icon newIcon = Icon.createWithBitmap(bitmap);
                NotificationM.mSmallIcon.set(notification, newIcon);
            }
        }
        Icon largeIcon = notification.getLargeIcon();
        if (largeIcon != null) {
            Bitmap bitmap = drawableToBitMap(largeIcon.loadDrawable(context));
            if (bitmap != null) {
                Icon newIcon = Icon.createWithBitmap(bitmap);
                NotificationM.mLargeIcon.set(notification, newIcon);
            }
        }
    }
}
Example 28
Project: Daedalus-master  File: Daedalus.java View source code
public static void updateShortcut(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        Log.d("Daedalus", "Updating shortcut");
        //shortcut!
        String notice = context.getString(R.string.button_text_activate);
        boolean activate = true;
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (DaedalusVpnService.class.getName().equals(service.service.getClassName())) {
                notice = context.getString(R.string.button_text_deactivate);
                activate = false;
            }
        }
        ShortcutInfo info = new ShortcutInfo.Builder(context, Daedalus.SHORTCUT_ID_ACTIVATE).setLongLabel(notice).setShortLabel(notice).setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher)).setIntent(new Intent(context, MainActivity.class).setAction(Intent.ACTION_VIEW).putExtra(MainActivity.LAUNCH_ACTION, activate ? MainActivity.LAUNCH_ACTION_ACTIVATE : MainActivity.LAUNCH_ACTION_DEACTIVATE)).build();
        ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(SHORTCUT_SERVICE);
        shortcutManager.addDynamicShortcuts(Collections.singletonList(info));
    }
}
Example 29
Project: CurrentActivity-master  File: MainFragment.java View source code
@TargetApi(Build.VERSION_CODES.N_MR1)
private void createShortcut() {
    ShortcutManager shortcutManager = activity.getSystemService(ShortcutManager.class);
    Intent intent = new Intent(activity, MainActivity.class);
    intent.setAction(ACTION_QUICK_START);
    intent.putExtra(IS_SHORTCUT_OPEN, true);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    ShortcutInfo shortcut = new ShortcutInfo.Builder(activity, "shortcut_open").setShortLabel(getString(R.string.quick_enable)).setLongLabel(getString(R.string.enable_float_window)).setIcon(Icon.createWithResource(activity, R.mipmap.ic_launcher)).setIntent(intent).build();
    shortcutManager.setDynamicShortcuts(Collections.singletonList(shortcut));
}
Example 30
Project: BeTrains-for-Android-master  File: WelcomeActivity.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        int num = 0;
        DbAdapterConnection mDbHelper = new DbAdapterConnection(this);
        ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
        shortcutManager.removeAllDynamicShortcuts();
        mDbHelper.open();
        Cursor mCursor = mDbHelper.fetchAllFav();
        try {
            while (mCursor.moveToNext() && num <= 4) {
                String item = mCursor.getString(mCursor.getColumnIndex(DbAdapterConnection.KEY_FAV_NAME));
                String itemTwo = mCursor.getString(mCursor.getColumnIndex(DbAdapterConnection.KEY_FAV_NAMETWO));
                int type = mCursor.getInt(mCursor.getColumnIndex(DbAdapterConnection.KEY_FAV_TYPE));
                ShortcutInfo shortcut = null;
                Intent i;
                switch(type) {
                    case 1:
                        i = new Intent(this, InfoStationActivity.class);
                        i.putExtra("Name", item);
                        i.putExtra("ID", itemTwo);
                        try {
                            shortcut = new ShortcutInfo.Builder(this, itemTwo == null ? item : itemTwo).setShortLabel(item).setLongLabel(item + " - " + itemTwo).setIcon(Icon.createWithResource(this, R.drawable.ic_fav_station)).setIntent(i.setAction("")).build();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case 2:
                        i = new Intent(this, InfoTrainActivity.class);
                        i.putExtra("Name", item);
                        shortcut = new ShortcutInfo.Builder(this, item).setShortLabel(item).setLongLabel(item).setIcon(Icon.createWithResource(this, R.drawable.ic_fav_train)).setIntent(i.setAction("")).build();
                        break;
                    case 3:
                        i = new Intent(this, WelcomeActivity.class);
                        i.putExtra("Departure", item);
                        i.putExtra("Arrival", itemTwo);
                        shortcut = new ShortcutInfo.Builder(this, item + " - " + itemTwo).setShortLabel(item + " - " + itemTwo).setLongLabel(item + " - " + itemTwo).setIcon(Icon.createWithResource(this, R.drawable.ic_fav_map)).setIntent(//.setIntent(i)
                        i.setAction("")).build();
                        break;
                }
                if (shortcut != null)
                    shortcutManager.addDynamicShortcuts(Arrays.asList(shortcut));
                num++;
            }
        } finally {
            mCursor.close();
        }
        mDbHelper.close();
    }
    setContentView(R.layout.responsive_content_frame);
    setProgressBarIndeterminateVisibility(false);
    setSupportActionBar((Toolbar) findViewById(R.id.my_awesome_toolbar));
    try {
        //Just in case setStatusBarColor not available
        getWindow().setStatusBarColor(getResources().getColor(R.color.primarycolortransparent));
    } catch (Error e) {
        e.printStackTrace();
    }
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    navigationView = (NavigationView) findViewById(R.id.navigation);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    navigationView.getMenu().clear();
    if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(WelcomeActivity.this) == ConnectionResult.SUCCESS)
        navigationView.inflateMenu(R.menu.nav);
    else
        navigationView.inflateMenu(R.menu.nav_nogps);
    if (drawerLayout != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, (Toolbar) findViewById(R.id.my_awesome_toolbar), R.string.app_name, R.string.app_name) {

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // code here will execute once the drawer is opened
                // creates call to onPrepareOptionsMenu()
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // Code here will execute once drawer is closed
                invalidateOptionsMenu();
            }

            ;
        };
        mDrawerToggle.syncState();
        drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                PreferenceManager.getDefaultSharedPreferences(WelcomeActivity.this).edit().putBoolean("navigation_drawer_learned", true).apply();
                if (mContent instanceof PlannerFragment)
                    findViewById(R.id.tuto).setVisibility(View.GONE);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
    }
    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    if (navigationView != null) {
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(final MenuItem menuItem) {
                if (drawerLayout != null)
                    drawerLayout.closeDrawers();
                switch(menuItem.getItemId()) {
                    case R.id.navigation_item_plan:
                        mContent = new PlannerFragment();
                        break;
                    /*case R.id.navigation_item_notif:
                            mContent = new NotifFragment();
                            break;*/
                    case R.id.navigation_item_iss:
                        mContent = new TrafficFragment();
                        break;
                    case R.id.navigation_item_chat:
                        mContent = new ChatFragment();
                        break;
                    case R.id.navigation_item_star:
                        mContent = new StarredFragment();
                        break;
                    case R.id.navigation_item_closest:
                        mContent = new ClosestFragment();
                        break;
                    case R.id.navigation_item_game:
                        mContent = new GameFragment();
                        break;
                    case R.id.navigation_item_comp:
                        mContent = new CompensationFragment();
                        break;
                    case R.id.navigation_item_extras:
                        mContent = new ExtraFragment();
                        break;
                    default:
                        mContent = new PlannerFragment();
                        close = getString(R.string.activity_label_planner);
                        break;
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit();
                return true;
            }
        });
    }
    // Set the default screen at startup from Preferences
    int pos = Integer.valueOf(settings.getString(getString(R.string.key_activity), "1"));
    if (getIntent().hasExtra("Departure") && getIntent().hasExtra("Arrival"))
        pos = 1;
    switch(pos) {
        case 1:
            mContent = new PlannerFragment();
            break;
        case 2:
            mContent = new TrafficFragment();
            break;
        case 3:
            mContent = new ChatFragment();
            break;
        case 4:
            mContent = new StarredFragment();
            break;
        case 5:
            mContent = new ClosestFragment();
            break;
        case 6:
            mContent = new GameFragment();
            break;
        default:
            mContent = new PlannerFragment();
            close = getString(R.string.activity_label_planner);
            break;
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit();
    SystemBarTintManager tintManager = new SystemBarTintManager(this);
    //tintManager.setStatusBarTintEnabled(true);
    tintManager.setNavigationBarTintEnabled(true);
    tintManager.setTintResource(R.color.primarycolor);
}
Example 31
Project: DeviceConnect-Android-master  File: HostNotificationProfile.java View source code
@Override
public boolean onRequest(final Intent request, final Intent response) {
    if (mNotificationStatusReceiver == null) {
        mNotificationStatusReceiver = new NotificationStatusReceiver();
        getContext().getApplicationContext().registerReceiver(mNotificationStatusReceiver, new IntentFilter(ACTON_NOTIFICATION));
    }
    String serviceId = getServiceID(request);
    NotificationType type = getType(request);
    String body = getBody(request);
    int iconType = 0;
    String title = "";
    if (type == NotificationType.PHONE) {
        iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.drawable.notification_00 : R.drawable.notification_00_post_lollipop;
        title = "PHONE";
    } else if (type == NotificationType.MAIL) {
        iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.drawable.notification_01 : R.drawable.notification_01_post_lollipop;
        title = "MAIL";
    } else if (type == NotificationType.SMS) {
        iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.drawable.notification_02 : R.drawable.notification_02_post_lollipop;
        title = "SMS";
    } else if (type == NotificationType.EVENT) {
        iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.drawable.notification_03 : R.drawable.notification_03_post_lollipop;
        title = "EVENT";
    } else {
        MessageUtils.setInvalidRequestParameterError(response, "type is invalid.");
        return true;
    }
    String encodeBody = "";
    try {
        if (body != null) {
            encodeBody = URLDecoder.decode(body, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        MessageUtils.setInvalidRequestParameterError(response, "body is invalid.");
        return true;
    }
    int notifyId = mRandom.nextInt(RANDOM_SEED);
    if (Build.MODEL.endsWith("M100")) {
        Toast.makeText(getContext(), encodeBody, Toast.LENGTH_SHORT).show();
        response.putExtra(NotificationProfile.PARAM_NOTIFICATION_ID, notifyId);
        setResult(response, IntentDConnectMessage.RESULT_OK);
    } else {
        // Build intent for notification content
        Intent notifyIntent = new Intent(ACTON_NOTIFICATION);
        notifyIntent.putExtra("notificationId", notifyId);
        notifyIntent.putExtra("serviceId", serviceId);
        PendingIntent mPendingIntent = PendingIntent.getBroadcast(getContext(), notifyId, notifyIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
        Notification notification;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext()).setSmallIcon(iconType).setContentTitle("" + title).setContentText(encodeBody).setContentIntent(mPendingIntent);
            notification = notificationBuilder.build();
        } else {
            Notification.Builder notificationBuilder = new Notification.Builder(getContext()).setSmallIcon(Icon.createWithResource(getContext(), iconType)).setContentTitle("" + title).setContentText(encodeBody).setContentIntent(mPendingIntent);
            notification = notificationBuilder.build();
        }
        // Get an instance of the NotificationManager service
        NotificationManager mNotification = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        // Build the notification and issues it with notification
        // manager.
        mNotification.notify(notifyId, notification);
        response.putExtra(NotificationProfile.PARAM_NOTIFICATION_ID, notifyId);
        setResult(response, IntentDConnectMessage.RESULT_OK);
    }
    List<Event> events = EventManager.INSTANCE.getEventList(serviceId, HostNotificationProfile.PROFILE_NAME, null, HostNotificationProfile.ATTRIBUTE_ON_SHOW);
    HostDeviceService service = (HostDeviceService) getContext();
    synchronized (events) {
        for (Event event : events) {
            Intent intent = EventManager.createEventMessage(event);
            setNotificationId(intent, String.valueOf(notifyId));
            service.sendEvent(intent, event.getAccessToken());
        }
    }
    return true;
}
Example 32
Project: KernelAdiutor-master  File: NavigationActivity.java View source code
private void setShortcuts() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
        return;
    HashMap<Fragment, Integer> openendFragmentsCount = new HashMap<>();
    for (int id : sActualFragments.keySet()) {
        Fragment fragment = sActualFragments.get(id);
        if (fragment == null || fragment.getClass() == SettingsFragment.class)
            continue;
        int opened = Prefs.getInt(fragment.getClass().getSimpleName() + "_opened", 0, this);
        openendFragmentsCount.put(fragment, opened);
    }
    int max = 0;
    for (Map.Entry<Fragment, Integer> map : openendFragmentsCount.entrySet()) {
        if (max < map.getValue()) {
            max = map.getValue();
        }
    }
    int count = 0;
    List<ShortcutInfo> shortcutInfos = new ArrayList<>();
    ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
    shortcutManager.removeAllDynamicShortcuts();
    for (int i = max; i >= 0; i--) {
        for (Map.Entry<Fragment, Integer> map : openendFragmentsCount.entrySet()) {
            if (i == map.getValue()) {
                NavigationFragment navFragment = getNavigationFragment(map.getKey());
                if (navFragment == null)
                    continue;
                if (count == 4)
                    break;
                count++;
                Intent intent = new Intent(this, MainActivity.class);
                intent.setAction(Intent.ACTION_VIEW);
                intent.putExtra("section", navFragment.mFragment.getClass().getCanonicalName());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                ShortcutInfo shortcut = new ShortcutInfo.Builder(this, navFragment.mFragment.getClass().getSimpleName()).setShortLabel(getString(navFragment.mId)).setLongLabel(Utils.strFormat(getString(R.string.open), getString(navFragment.mId))).setIcon(Icon.createWithResource(this, navFragment.mDrawable == 0 ? R.drawable.ic_blank : navFragment.mDrawable)).setIntent(intent).build();
                shortcutInfos.add(shortcut);
            }
        }
    }
    shortcutManager.setDynamicShortcuts(shortcutInfos);
}
Example 33
Project: AndroidChromium-master  File: NotificationBuilderBase.java View source code
/**
     * Creates a public version of the notification to be displayed in sensitive contexts, such as
     * on the lockscreen, displaying just the site origin and badge or generated icon.
     */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected Notification createPublicNotification(Context context) {
    // Use Android's Notification.Builder because we want the default small icon behaviour.
    Notification.Builder builder = new Notification.Builder(context).setContentText(context.getString(org.chromium.chrome.R.string.notification_hidden_text)).setSmallIcon(org.chromium.chrome.R.drawable.ic_chrome);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        // On N, 'subtext' displays at the top of the notification and this looks better.
        builder.setSubText(mOrigin);
    } else {
        // Set origin as title on L & M, because they look odd without one.
        builder.setContentTitle(mOrigin);
        // Hide the timestamp to match Android's default public notifications on L and M.
        builder.setShowWhen(false);
    }
    // Use the badge if provided and SDK supports it, else use a generated icon.
    if (mSmallIconBitmap != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // The Icon class was added in Android M.
        Bitmap publicIcon = mSmallIconBitmap.copy(mSmallIconBitmap.getConfig(), true);
        builder.setSmallIcon(Icon.createWithBitmap(publicIcon));
    } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M && mOrigin != null) {
        // Only set the large icon for L & M because on N(+?) it would add an extra icon on
        // the right hand side, which looks odd without a notification title.
        builder.setLargeIcon(mIconGenerator.generateIconForUrl(mOrigin.toString(), true));
    }
    return builder.build();
}
Example 34
Project: Android-Password-Store-master  File: PasswordStore.java View source code
public void decryptPassword(PasswordItem item) {
    Intent intent = new Intent(this, PgpHandler.class);
    intent.putExtra("NAME", item.toString());
    intent.putExtra("FILE_PATH", item.getFile().getAbsolutePath());
    intent.putExtra("Operation", "DECRYPT");
    // Adds shortcut
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        ShortcutInfo shortcut = new ShortcutInfo.Builder(this, item.getFullPathToParent()).setShortLabel(item.toString()).setLongLabel(item.getFullPathToParent() + item.toString()).setIcon(Icon.createWithResource(this, R.drawable.ic_launcher)).setIntent(// Needs action
        intent.setAction("DECRYPT_PASS")).build();
        shortcutManager.addDynamicShortcuts(Arrays.asList(shortcut));
    }
    startActivityForResult(intent, PgpHandler.REQUEST_CODE_DECRYPT_AND_VERIFY);
}
Example 35
Project: K6nele-master  File: Utils.java View source code
/**
     * Constructs and publishes the list of app shortcuts, one for each combo that is selected for the
     * search panel. The intent behind the shortcut sets AUTO_START=true and sets RESULTS_REWRITES
     * to the list of default rewrites (at creation time), and PROMPT to the list of rewrite names.
     * All other settings (e.g. MAX_RESULTS) depend on the settings at execution time.
     */
@TargetApi(Build.VERSION_CODES.N_MR1)
public static void publishShortcuts(Context context, List<Combo> selectedCombos, Set<String> rewriteTables) {
    ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
    List<ShortcutInfo> shortcuts = new ArrayList<>();
    int maxShortcutCountPerActivity = shortcutManager.getMaxShortcutCountPerActivity();
    int counter = 0;
    // TODO: rewriteTables should be a list (not a set that needs to be sorted)
    String[] names = rewriteTables.toArray(new String[rewriteTables.size()]);
    Arrays.sort(names);
    String rewritesId = TextUtils.join(", ", names);
    for (Combo combo : selectedCombos) {
        Intent intent = new Intent(context, SpeechActionActivity.class);
        intent.setAction(RecognizerIntent.ACTION_WEB_SEARCH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, combo.getLocaleAsStr());
        intent.putExtra(Extras.EXTRA_SERVICE_COMPONENT, combo.getServiceComponent().flattenToShortString());
        if (names.length > 0) {
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, rewritesId);
        }
        intent.putExtra(Extras.EXTRA_RESULT_REWRITES, names);
        intent.putExtra(Extras.EXTRA_AUTO_START, true);
        // Launch the activity so that the existing Kõnele activities are not in the background stack.
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        shortcuts.add(new ShortcutInfo.Builder(context, combo.getId() + rewritesId).setIntent(intent).setShortLabel(combo.getShortLabel()).setLongLabel(combo.getLongLabel() + "; " + rewritesId).setIcon(Icon.createWithBitmap(drawableToBitmap(combo.getIcon(context)))).build());
        counter++;
        // We are only allowed a certain number (5) of shortcuts
        if (counter >= maxShortcutCountPerActivity) {
            break;
        }
    }
    shortcutManager.setDynamicShortcuts(shortcuts);
}
Example 36
Project: AndroidN-ify-master  File: NotificationHooks.java View source code
private static void bindSmallIcon(RemoteViews contentView, Object builder, int color) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Icon mSmallIcon = (Icon) XposedHelpers.getObjectField(builder, "mSmallIcon");
        contentView.setImageViewIcon(R.id.icon, mSmallIcon);
    } else {
        int mSmallIcon = XposedHelpers.getIntField(builder, "mSmallIcon");
        contentView.setImageViewResource(R.id.icon, mSmallIcon);
    }
    processSmallIconColor(contentView, builder, color);
}
Example 37
Project: packages_apps_settings-master  File: BackgroundDataCondition.java View source code
@Override
public Icon getIcon() {
    return Icon.createWithResource(mManager.getContext(), R.drawable.ic_data_saver);
}
Example 38
Project: AnimatorDurationTile-master  File: ToggleAnimatorDuration.java View source code
private void updateTile() {
    final float scale = getAnimatorScale(getContentResolver());
    final Tile tile = getQsTile();
    tile.setIcon(Icon.createWithResource(getApplicationContext(), getIcon(scale)));
    tile.updateTile();
}
Example 39
Project: Blackbulb-master  File: MaskTileService.java View source code
private void updateInactiveTile(Tile tile) {
    Icon inActiveIcon = Icon.createWithResource(getApplicationContext(), R.drawable.ic_qs_night_mode_off);
    tile.setIcon(inActiveIcon);
    tile.setState(Tile.STATE_INACTIVE);
    tile.updateTile();
}
Example 40
Project: loaderviewlibrary-master  File: LoaderImageView.java View source code
@Override
public void setImageIcon(Icon icon) {
    super.setImageIcon(icon);
    loaderController.stopLoading();
}
Example 41
Project: AirPlayer-master  File: AirNotification.java View source code
@SuppressLint("NewApi")
private Action newAction(int iconResId, String title, PendingIntent pi) {
    Icon icon = Icon.createWithResource(mContext, iconResId);
    return new Notification.Action.Builder(icon, title, pi).build();
}