Java Code Examples for android.app.NotificationManager#createNotificationChannel()

The following examples show how to use android.app.NotificationManager#createNotificationChannel() . 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: MApplication.java    From HaoReader with GNU General Public License v3.0 9 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.O)
private void createChannelIdWeb() {
    //用唯一的ID创建渠道对象
    NotificationChannel firstChannel = new NotificationChannel(channelIdWeb,
            getString(R.string.web_menu),
            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 2
Source File: NotificationUtilites.java    From GotoSleep with GNU General Public License v3.0 6 votes vote down vote up
public static void createNotificationChannel(Context context) {
    // 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) {
        CharSequence name = context.getString(R.string.channel_name);
        String description = context.getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(BEDTIME_CHANNEL_ID, name, importance);
        channel.setDescription(description);
        channel.setBypassDnd(true);
        channel.enableLights(true);
        //channel.enableVibration(true);
        channel.setLightColor(Color.BLUE);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
 
Example 3
Source File: PushService.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Set default channel for Android Oreo or newer version
 * Notice: it isn"t necessary to invoke this method for any Android version before Oreo.
 *
 * @param context   context
 * @param channelId default channel id.
 */
@TargetApi(Build.VERSION_CODES.O)
public static void setDefaultChannelId(Context context, String channelId) {
  DefaultChannelId = channelId;
  if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
    // do nothing for Android versions before Ore
    return;
  }

  try {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence name = context.getPackageName();
    String description = "PushNotification";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    android.app.NotificationChannel channel = new android.app.NotificationChannel(channelId, name, importance);
    channel.setDescription(description);
    notificationManager.createNotificationChannel(channel);
  } catch (Exception ex) {
    LOGGER.w("failed to create NotificationChannel, then perhaps PushNotification doesn't work well on Android O and newer version.");
  }
}
 
Example 4
Source File: AudioService.java    From baby-sleep-sounds with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel()
{
    String channelId = NOTIFICATION_CHANNEL_ID;
    String channelName = getString(R.string.notificationChannelName);
    NotificationChannel chan = new NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_LOW);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager service = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    if(service != null)
    {
        service.createNotificationChannel(chan);
    }
    else
    {
        Log.w(TAG, "Could not get NotificationManager");
    }

    return channelId;
}
 
Example 5
Source File: MediaReaderService.java    From AndroidScreenShare with Apache License 2.0 6 votes vote down vote up
private void initNotificationChannel(){
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
		//创建通知渠道
		CharSequence name = "运行通知";
		String description = "服务运行中";
		String channelId=UNLOCK_NOTIFICATION_CHANNEL_ID;//渠道id
		int importance = NotificationManager.IMPORTANCE_DEFAULT;//重要性级别
		NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
		mChannel.setDescription(description);//渠道描述
		mChannel.enableLights(false);//是否显示通知指示灯
		mChannel.enableVibration(false);//是否振动

		NotificationManager notificationManager = (NotificationManager) getSystemService(
				NOTIFICATION_SERVICE);
		notificationManager.createNotificationChannel(mChannel);//创建通知渠道
	}

}
 
Example 6
Source File: CompatHelperBase.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
public static synchronized String getFileOperationsNotificationsChannelId(Context context)
{
	if (fileOperationsNotificationsChannelId == null)
	{
		fileOperationsNotificationsChannelId = "com.sovworks.eds.FILE_OPERATIONS_CHANNEL2";
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel channel = new NotificationChannel(
				fileOperationsNotificationsChannelId,
				context.getString(R.string.file_operations_notifications_channel_name),
				NotificationManager.IMPORTANCE_LOW
			);
			channel.enableLights(false);
			channel.enableVibration(false);
			NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
			notificationManager.createNotificationChannel(channel);
		}
	}
	return fileOperationsNotificationsChannelId;
}
 
Example 7
Source File: ApplyOnBootService.java    From KernelAdiutor with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
                getString(R.string.apply_on_boot), NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.setSound(null, null);
        notificationManager.createNotificationChannel(notificationChannel);

        Notification.Builder builder = new Notification.Builder(
                this, CHANNEL_ID);
        builder.setContentTitle(getString(R.string.apply_on_boot))
                .setSmallIcon(R.mipmap.ic_launcher);
        startForeground(NotificationId.APPLY_ON_BOOT, builder.build());
    }
}
 
