android.app.NotificationManager Java Examples

The following examples show how to use android.app.NotificationManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Notifications.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static void lowPredictAlert(Context context, boolean on, String msg) {
    final String type = "bg_predict_alert";
    if (on) {
        if ((Pref.getLong("alerts_disabled_until", 0) < JoH.tsl()) && (Pref.getLong("low_alerts_disabled_until", 0) < JoH.tsl())) {
            OtherAlert(context, type, msg, lowPredictAlertNotificationId, NotificationChannels.BG_PREDICTED_LOW_CHANNEL, false, 20 * 60);
            if (Pref.getBooleanDefaultFalse("speak_alerts")) {
               if (JoH.pratelimit("low-predict-speak", 1800)) SpeechUtil.say(msg, 4000);
            }
        } else {
            Log.ueh(TAG, "Not Low predict alerting due to snooze: " + msg);
        }
    } else {
        NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyMgr.cancel(lowPredictAlertNotificationId);
        UserNotification.DeleteNotificationByType(type);
    }
}
 
Example #2
Source File: MusicService.java    From LLApp with Apache License 2.0 6 votes vote down vote up
@Override
    public void onCreate() {
        super.onCreate();
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(mp -> {
            if (musicModeActivity != null) {
                musicModeActivity.next_img.performClick();
            }
        });
        myApplication = (App) getApplication();
//        handler.sendEmptyMessageDelayed(1002, 200);
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(PAUSE_BROADCAST_NAME);
        filter.addAction(NEXT_BROADCAST_NAME);
        filter.addAction(PRE_BROADCAST_NAME);
        registerReceiver(mConrolBroadcast, filter);
    }
 
Example #3
Source File: Utils.java    From adbwireless with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static void showNotification(Context context, int icon, String text) {
	final Notification notifyDetails = new Notification(icon, text, System.currentTimeMillis());
	notifyDetails.flags = Notification.FLAG_ONGOING_EVENT;

	if (prefsSound(context)) {
		notifyDetails.defaults |= Notification.DEFAULT_SOUND;
	}

	if (prefsVibrate(context)) {
		notifyDetails.defaults |= Notification.DEFAULT_VIBRATE;
	}

	Intent notifyIntent = new Intent(context, adbWireless.class);
	notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
	PendingIntent intent = PendingIntent.getActivity(context, 0, notifyIntent, 0);
	notifyDetails.setLatestEventInfo(context, context.getResources().getString(R.string.noti_title), text, intent);

	if (Utils.mNotificationManager != null) {
		Utils.mNotificationManager.notify(Utils.START_NOTIFICATION_ID, notifyDetails);
	} else {
		Utils.mNotificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
	}

	Utils.mNotificationManager.notify(Utils.START_NOTIFICATION_ID, notifyDetails);
}
 
Example #4
Source File: StepService.java    From LLApp with Apache License 2.0 6 votes vote down vote up
/**
 * 提醒锻炼通知栏
 */
private void remindNotify() {

    //设置点击跳转
    Intent hangIntent = new Intent(this, RunActivity.class);
    PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    String plan = this.getSharedPreferences("share_date", Context.MODE_MULTI_PROCESS).getString("planWalk_QTY", "7000");
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle("今日步数" + CURRENT_STEP + " 步")
            .setContentText("距离目标还差" + (Integer.valueOf(plan) - CURRENT_STEP) + "步,加油!")
            .setContentIntent(hangPendingIntent)
            .setTicker(getResources().getString(R.string.app_name) + "提醒您开始锻炼了")//通知首次出现在通知栏,带上升动画效果的
            .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示
            .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
            .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
            .setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
            .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
            //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
            .setSmallIcon(R.mipmap.logo);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNotificationManager.notify(notify_remind_id, mBuilder.build());
}
 
Example #5
Source File: MetionsPageUpTask.java    From YiBo with Apache License 2.0 6 votes vote down vote up
private void addToAdapter() {
	List<com.cattong.entity.Status> listNewBlog = adapter.getListNewBlogs();
	int cacheSize = listNewBlog.size();
	//如果通知已经存在;
	if (cacheSize > 0) {
		NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notiManager.cancel(adapter.getAccount().getAccountId().intValue() * 100 + Skeleton.TYPE_MENTION);
	}

	if (cacheSize > 0 &&
		listNewBlog.get(cacheSize - 1) instanceof LocalStatus
	) {
		cacheSize--;
	}

	adapter.refresh();
	if (!isAutoUpdate && !isEmptyAdapter) {
		Toast.makeText(
			adapter.getContext(),
			adapter.getContext().getString(R.string.msg_refresh_metion, cacheSize),
			Toast.LENGTH_LONG
		).show();
	}
}
 
