android.app.NotificationManager#IMPORTANCE_LOW源码实例Demo

下面列出了android.app.NotificationManager#IMPORTANCE_LOW 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: your-local-weather   文件: NotificationUtils.java
public static void checkAndCreateNotificationChannel(Context context) {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
        return;
    }
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel notificationChannel = notificationManager.getNotificationChannel("yourLocalWeather");
    boolean createNotification = notificationChannel == null;
    if (!createNotification &&
            ((notificationChannel.getImportance() == NotificationManager.IMPORTANCE_LOW) ||
                    (AppPreference.isVibrateEnabled(context) && (notificationChannel.getVibrationPattern() == null)))) {
        notificationManager.deleteNotificationChannel("yourLocalWeather");
        createNotification = true;
    }
    if (createNotification) {
        NotificationChannel channel = new NotificationChannel("yourLocalWeather",
                context.getString(R.string.notification_channel_name),
                NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription(context.getString(R.string.notification_channel_description));
        channel.setVibrationPattern(isVibrateEnabled(context));
        channel.enableVibration(AppPreference.isVibrateEnabled(context));
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        channel.setSound(null, null);
        notificationManager.createNotificationChannel(channel);
    }
}
 
源代码2 项目: DanDanPlayForAndroid   文件: SmbService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    //创建NotificationChannel
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel channel = new NotificationChannel("com.xyoye.dandanplay.smbservice.playchannel", "SMB服务", NotificationManager.IMPORTANCE_LOW);
        channel.enableVibration(false);
        channel.setVibrationPattern(new long[]{0});
        channel.enableLights(false);
        channel.setSound(null, null);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
    startForeground(NOTIFICATION_ID, buildNotification());
    return super.onStartCommand(intent, flags, startId);
}
 
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel() {
    if (mNotificationManager.getNotificationChannel(CHANNEL_ID) == null) {
        // The user-visible name of the channel.
        CharSequence name = "MediaSession";
        // The user-visible description of the channel.
        String description = "MediaSession and MediaPlayer";
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        // Configure the notification channel.
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        // Sets the notification light color for notifications posted to this
        // channel, if the device supports this feature.
        mChannel.setLightColor(Color.RED);
        mChannel.enableVibration(true);
        mChannel.setVibrationPattern(
                new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        mNotificationManager.createNotificationChannel(mChannel);
        Log.d(TAG, "createChannel: New channel created");
    } else {
        Log.d(TAG, "createChannel: Existing channel reused");
    }
}
 
源代码4 项目: android-auto-update   文件: NotificationHelper.java
public NotificationHelper(Context base) {
    super(base);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "应用更新", NotificationManager.IMPORTANCE_LOW);
        mChannel.setDescription("应用有新版本");
        mChannel.enableLights(true); //是否在桌面icon右上角展示小红点
        getManager().createNotificationChannel(mChannel);
    }
}
 
源代码5 项目: rcloneExplorer   文件: FirebaseMessagingService.java
private void setNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
        channel.setDescription("App updates notification");
        // Register the channel with the system
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}
 
源代码6 项目: Infinity-For-Reddit   文件: SubmitPostService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ((Infinity) getApplication()).getAppComponent().inject(this);

    mAccessToken = intent.getStringExtra(EXTRA_ACCESS_TOKEN);
    subredditName = intent.getStringExtra(EXTRA_SUBREDDIT_NAME);
    title = intent.getStringExtra(EXTRA_TITLE);
    flair = intent.getParcelableExtra(EXTRA_FLAIR);
    isSpoiler = intent.getBooleanExtra(EXTRA_IS_SPOILER, false);
    isNSFW = intent.getBooleanExtra(EXTRA_IS_NSFW, false);
    int postType = intent.getIntExtra(EXTRA_POST_TYPE, EXTRA_POST_TEXT_OR_LINK);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(
                NotificationUtils.CHANNEL_SUBMIT_POST,
                NotificationUtils.CHANNEL_SUBMIT_POST,
                NotificationManager.IMPORTANCE_LOW
        );

        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        manager.createNotificationChannel(serviceChannel);
    }

    if (postType == EXTRA_POST_TEXT_OR_LINK) {
        content = intent.getStringExtra(EXTRA_CONTENT);
        kind = intent.getStringExtra(EXTRA_KIND);
        startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting));
        submitTextOrLinkPost();
    } else if (postType == EXTRA_POST_TYPE_IMAGE) {
        mediaUri = intent.getData();
        startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting_image));
        submitImagePost();
    } else {
        mediaUri = intent.getData();
        startForeground(NotificationUtils.SUBMIT_POST_SERVICE_NOTIFICATION_ID, createNotification(R.string.posting_video));
        submitVideoPost();
    }

    return START_NOT_STICKY;
}
 