Example 8
Source File: NotificationsService.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    ApplicationLoader.postInitApplication();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String CHANNEL_ID = "push_service_channel";
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"Push Notifications Service",NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
        Intent explainIntent = new Intent("android.intent.action.VIEW");
        explainIntent.setData(Uri.parse("https://github.com/Telegram-FOSS-Team/Telegram-FOSS/blob/master/Notifications.md"));
        PendingIntent explainPendingIntent = PendingIntent.getActivity(this, 0, explainIntent, 0);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentIntent(explainPendingIntent)
                .setShowWhen(false)
                .setOngoing(true)
                .setSmallIcon(R.drawable.notification)
                .setContentText("Push service: tap to learn more").build();
        startForeground(9999,notification);
    }
}
 
Example 9
Source File: NotificationUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * Post a notification to be shown in the status bar.
 *
 * @param tag           A string identifier for this notification.  May be {@code null}.
 * @param id            An identifier for this notification.
 * @param channelConfig The notification channel of config.
 * @param consumer      The consumer of create the builder of notification.
 */
public static void notify(String tag, int id, ChannelConfig channelConfig, Utils.Consumer<NotificationCompat.Builder> consumer) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager nm = (NotificationManager) Utils.getApp().getSystemService(Context.NOTIFICATION_SERVICE);
        //noinspection ConstantConditions
        nm.createNotificationChannel(channelConfig.getNotificationChannel());
    }

    NotificationManagerCompat nmc = NotificationManagerCompat.from(Utils.getApp());

    NotificationCompat.Builder builder = new NotificationCompat.Builder(Utils.getApp());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId(channelConfig.mNotificationChannel.getId());
    }
    consumer.accept(builder);

    nmc.notify(tag, id, builder.build());
}
 
Example 10
Source File: MyService.java    From BadgeForAppIcon with MIT License 5 votes vote down vote up
private void sendIconNumNotification() {
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (nm == null) return;
    String notificationChannelId = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = createNotificationChannel();
        nm.createNotificationChannel(notificationChannel);
        notificationChannelId = notificationChannel.getId();
    }
    Notification notification = null;
    try {
        notification = new NotificationCompat.Builder(this, notificationChannelId)
                .setSmallIcon(getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("title")
                .setContentText("content num: " + count)
                .setTicker("ticker")
                .setAutoCancel(true)
                .setNumber(count)
                .build();
        notification = setIconBadgeNumManager.setIconBadgeNum(getApplication(), notification, count);

        nm.notify(32154, notification);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: NotificationHelper.java    From azure-notificationhubs-android with Apache License 2.0 5 votes vote down vote up
public static void createChannelAndHandleNotifications(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription(NOTIFICATION_CHANNEL_DESCRIPTION);
        channel.setShowBadge(true);

        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
        NotificationsManager.handleNotifications(context, DemoNotificationsHandler.class);
    }
}
 
Example 12
Source File: FFMIntentService.java    From FCM-for-Mojo with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onCreateNotificationChannel(@NonNull NotificationManager notificationManager) {
    NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_PROGRESS,
            getString(R.string.notification_channel_progress_message),
            NotificationManager.IMPORTANCE_LOW);
    channel.enableLights(false);
    channel.enableVibration(false);
    channel.setShowBadge(false);
    notificationManager.createNotificationChannel(channel);
}
 
Example 13
Source File: SleepReminderService.java    From Alarmio with Apache License 2.0 5 votes vote down vote up
/**
 * Refresh the state of the sleepy stuff. This will either show a notification if a notification
 * should be shown, or stop the service if it shouldn't.
 */
public void refreshState() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? powerManager.isInteractive() : powerManager.isScreenOn()) {
        AlarmData nextAlarm = getSleepyAlarm(alarmio);
        if (nextAlarm != null) {
            NotificationCompat.Builder builder;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                if (manager != null)
                    manager.createNotificationChannel(new NotificationChannel("sleepReminder", getString(R.string.title_sleep_reminder), NotificationManager.IMPORTANCE_DEFAULT));

                builder = new NotificationCompat.Builder(this, "sleepReminder");
            } else builder = new NotificationCompat.Builder(this);

            startForeground(540, builder.setContentTitle(getString(R.string.title_sleep_reminder))
                    .setContentText(String.format(getString(R.string.msg_sleep_reminder),
                            FormatUtils.formatUnit(this, (int) TimeUnit.MILLISECONDS.toMinutes(nextAlarm.getNext().getTimeInMillis() - System.currentTimeMillis()))))
                    .setSmallIcon(R.drawable.ic_notification_sleep)
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setCategory(NotificationCompat.CATEGORY_SERVICE)
                    .build());
            return;
        }
    }

    stopForeground(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        stopSelf();
}
 