Example #6
Source File: PermissionUtils.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
public void needNotificationPolicy(@NonNull final Activity act) {
    if (act.isDestroyed())
        return;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return;
    }
    NotificationManager nm = (NotificationManager) act.getSystemService(Context.NOTIFICATION_SERVICE);
    pNotPolicy = nm.isNotificationPolicyAccessGranted();
    if (!pNotPolicy) {
        Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);

        PackageManager packageManager = act.getPackageManager();
        if (intent.resolveActivity(packageManager) != null) {
            act.startActivity(intent);
        } else {
            ActivityCompat.requestPermissions(act, new String[]{Manifest.permission.ACCESS_NOTIFICATION_POLICY}, 0);
        }
    }

}
 
Example #7
Source File: NotificationUtils.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
/**
 * 文本消息
 *
 * @param notifyId      消息ID
 * @param title         标题
 * @param summary       内容
 * @param ticker        出现消息时状态栏的提示文字
 * @param pendingIntent 点击后的intent
 */
public static void setMessageNotification(Context context, int notifyId, int smallIconId, CharSequence title, CharSequence summary, CharSequence ticker, PendingIntent pendingIntent) {
    NotificationCompat.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder = new NotificationCompat.Builder(context, ID_HIGH_CHANNEL);
    } else {
        builder = new NotificationCompat.Builder(context);
    }
    builder.setSmallIcon(smallIconId)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.dk_doraemon))
            .setContentTitle(title)
            .setContentText(summary)
            .setAutoCancel(true)
            .setProgress(0, 0, false);// Removes the progress bar
    if (!TextUtils.isEmpty(ticker)) {
        builder.setTicker(ticker);
    }
    if (pendingIntent != null) {
        builder.setContentIntent(pendingIntent);
    } else {
        builder.setContentIntent(PendingIntent.getBroadcast(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
    }
    NotificationManager manager = createNotificationManager(context);
    manager.notify(notifyId, builder.build());
}
 
Example #8
Source File: NotificationUtils.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
/**
 * 设置下载进度通知
 *
 * @param notifyId      消息ID
 * @param title         标题
 * @param ticker        出现消息时状态栏的提示文字
 * @param progress      进度(0-100)
 * @param pendingIntent 点击后的intent
 */
public static void setProgressNotification(Context context, int notifyId, CharSequence title, CharSequence ticker, int progress, PendingIntent pendingIntent) {
    NotificationCompat.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder = new NotificationCompat.Builder(context, ID_HIGH_CHANNEL);
    } else {
        builder = new NotificationCompat.Builder(context);
    }
    builder.setSmallIcon(android.R.drawable.stat_sys_download)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.dk_doraemon))
            .setContentTitle(title)
            .setProgress(100, progress, progress == 0)
            .setOngoing(progress < 100)
            .setAutoCancel(progress == 100);
    if (pendingIntent != null) {
        builder.setContentIntent(pendingIntent);
    } else {
        builder.setContentIntent(PendingIntent.getBroadcast(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
    }
    if (!TextUtils.isEmpty(ticker)) {
        builder.setTicker(ticker);
    }
    NotificationManager manager = createNotificationManager(context);
    manager.notify(notifyId, builder.build());
}
 
Example #9
Source File: MApplication.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.O)
private void createChannelIdAudioBook() {
    //用唯一的ID创建渠道对象
    NotificationChannel firstChannel = new NotificationChannel(channelIdAudioBook,
            getString(R.string.audio_book),
            NotificationManager.IMPORTANCE_LOW);
    //初始化channel
    firstChannel.enableLights(false);
    firstChannel.enableVibration(false);
    firstChannel.setSound(null, null);
    //向notification manager 提交channel
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(firstChannel);
    }
}
 