源代码7 项目: Rey-MusicPlayer   文件: MusicService.java
private String channelId() {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        CharSequence channelName = "NOTIFICATION_CHANNEL_NAME";
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }
    return NOTIFICATION_CHANNEL_ID;
}
 
源代码8 项目: abnd-track-pomodoro-timer-app   文件: App.java
public void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(
                CHANNEL_ID,
                getResources().getString(R.string.app_name),
                NotificationManager.IMPORTANCE_LOW);

        NotificationManager notificationManager = Objects.requireNonNull(
                getSystemService(NotificationManager.class));

        notificationManager.createNotificationChannel(notificationChannel);
    }
}
 
源代码9 项目: Jockey   文件: PlayerService.java
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannel() {
    NotificationChannel channel = new NotificationChannel(
            NOTIFICATION_CHANNEL_ID,
            getString(R.string.player_notification_channel_name),
            NotificationManager.IMPORTANCE_LOW);

    NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mgr.createNotificationChannel(channel);
}
 
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void registerSession() {
    Resources res = mContext.getResources();
    mNotificationHeight = (int) res
            .getDimension(android.R.dimen.notification_large_icon_height);
    mNotificationWidth = (int) res.getDimension(android.R.dimen.notification_large_icon_width);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(
                App.notificationChannel, "Default",
                NotificationManager.IMPORTANCE_LOW
        );

        mNotificationManager.createNotificationChannel(notificationChannel);

        mNotificationBuilder = new Notification.Builder(mContext, App.notificationChannel)
                .setSmallIcon(R.drawable.notification)
                .setOngoing(true);
    } else {
        mNotificationBuilder = new Notification.Builder(mContext)
                .setSmallIcon(R.drawable.notification)
                .setOngoing(true);

    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
    }

    mNotificationBuilder.setContentIntent(Utilities.getClementineRemotePendingIntent(mContext));

    mNotificationView = new RemoteViews(mContext.getPackageName(), R.layout.notification_small);
    if (mTurnColor) {
        mNotificationView.setInt(R.id.noti, "setBackgroundColor", Color.TRANSPARENT);
        mNotificationView.setImageViewResource(R.id.noti_play_pause, R.drawable.ic_media_play);
        mNotificationView.setImageViewResource(R.id.noti_next, R.drawable.ic_media_next);
    }
    mNotificationBuilder.setContent(mNotificationView);
}
 
源代码11 项目: v9porn   文件: NotificationChannelHelper.java
public static void initChannel(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String channelId = CHANNEL_ID_FOR_DOWNLOAD;
        String channelName = "视频下载";
        int importance = NotificationManager.IMPORTANCE_LOW;
        createNotificationChannel(context, channelId, channelName, importance);
        channelId = CHANNEL_ID_FOR_UPDATE;
        channelName = "应用升级";
        importance = NotificationManager.IMPORTANCE_LOW;
        createNotificationChannel(context, channelId, channelName, importance);
    }
}
 
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel(ReactApplicationContext context) {
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "Media playback", NotificationManager.IMPORTANCE_LOW);
    mChannel.setDescription("Media playback controls");
    mChannel.setShowBadge(false);
    mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    mNotificationManager.createNotificationChannel(mChannel);
}
 
源代码13 项目: xmrwallet   文件: WalletService.java
@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.service_description),
            NotificationManager.IMPORTANCE_LOW);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return CHANNEL_ID;
}
 