Example 14
Source File: DownProgressNotify.java    From AndroidDownload with Apache License 2.0 5 votes vote down vote up
public DownProgressNotify(){
    //this.context=context;
    notificationManager = (NotificationManager) x.app().getSystemService(x.app().NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(x.app().getPackageName(), x.app().getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
        channel.enableLights(false);
        channel.enableVibration(false);
        notificationManager.createNotificationChannel(channel);
    }
    downRemoteViews=new HashMap<>();
    downNotification=new HashMap<>();
}
 
Example 15
Source File: TwireApplication.java    From Twire with GNU General Public License v3.0 5 votes vote down vote up
private void initNotificationChannels() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || notificationManager == null) {
        return;
    }

    notificationManager.createNotificationChannel(
            new NotificationChannel(getString(R.string.live_streamer_notification_id), "New Streamer is live", NotificationManager.IMPORTANCE_LOW)
    );

    notificationManager.createNotificationChannel(
            new NotificationChannel(getString(R.string.stream_cast_notification_id), "Stream Playback Control", NotificationManager.IMPORTANCE_DEFAULT)
    );
}
 
Example 16
Source File: NotificationController.java    From MiPushFramework with GNU General Public License v3.0 5 votes vote down vote up
public static NotificationChannel registerChannelIfNeeded(Context context, String packageName) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        return null;
    }

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    String channelId = getChannelIdByPkg(packageName);
    NotificationChannel notificationChannel = manager.getNotificationChannel(channelId);

    if (notificationChannel != null) {
        if (ID_GROUP_APPLICATIONS.equals(notificationChannel.getGroup()) || TextUtils.isEmpty(notificationChannel.getGroup())) {
            manager.deleteNotificationChannel(channelId);
            notificationChannel = null;
        }
    }

    if (notificationChannel == null) {

        CharSequence name = ApplicationNameCache.getInstance().getAppName(context, packageName);
        if (name == null) {
            return null;
        }

        NotificationChannelGroup notificationChannelGroup = createGroupWithPackage(packageName, name);
        manager.createNotificationChannelGroup(notificationChannelGroup);

        notificationChannel = createChannelWithPackage(packageName, name);
        notificationChannel.setGroup(notificationChannelGroup.getId());

        manager.createNotificationChannel(notificationChannel);
    }

    return notificationChannel;

}
 
Example 17
Source File: CheckRecentRun.java    From WhatsApp-Cleaner with MIT License 4 votes vote down vote up
public void sendNotification() {
    Intent mainIntent = new Intent(this, MainActivity.class);
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Notifications";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mChannel.setSound(null, null);
        notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT))
                .setContentTitle("We Miss You!")
                .setContentText("Please clear your WhatsApp Media Clutter.")
                .setTicker("We Miss You! Please Clear Your WhatsApp Media Clutter.")
                .setChannelId(CHANNEL_ID)
                .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                .setSound(null)
                .setLights(Color.GREEN, 3000, 3000)
                .setColor(Color.parseColor("#12921F"))
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                .setAutoCancel(true);

        notificationManager.createNotificationChannel(mChannel);
        notificationManager.notify(notificationId, notificationBuilder.build());  Log.v(TAG, "Notification sent");

    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
                PendingIntent.FLAG_UPDATE_CURRENT))
                .setContentTitle("We Miss You!")
                .setContentText("Please clear your WhatsApp Media Clutter.")
                .setTicker("We Miss You! Please Clear Your WhatsApp Media Clutter.")
                .setPriority(NotificationManager.IMPORTANCE_DEFAULT)
                .setSound(null)
                .setLights(Color.GREEN, 3000, 3000)
                .setColor(Color.parseColor("#12921F"))
                .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                .setAutoCancel(true);
        notificationManager.notify(notificationId, notificationBuilder.build());
        Log.v(TAG, "Notification sent");
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT))
                .setContentTitle("We Miss You!")
                .setContentText("Please clear your WhatsApp Media Clutter.")
                .setTicker("We Miss You! Please Clear Your WhatsApp Media Clutter.")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setSound(null)
                .setLights(Color.GREEN, 3000, 3000)
                .setColor(Color.parseColor("#12921F"))
                .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                .setAutoCancel(true);
        notificationManager.notify(notificationId, notificationBuilder.build());
        Log.v(TAG, "Notification sent");
    }



}
 