Example #10
Source File: NotificationUtils.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
static NotificationCompat.Builder buildNotification(NotificationManagerCompat notificationManager,
                                                    Context context, String title, String content,
                                                    String summary, String channelId, String channelName,
                                                    String group, int color) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    return new NotificationCompat.Builder(context.getApplicationContext(), channelId)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(R.drawable.ic_notification)
            .setColor(color)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .setSummaryText(summary)
                    .bigText(content))
            .setGroup(group)
            .setAutoCancel(true);
}
 
Example #11
Source File: UpdateUtils.java    From freemp with Apache License 2.0 6 votes vote down vote up
private void buildNotification(String title, String text, PendingIntent pIntent, int id) {
    if (TextUtils.equals("", title) && TextUtils.equals("", text)) {
        return;
    }
    // if you don't use support library, change NotificationCompat on Notification
    Notification noti = new NotificationCompat.Builder(context)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.drawable.freemp)//change this on your freemp
            .setContentIntent(pIntent).build();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    // hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(id, noti);
}
 
Example #12
Source File: MainActivity.java    From habpanelviewer with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onPause() {
    unbindService(mSC);
    if (mService != null) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("de.vier_bier.habpanelviewer.status", "Status", NotificationManager.IMPORTANCE_MIN);
            channel.enableLights(false);
            channel.setSound(null, null);
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "de.vier_bier.habpanelviewer.status");
        builder.setSmallIcon(R.drawable.logo);
        mService.startForeground(42, builder.build());
    }

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    boolean pauseWebview = prefs.getBoolean(Constants.PREF_PAUSE_WEBVIEW, false);
    if (pauseWebview && !((PowerManager) getSystemService(POWER_SERVICE)).isInteractive()) {
        mWebView.pause();
    }
    super.onPause();
}
 
Example #13
Source File: GcmIntentService.java    From MobileShoppingAssistant-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Put the message into a notification and post it.
 * This is just one simple example of what you might choose to do with
 * a GCM message.
 * @param msg is the message to display in the notification.
 */
private  void sendNotification(final String msg) {
    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("MobileAssistant GCM Notification")
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(msg))
                    .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
 
Example #14
Source File: C2DMRegistrationReceiver.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
public void createNotification(Context context, String registrationId) {
	NotificationManager notificationManager = (NotificationManager) context
			.getSystemService(Context.NOTIFICATION_SERVICE);
	Notification notification = new Notification(R.drawable.icon,
			"Registration successful", System.currentTimeMillis());
	// Hide the notification after its selected
	notification.flags |= Notification.FLAG_AUTO_CANCEL;

	Intent intent = new Intent(context, RegistrationResultActivity.class);
	intent.putExtra("registration_id", registrationId);
	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
			intent, 0);
	notification.setLatestEventInfo(context, "Registration",
			"Successfully registered", pendingIntent);
	notificationManager.notify(0, notification);
}
 
Example #15
Source File: OnekeyShare.java    From -Android_ShareSDK_Example_Wechat with MIT License 6 votes vote down vote up
private void showNotification(long cancelTime, String text) {
	try {
		Context app = getContext().getApplicationContext();
		NotificationManager nm = (NotificationManager) app
				.getSystemService(Context.NOTIFICATION_SERVICE);
		final int id = Integer.MAX_VALUE / 13 + 1;
		nm.cancel(id);

		long when = System.currentTimeMillis();
		Notification notification = new Notification(notifyIcon, text, when);
		PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(), 0);
		notification.setLatestEventInfo(app, notifyTitle, text, pi);
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		nm.notify(id, notification);

		if (cancelTime > 0) {
			Message msg = new Message();
			msg.what = MSG_CANCEL_NOTIFY;
			msg.obj = nm;
			msg.arg1 = id;
			UIHandler.sendMessageDelayed(msg, cancelTime, this);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #16
Source File: NotificationListenerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * {@hide}
 */
public static String importanceToString(int importance) {
    switch (importance) {
        case NotificationManager.IMPORTANCE_UNSPECIFIED:
            return "UNSPECIFIED";
        case NotificationManager.IMPORTANCE_NONE:
            return "NONE";
        case NotificationManager.IMPORTANCE_MIN:
            return "MIN";
        case NotificationManager.IMPORTANCE_LOW:
            return "LOW";
        case NotificationManager.IMPORTANCE_DEFAULT:
            return "DEFAULT";
        case NotificationManager.IMPORTANCE_HIGH:
        case NotificationManager.IMPORTANCE_MAX:
            return "HIGH";
        default:
            return "UNKNOWN(" + String.valueOf(importance) + ")";
    }
}
 
Example #17
Source File: ReminderReceiver.java    From YCNotification with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "ReminderReceiver");
    //Calendar now = GregorianCalendar.getInstance();
    Notification.Builder mBuilder = new Notification.Builder(context)
                    .setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("广播接受者标题,小杨")
                    .setContentText("广播接受者内容,扯犊子")
                    .setAutoCancel(true);

    Log.i(TAG, "onReceive: intent" + intent.getClass().getName());
    Intent resultIntent = new Intent(context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    //将该Activity添加为栈顶
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());
}
 