源代码14 项目: AsteroidOSSync   文件: SynchronizationService.java
@Override
public void onCreate() {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Synchronization Service", NotificationManager.IMPORTANCE_LOW);
        notificationChannel.setDescription("Connection status");
        notificationChannel.setVibrationPattern(new long[]{0L});
        notificationChannel.setShowBadge(false);
        mNM.createNotificationChannel(notificationChannel);
    }

    mBleMngr = get(getApplication());
    BleManagerConfig cfg = new BleManagerConfig();
    cfg.forceBondDialog = true;
    cfg.taskTimeoutRequestFilter = new TaskTimeoutRequestFilter();
    cfg.defaultScanFilter = new WatchesFilter();
    cfg.enableCrashResolver = true;
    cfg.bondFilter = new BondFilter();
    cfg.alwaysUseAutoConnect = true;
    cfg.useLeTransportForBonding = true;
    if (BuildConfig.DEBUG)
        cfg.loggingEnabled = true;
    mBleMngr.setConfig(cfg);

    mPrefs = getSharedPreferences(MainActivity.PREFS_NAME, Context.MODE_PRIVATE);
    String defaultDevMacAddr = mPrefs.getString(MainActivity.PREFS_DEFAULT_MAC_ADDR, "");
    String defaultLocalName = mPrefs.getString(MainActivity.PREFS_DEFAULT_LOC_NAME, "");

    if(!defaultDevMacAddr.isEmpty()) {
        if(!mBleMngr.hasDevice(defaultDevMacAddr))
            mBleMngr.newDevice(defaultDevMacAddr, defaultLocalName);

        mDevice = mBleMngr.getDevice(defaultDevMacAddr);
        mDevice.setListener_State(SynchronizationService.this);

        mWeatherService = new WeatherService(getApplicationContext(), mDevice);
        mNotificationService = new NotificationService(getApplicationContext(), mDevice);
        mMediaService = new MediaService(getApplicationContext(), mDevice);
        mScreenshotService = new ScreenshotService(getApplicationContext(), mDevice);
        mTimeService = new TimeService(getApplicationContext(), mDevice);
        silentModeService = new SilentModeService(getApplicationContext());

        mDevice.connect();
    }

    updateNotification();
}
 
源代码15 项目: sdl_java_suite   文件: SdlRouterService.java
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void enterForeground(String content, long chronometerLength, boolean ongoing) {
	DebugTool.logInfo("Attempting to enter the foreground - " + System.currentTimeMillis());
	if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB){
		Log.w(TAG, "Unable to start service as foreground due to OS SDK version being lower than 11");
		isForeground = false;
		return;
	}

	Bitmap icon;
	int resourcesIncluded = getResources().getIdentifier("ic_sdl", "drawable", getPackageName());

	if ( resourcesIncluded != 0 ) {  //No additional pylons required
		icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_sdl);
	}
	else {  
		icon = BitmapFactory.decodeResource(getResources(), android.R.drawable.stat_sys_data_bluetooth);
	}
      // Bitmap icon = BitmapFactory.decodeByteArray(SdlLogo.SDL_LOGO_STRING, 0, SdlLogo.SDL_LOGO_STRING.length);

       Notification.Builder builder;
	if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
		builder = new Notification.Builder(this);
	} else {
		builder = new Notification.Builder(this, SDL_NOTIFICATION_CHANNEL_ID);
	}

	if(0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)){ //If we are in debug mode, include what app has the router service open
       	ComponentName name = new ComponentName(this, this.getClass());
       	builder.setContentTitle("SDL: " + name.getPackageName());
       }else{
       	builder.setContentTitle("SmartDeviceLink");
       }
       builder.setTicker("SmartDeviceLink");
       builder.setContentText(content);

      //We should use icon from library resources if available
       int trayId = getResources().getIdentifier("sdl_tray_icon", "drawable", getPackageName());

	if ( resourcesIncluded != 0 ) {  //No additional pylons required
		 builder.setSmallIcon(trayId);
	}
	else {  
		 builder.setSmallIcon(android.R.drawable.stat_sys_data_bluetooth);
	}
       builder.setLargeIcon(icon);
       builder.setOngoing(ongoing);

	// Create an intent that will be fired when the user clicks the notification.
	Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(SDL_NOTIFICATION_FAQS_PAGE));
	PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
	builder.setContentIntent(pendingIntent);

       if(chronometerLength > (FOREGROUND_TIMEOUT/1000) && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
       	//The countdown method is only available in SDKs >= 24
       	// Only add countdown if it is over the min timeout
       	builder.setWhen(chronometerLength + System.currentTimeMillis());
       	builder.setUsesChronometer(true);
       	builder.setChronometerCountDown(true);
       }
       synchronized (NOTIFICATION_LOCK) {
		Notification notification;
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
			notification = builder.getNotification();

		} else {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
				//Now we need to add a notification channel
				NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				if (notificationManager != null) {
					NotificationChannel notificationChannel = new NotificationChannel(SDL_NOTIFICATION_CHANNEL_ID, SDL_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
					notificationChannel.enableLights(false);
					notificationChannel.enableVibration(false);
					notificationManager.createNotificationChannel(notificationChannel);
				} else {
					Log.e(TAG, "Unable to retrieve notification Manager service");
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
						safeStartForeground(FOREGROUND_SERVICE_ID, builder.build());
						stopSelf();	//A valid notification channel must be supplied for SDK 27+
					}
				}

			}
			notification = builder.build();
		}
		if (notification == null) {
			safeStartForeground(FOREGROUND_SERVICE_ID, builder.build());
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
				stopSelf(); //A valid notification must be supplied for SDK 27+
			}
			return;
		}
		safeStartForeground(FOREGROUND_SERVICE_ID, notification);
		isForeground = true;

	}

   }
 