Example 18
Source File: PlayerService.java    From AndroidAudioExample with MIT License 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_DEFAULT_CHANNEL_ID, getString(R.string.notification_channel_name), NotificationManagerCompat.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);

        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build();
        audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                .setOnAudioFocusChangeListener(audioFocusChangeListener)
                .setAcceptsDelayedFocusGain(false)
                .setWillPauseWhenDucked(true)
                .setAudioAttributes(audioAttributes)
                .build();
    }

    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mediaSession = new MediaSessionCompat(this, "PlayerService");
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mediaSessionCallback);

    Context appContext = getApplicationContext();

    Intent activityIntent = new Intent(appContext, MainActivity.class);
    mediaSession.setSessionActivity(PendingIntent.getActivity(appContext, 0, activityIntent, 0));

    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null, appContext, MediaButtonReceiver.class);
    mediaSession.setMediaButtonReceiver(PendingIntent.getBroadcast(appContext, 0, mediaButtonIntent, 0));

    exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultRenderersFactory(this), new DefaultTrackSelector(), new DefaultLoadControl());
    exoPlayer.addListener(exoPlayerListener);
    DataSource.Factory httpDataSourceFactory = new OkHttpDataSourceFactory(new OkHttpClient(), Util.getUserAgent(this, getString(R.string.app_name)));
    Cache cache = new SimpleCache(new File(this.getCacheDir().getAbsolutePath() + "/exoplayer"), new LeastRecentlyUsedCacheEvictor(1024 * 1024 * 100)); // 100 Mb max
    this.dataSourceFactory = new CacheDataSourceFactory(cache, httpDataSourceFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
    this.extractorsFactory = new DefaultExtractorsFactory();
}
 
Example 19
Source File: IntentDownloadService.java    From YTPlayer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate() {
    context = getApplicationContext();
    pendingJobs = new ArrayList<>();

    SharedPreferences preferences = getSharedPreferences("appSettings",MODE_PRIVATE);
    useFFMPEGmuxer = preferences.getBoolean("pref_muxer",true);

    PRDownloader.initialize(context);

    /** Create notification channel if not present */
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
        CharSequence name = context.getString(R.string.channel_name);
        String description = context.getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel("channel_01", name, importance);
        notificationChannel.setDescription(description);
        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(notificationChannel);

        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"Download",importance);
        notificationManager.createNotificationChannel(channel);
    }


    /** Setting Power Manager and Wakelock */

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "app:Wakelock");
    wakeLock.acquire();

    Intent notificationIntent = new Intent(context, DownloadActivity.class);
    contentIntent = PendingIntent.getActivity(context,
            0, notificationIntent, 0);

    Intent newintent = new Intent(context, SongBroadCast.class);
    newintent.setAction("com.kpstv.youtube.STOP_SERVICE");
    cancelIntent =
            PendingIntent.getBroadcast(context, 5, newintent, 0);

    setUpdateNotificationTask();
    super.onCreate();
}
 
Example 20
Source File: AltBeaconScannerForegroundService.java    From com.ruuvi.station with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private NotificationCompat.Builder setupNotification() {
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    String channelId = "foreground_scanner_channel";
    if (Build.VERSION.SDK_INT >= 26) {
        CharSequence channelName = "RuuviStation foreground scanner";
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
        try {
            notificationManager.createNotificationChannel(notificationChannel);
        } catch (Exception e) {
            Log.e(TAG, "Could not create notification channel");
        }
    }

    Intent notificationIntent = new Intent(this, StartupActivity.class);

    Bitmap bitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    String notificationText = getString(R.string.scanner_notification_title);
    notificationText = notificationText.replace("..", " every ");
    int scanInterval = new Preferences(getApplicationContext()).getBackgroundScanInterval();
    int min = scanInterval / 60;
    int sec = scanInterval - min * 60;
    if (min > 0) {
        String minutes = getString(R.string.minutes).toLowerCase();
        if (min == 1) {
            minutes = minutes.substring(0, minutes.length() - 1);
        }
        notificationText += min + " " + minutes + ", ";
    }
    if (sec > 0) {
        String seconds = getString(R.string.seconds).toLowerCase();
        if (sec == 1) {
            seconds = seconds.substring(0, seconds.length() - 1);
        }
        notificationText += sec + " " + seconds;
    }
    else {
        notificationText = notificationText.replace(", ", "");
    }

    notification
            = new NotificationCompat.Builder(getApplicationContext(), channelId)
            .setContentTitle(notificationText)
            .setSmallIcon(R.mipmap.ic_launcher_small)
            .setTicker(this.getString(R.string.scanner_notification_ticker))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(this.getString(R.string.scanner_notification_message)))
            .setContentText(this.getString(R.string.scanner_notification_message))
            .setOnlyAlertOnce(true)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setLargeIcon(bitmap)
            .setContentIntent(pendingIntent);

    notification.setSmallIcon(R.drawable.ic_ruuvi_bgscan_icon);

    return notification;
}