Example #18
Source File: NotificationUtil.java    From user-interface-samples with Apache License 2.0 5 votes vote down vote up
public static String createNotificationChannel(
        Context context,
        MockDatabase.MockNotificationData mockNotificationData) {

    // NotificationChannels are required for Notifications on O (API 26) and above.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        // The id of the channel.
        String channelId = mockNotificationData.getChannelId();

        // The user-visible name of the channel.
        CharSequence channelName = mockNotificationData.getChannelName();
        // The user-visible description of the channel.
        String channelDescription = mockNotificationData.getChannelDescription();
        int channelImportance = mockNotificationData.getChannelImportance();
        boolean channelEnableVibrate = mockNotificationData.isChannelEnableVibrate();
        int channelLockscreenVisibility =
                mockNotificationData.getChannelLockscreenVisibility();

        // Initializes NotificationChannel.
        NotificationChannel notificationChannel =
                new NotificationChannel(channelId, channelName, channelImportance);
        notificationChannel.setDescription(channelDescription);
        notificationChannel.enableVibration(channelEnableVibrate);
        notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

        // Adds NotificationChannel to system. Attempting to create an existing notification
        // channel with its original values performs no operation, so it's safe to perform the
        // below sequence.
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);

        return channelId;
    } else {
        // Returns null for pre-O (26) devices.
        return null;
    }
}
 
Example #19
Source File: CaptchaDecoratorService.java    From nevo-decorators-sms-captchas with GNU General Public License v3.0 5 votes vote down vote up
private void createNotificationChannels() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channelNormal = new NotificationChannel(NOTIFICATION_CHANNEL_CAPTCHA_NORMAL, getString(R.string.captcha_service_notification_channel_name), NotificationManager.IMPORTANCE_HIGH);
        NotificationChannel channelSilent = new NotificationChannel(NOTIFICATION_CHANNEL_CAPTCHA_SILENT, getString(R.string.captcha_service_notification_channel_name), NotificationManager.IMPORTANCE_LOW);

        ArrayList<NotificationChannel> notificationChannels = new ArrayList<>();
        notificationChannels.add(channelNormal);
        notificationChannels.add(channelSilent);

        for (String packageName : TARGET_PACKAGES)
            if (PackageUtils.hasPackageInstalled(this ,packageName))
                createNotificationChannels(packageName, notificationChannels);
    }
}
 
Example #20
Source File: FindPhoneActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create a notification with an action to toggle an alarm on the phone.
    Intent toggleAlarmOperation = new Intent(this, FindPhoneService.class);
    toggleAlarmOperation.setAction(FindPhoneService.ACTION_TOGGLE_ALARM);
    PendingIntent toggleAlarmIntent = PendingIntent.getService(this, 0, toggleAlarmOperation,
            PendingIntent.FLAG_CANCEL_CURRENT);
    Action alarmAction = new Action(R.drawable.alarm_action_icon, "", toggleAlarmIntent);
    // This intent turns off the alarm if the user dismisses the card from the wearable.
    Intent cancelAlarmOperation = new Intent(this, FindPhoneService.class);
    cancelAlarmOperation.setAction(FindPhoneService.ACTION_CANCEL_ALARM);
    PendingIntent cancelAlarmIntent = PendingIntent.getService(this, 0, cancelAlarmOperation,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // Use a spannable string for the notification title to resize it.
    SpannableString title = new SpannableString(getString(R.string.app_name));
    title.setSpan(new RelativeSizeSpan(0.85f), 0, title.length(), Spannable.SPAN_POINT_MARK);
    notification = new Notification.Builder(this)
            .setContentTitle(title)
            .setContentText(getString(R.string.turn_alarm_on))
            .setSmallIcon(R.drawable.ic_launcher)
            .setVibrate(new long[] {0, 50})  // Vibrate to bring card to top of stream.
            .setDeleteIntent(cancelAlarmIntent)
            .extend(new Notification.WearableExtender()
                    .addAction(alarmAction)
                    .setContentAction(0)
                    .setHintHideIcon(true))
            .setLocalOnly(true)
            .setPriority(Notification.PRIORITY_MAX);
    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
            .notify(FIND_PHONE_NOTIFICATION_ID, notification.build());

    finish();
}
 