源代码16 项目: android_9.0.0_r45   文件: NotificationComparator.java
private boolean isImportantColorized(NotificationRecord record) {
    if (record.getImportance() < NotificationManager.IMPORTANCE_LOW) {
        return false;
    }
    return record.getNotification().isColorized();
}
 
源代码17 项目: Beginner-Level-Android-Studio-Apps   文件: App.java
private void CreateNotificationChannels() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            //Channel 1 Configuration
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID,
                    "channel 1",NotificationManager.IMPORTANCE_HIGH);
            channel1.setDescription("Test Channel 1");

            //Channel 2 Configuration
            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID,
                    "channel 2",NotificationManager.IMPORTANCE_LOW);
            channel2.setDescription("Test Channel 2");

            //Channel 3 Configuration
            NotificationChannel channel3 = new NotificationChannel(CHANNEL_3_ID,
                    "channel 3",NotificationManager.IMPORTANCE_DEFAULT);
            channel3.setDescription("Test Channel 3");

            //Channel 4 Configuration
            NotificationChannel channel4 = new NotificationChannel(CHANNEL_4_ID,
                    "channel 4",NotificationManager.IMPORTANCE_HIGH);
            channel4.setDescription("Test Channel 4");

            //Channel 5 Configuration
            NotificationChannel channel5 = new NotificationChannel(CHANNEL_5_ID,
                    "channel 5",NotificationManager.IMPORTANCE_HIGH);
            channel5.setDescription("Test Channel 5");




            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
            manager.createNotificationChannel(channel3);
            manager.createNotificationChannel(channel4);
            manager.createNotificationChannel(channel5);

        }

    }
 
源代码18 项目: FreezeYou   文件: NotificationUtils.java
@SuppressLint("ApplySharedPref")
public static void createFUFQuickNotification(Context context, String pkgName, int iconResId, Bitmap bitmap) {

    AppPreferences preferenceManager = new AppPreferences(context);
    boolean notificationBarFreezeImmediately = preferenceManager.getBoolean("notificationBarFreezeImmediately", true);
    String description = notificationBarFreezeImmediately ? context.getString(R.string.freezeImmediately) : context.getString(R.string.disableAEnable);
    Notification.Builder mBuilder = new Notification.Builder(context);
    int mId = pkgName.hashCode();
    String name = getApplicationLabel(context, null, null, pkgName);
    if (!context.getString(R.string.uninstalled).equals(name)) {
        mBuilder.setSmallIcon(iconResId);
        mBuilder.setLargeIcon(bitmap);
        mBuilder.setContentTitle(name);
        mBuilder.setContentText(description);
        mBuilder.setAutoCancel(!preferenceManager.getBoolean("notificationBarDisableClickDisappear", true));
        mBuilder.setOngoing(preferenceManager.getBoolean("notificationBarDisableSlideOut", false));

        Intent intent = new Intent(context, NotificationDeletedReceiver.class).putExtra("pkgName", pkgName);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, mId, intent, 0);
        mBuilder.setDeleteIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "FAUf";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, description, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            if (notificationManager != null)
                notificationManager.createNotificationChannel(channel);
            mBuilder.setChannelId(CHANNEL_ID);
        }
        // Create an Intent for the activity you want to start
        Intent resultIntent;
        PendingIntent resultPendingIntent;
        if (notificationBarFreezeImmediately) {
            resultIntent = new Intent(context, FUFService.class)
                    .putExtra("pkgName", pkgName)
                    .putExtra("single", true)
                    .putExtra("freeze", true);
            resultPendingIntent = PendingIntent.getService(context, mId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            resultIntent = new Intent(context, Freeze.class).putExtra("pkgName", pkgName).putExtra("auto", false);
            resultPendingIntent = PendingIntent.getActivity(context, mId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (mNotificationManager != null) {
            mNotificationManager.notify(mId, mBuilder.getNotification());
            AppPreferences appPreferences = new AppPreferences(context);
            String notifying = appPreferences.getString("notifying", "");
            if (notifying != null && !notifying.contains(pkgName + ",")) {
                appPreferences.put("notifying", notifying + pkgName + ",");
            }
        }
    }
}
 
源代码19 项目: Daedalus   文件: DaedalusVpnService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        switch (intent.getAction()) {
            case ACTION_ACTIVATE:
                activated = true;
                if (Daedalus.getPrefs().getBoolean("settings_notification", true)) {
                    NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

                    NotificationCompat.Builder builder;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
                        manager.createNotificationChannel(channel);
                        builder = new NotificationCompat.Builder(this, CHANNEL_ID);
                    } else {
                        builder = new NotificationCompat.Builder(this);
                    }

                    Intent deactivateIntent = new Intent(StatusBarBroadcastReceiver.STATUS_BAR_BTN_DEACTIVATE_CLICK_ACTION);
                    deactivateIntent.setClass(this, StatusBarBroadcastReceiver.class);
                    Intent settingsIntent = new Intent(StatusBarBroadcastReceiver.STATUS_BAR_BTN_SETTINGS_CLICK_ACTION);
                    settingsIntent.setClass(this, StatusBarBroadcastReceiver.class);
                    PendingIntent pIntent = PendingIntent.getActivity(this, 0,
                            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
                    builder.setWhen(0)
                            .setContentTitle(getResources().getString(R.string.notice_activated))
                            .setDefaults(NotificationCompat.DEFAULT_LIGHTS)
                            .setSmallIcon(R.drawable.ic_security)
                            .setColor(getResources().getColor(R.color.colorPrimary)) //backward compatibility
                            .setAutoCancel(false)
                            .setOngoing(true)
                            .setTicker(getResources().getString(R.string.notice_activated))
                            .setContentIntent(pIntent)
                            .addAction(R.drawable.ic_clear, getResources().getString(R.string.button_text_deactivate),
                                    PendingIntent.getBroadcast(this, 0,
                                            deactivateIntent, PendingIntent.FLAG_UPDATE_CURRENT))
                            .addAction(R.drawable.ic_settings, getResources().getString(R.string.action_settings),
                                    PendingIntent.getBroadcast(this, 0,
                                            settingsIntent, PendingIntent.FLAG_UPDATE_CURRENT));

                    Notification notification = builder.build();

                    manager.notify(NOTIFICATION_ACTIVATED, notification);

                    this.notification = builder;
                }

                Daedalus.initRuleResolver();
                startThread();
                Daedalus.updateShortcut(getApplicationContext());
                if (MainActivity.getInstance() != null) {
                    MainActivity.getInstance().startActivity(new Intent(getApplicationContext(), MainActivity.class)
                            .putExtra(MainActivity.LAUNCH_ACTION, MainActivity.LAUNCH_ACTION_SERVICE_DONE));
                }
                return START_STICKY;
            case ACTION_DEACTIVATE:
                stopThread();
                return START_NOT_STICKY;
        }
    }
    return START_NOT_STICKY;
}
 