Example #21
Source File: Notifications.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
static private void createNotificationChannel(String channelId) {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription(channelId);
        NotificationManager notificationManager = Game.instance().getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
 
Example #22
Source File: NotificationComparator.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private boolean isImportantOngoing(NotificationRecord record) {
    if (!isOngoing(record)) {
        return false;
    }

    if (record.getImportance() < NotificationManager.IMPORTANCE_LOW) {
        return false;
    }

    return isCall(record) || isMediaNotification(record);
}
 
Example #23
Source File: EarthBackgroundService.java    From earth with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressLint("WakelockTimeout")
public void onCreate() {
    super.onCreate();

    syncer = new EarthSyncImpl(this);

    nm = NotificationManagerCompat.from(this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        final NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL,
                getString(R.string.background_channel), NotificationManager.IMPORTANCE_MIN);
        channel.enableLights(false);
        channel.enableVibration(false);
        channel.setShowBadge(false);
        nm.createNotificationChannel(channel);
    }

    startForeground(NOTIFICATION_ID, createNotification().build());

    final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    if (pm != null) {
        wakeLock = pm.newWakeLock(PARTIAL_WAKE_LOCK, "earth:background");
        wakeLock.acquire();
    }

    handlerThread = new HandlerThread("sync");
    handlerThread.start();

    handler = new Handler(handlerThread.getLooper());

    handler.post(this::run);
}
 
Example #24
Source File: notificationReceiver.java    From HAPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent arg1) {
    RealmManager realmManager = new RealmManager();

    Bundle bundle = arg1.getExtras();
    switch (bundle.getString("NOTIFICATION_TYPE","")){
        case "newTemp":
            ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(55);  //Kills the notification

            Gson gson = new GsonBuilder().create();
            TempBasal suggestedTemp = gson.fromJson(bundle.getString("SUGGESTED_BASAL", ""), TempBasal.class);
            pumpAction.setTempBasal(suggestedTemp, realmManager.getRealm());   //Action the suggested Temp

            Notifications.clear("updateCard");                                                  //Clears info card on current Basal
            break;
        case "setTemp":
            ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(56);  //Kills the notification
            break;
        case "NEW_INSULIN_UPDATE":
            Notifications.newInsulinUpdate(realmManager.getRealm());
            break;
        case "RUN_OPENAPS":
            Intent apsIntent = new Intent(MainApp.instance(), APSService.class);
            MainApp.instance().startService(apsIntent);
            break;
        case "CANCEL_TBR":
            pumpAction.cancelTempBasal(realmManager.getRealm());
            break;
    }

    realmManager.closeRealm();
}
 
Example #25
Source File: MageApplication.java    From mage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();

	//This ensures the singleton is created with the correct context, which needs to be the
	//application context
	DaoStore.getInstance(this.getApplicationContext());
	LayerHelper.getInstance(this.getApplicationContext());
	StaticFeatureHelper.getInstance(this.getApplicationContext());

	ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

	HttpClientManager.initialize(this);

	// setup the screen unlock stuff
	registerReceiver(ScreenChangeReceiver.getInstance(), new IntentFilter(Intent.ACTION_SCREEN_ON));

	registerActivityLifecycleCallbacks(this);

	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
	int dayNightTheme = preferences.getInt(getResources().getString(R.string.dayNightThemeKey), getResources().getInteger(R.integer.dayNightThemeDefaultValue));
	AppCompatDelegate.setDefaultNightMode(dayNightTheme);

	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		NotificationChannel channel = new NotificationChannel(MAGE_NOTIFICATION_CHANNEL_ID,"MAGE", NotificationManager.IMPORTANCE_LOW);
		channel.setShowBadge(true);
		notificationManager.createNotificationChannel(channel);

		NotificationChannel observationChannel = new NotificationChannel(MAGE_OBSERVATION_NOTIFICATION_CHANNEL_ID,"MAGE Observations", NotificationManager.IMPORTANCE_HIGH);
		observationChannel.setShowBadge(true);
		notificationManager.createNotificationChannel(observationChannel);
	}
}
 