源代码20 项目: neverEndingProcessAndroid7-   文件: Notification.java
/**
     * This is the method  called to create the Notification
     */
    public android.app.Notification setNotification(Context context, String title, String text, int icon) {
        if (notificationPendingIntent == null) {
            Intent notificationIntent = new Intent(context, MainActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            // notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            notificationPendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        }

        android.app.Notification notification;

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

        // OREO
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            // Create the NotificationChannel, but only on API 26+ because
            // the NotificationChannel class is new and not in the support library
            CharSequence name = "Permanent Notification";
            //mContext.getString(R.string.channel_name);
            int importance = NotificationManager.IMPORTANCE_LOW;

            String CHANNEL_ID = "uk.ac.shef.oak.channel";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            //String description = mContext.getString(R.string.notifications_description);
            String description = "I would like to receive travel alerts and notifications for:";
            channel.setDescription(description);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
            notification = notificationBuilder
                    //the log is PNG file format with a transparent background
                    .setSmallIcon(icon)
                    .setColor(ContextCompat.getColor(context, R.color.colorAccent))
                    .setContentTitle(title)
                    .setContentText(text)
                    .setContentIntent(notificationPendingIntent)
                    .build();

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notification = new NotificationCompat.Builder(context, "channel")
                    // to be defined in the MainActivity of the app
                    .setSmallIcon(icon)
                    .setContentTitle(title)
//                    .setColor(mContext.getResources().getColor(R.color.colorAccent))
                    .setContentText(text)
                    .setPriority(android.app.Notification.PRIORITY_MIN)
                    .setContentIntent(notificationPendingIntent).build();
        } else {
            notification = new NotificationCompat.Builder(context, "channel")
                    // to be defined in the MainActivity of the app
                    .setSmallIcon(icon)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setPriority(android.app.Notification.PRIORITY_MIN)
                    .setContentIntent(notificationPendingIntent).build();
        }

        return notification;
    }