Example #26
Source File: AlertWindowNotification.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
AlertWindowNotification(WindowManagerService service, String packageName) {
    mService = service;
    mPackageName = packageName;
    mNotificationManager =
            (NotificationManager) mService.mContext.getSystemService(NOTIFICATION_SERVICE);
    mNotificationTag = CHANNEL_PREFIX + mPackageName;
    mRequestCode = sNextRequestCode++;
    mIconUtilities = new IconUtilities(mService.mContext);
}
 
Example #27
Source File: MediaNotificationManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
public MediaNotificationManager(MusicService service) {
    mService = service;

    String pkg = mService.getPackageName();
    PendingIntent playIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    PendingIntent pauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    PendingIntent nextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    PendingIntent prevIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);

    mPlayAction = new Notification.Action(R.drawable.ic_play_arrow_white_24dp,
            mService.getString(R.string.label_play), playIntent);
    mPauseAction = new Notification.Action(R.drawable.ic_pause_white_24dp,
            mService.getString(R.string.label_pause), pauseIntent);
    mNextAction = new Notification.Action(R.drawable.ic_skip_next_white_24dp,
            mService.getString(R.string.label_next), nextIntent);
    mPrevAction = new Notification.Action(R.drawable.ic_skip_previous_white_24dp,
            mService.getString(R.string.label_previous), prevIntent);

    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_NEXT);
    filter.addAction(ACTION_PAUSE);
    filter.addAction(ACTION_PLAY);
    filter.addAction(ACTION_PREV);

    mService.registerReceiver(this, filter);


    mNotificationManager = (NotificationManager) mService
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}
 
Example #28
Source File: TimedNotificationPublisher.java    From OsmGo with MIT License 5 votes vote down vote up
/**
 * Restore and present notification
 */
public void onReceive(Context context, Intent intent) {
  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  Notification notification = intent.getParcelableExtra(NOTIFICATION_KEY);
  int id = intent.getIntExtra(LocalNotificationManager.NOTIFICATION_INTENT_KEY, Integer.MIN_VALUE);
  if (id == Integer.MIN_VALUE) {
    Log.e(LogUtils.getPluginTag("LN"), "No valid id supplied");
  }
  notificationManager.notify(id, notification);
  rescheduleNotificationIfNeeded(context, intent, id);
}
 
Example #29
Source File: MessagingBuilder.java    From decorator-wechat with Apache License 2.0 5 votes vote down vote up
private void showDebugNotification(final Conversation convs, final @Nullable String summary) {
	final StringBuilder bigText = new StringBuilder().append(convs.summary).append("\nT:").append(convs.ticker);
	final String[] messages = convs.ext != null ? convs.ext.getMessages() : null;
	if (messages != null) for (final String msg : messages) bigText.append("\n").append(msg);
	final Builder n = new Builder(mContext).setSmallIcon(android.R.drawable.stat_sys_warning)
			.setContentTitle(convs.key).setContentText(convs.ticker).setSubText(summary).setShowWhen(true)
			.setStyle(new BigTextStyle().setBigContentTitle(convs.title).bigText(bigText.toString()));
	if (SDK_INT >= O) n.setChannelId("Debug");
	requireNonNull(mContext.getSystemService(NotificationManager.class))
			.notify(convs.key != null ? convs.key.hashCode() : convs.title.hashCode(), n.build());
}
 
Example #30
Source File: Notifications.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void lowPredictAlert(Context context, boolean on, String msg) {
    final String type = "bg_predict_alert";
    if (on) {
        if ((Pref.getLong("alerts_disabled_until", 0) < JoH.tsl()) && (Pref.getLong("low_alerts_disabled_until", 0) < JoH.tsl())) {
            OtherAlert(context, type, msg, lowPredictAlertNotificationId, false,  20 * 60);
        } else {
            Log.ueh(TAG, "Not Low predict alerting due to snooze: " + msg);
        }
    } else {
        NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyMgr.cancel(lowPredictAlertNotificationId);
        UserNotification.DeleteNotificationByType(type);
    }
}