Example usage for android.app NotificationManager cancel

List of usage examples for android.app NotificationManager cancel

Introduction

In this page you can find the example usage for android.app NotificationManager cancel.

Prototype

public void cancel(String tag, int id) 

Source Link

Document

Cancel a previously shown notification.

Usage

From source file:org.wso2.iot.agent.activities.AlreadyRegisteredActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    if (requestCode == 110) {
        List<String> missingPermissions = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                missingPermissions.add(permissions[i]);
            }/*from   ww  w .  j av  a 2s .  co  m*/
        }
        if (!missingPermissions.isEmpty()) {
            Log.w(TAG, "Permissions not granted: " + missingPermissions.toString());
        }
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(Constants.PERMISSION_MISSING, Constants.PERMISSION_MISSING_NOTIFICATION_ID);
    }
}

From source file:org.wso2.iot.agent.activities.AlreadyRegisteredActivity.java

@Override
protected void onResume() {
    super.onResume();

    if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "Calling onResume");
    }//from  w ww.  j  av  a2 s. c om

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            int locationSetting = Settings.Secure.getInt(context.getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
            if (locationSetting != 0) {
                NotificationManager mNotificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.cancel(Constants.LOCATION_DISABLED,
                        Constants.LOCATION_DISABLED_NOTIFICATION_ID);
            }
        } catch (Settings.SettingNotFoundException e) {
            Log.w(TAG, "Location setting is not available on this device");
        }
    }
    if (Preference.hasPreferenceKey(context, Constants.PreferenceFlag.LAST_SERVER_CALL)) {
        lastSyncMillis = Preference.getLong(context, Constants.PreferenceFlag.LAST_SERVER_CALL);
    }
    updateSyncText();
    IntentFilter filter = new IntentFilter(Constants.SYNC_BROADCAST_ACTION);
    registerReceiver(syncUpdateReceiver, filter);

    mHandler = new Handler();
    mTimer = new Timer();
    mTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    updateSyncText();
                }
            });
        }
    }, DELAY_TIME, PERIOD_TIME);
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private void clearMissingKeyNotification(Account account) {
    NotificationManager mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(account.name, Constants.NOTIF_MISSING_KEY);
}

From source file:org.wso2.iot.agent.activities.AlreadyRegisteredActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_already_registered);

    textViewLastSync = (TextView) findViewById(R.id.textViewLastSync);
    imageViewRefresh = (ImageView) findViewById(R.id.imageViewRefresh);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class);
    context = this;
    DeviceInfo info = new DeviceInfo(context);
    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        if (extras.containsKey(getResources().getString(R.string.intent_extra_fresh_reg_flag))) {
            isFreshRegistration = extras
                    .getBoolean(getResources().getString(R.string.intent_extra_fresh_reg_flag));
        }/*w  ww . j  a va2 s  .c om*/
    }
    String registrationId = Preference.getString(context, Constants.PreferenceFlag.REG_ID);

    if (registrationId != null && !registrationId.isEmpty()) {
        regId = registrationId;
    } else {
        regId = info.getDeviceId();
    }

    if (isFreshRegistration) {
        Preference.putBoolean(context, Constants.PreferenceFlag.REGISTERED, true);
        if (!isDeviceAdminActive()) {
            startEvents();
        }
        // In FCM, for fresh registrations, the initial FCM notification has been ignored
        // purposely to avoid calling the server during enrollment flow and causing threading
        // issues. Therefore after initial enrollment, pending operations is called manually.
        if (Constants.NOTIFIER_FCM
                .equals(Preference.getString(context, Constants.PreferenceFlag.NOTIFIER_TYPE))) {
            MessageProcessor messageProcessor = new MessageProcessor(context);
            try {
                if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED)) {
                    messageProcessor.getMessages();
                }
            } catch (AndroidAgentException e) {
                Log.e(TAG, "Failed to perform operation", e);
            }
        }
        isFreshRegistration = false;
    }

    RelativeLayout relativeLayoutSync = (RelativeLayout) findViewById(R.id.layoutSync);
    relativeLayoutSync.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED) && isDeviceAdminActive()) {
                syncWithServer();
            }
        }
    });

    RelativeLayout relativeLayoutDeviceInfo = (RelativeLayout) findViewById(R.id.layoutDeviceInfo);
    relativeLayoutDeviceInfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadDeviceInfoActivity();
        }
    });

    RelativeLayout relativeLayoutChangePIN = (RelativeLayout) findViewById(R.id.layoutChangePIN);
    relativeLayoutChangePIN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadPinCodeActivity();
        }
    });

    RelativeLayout relativeLayoutRegistration = (RelativeLayout) findViewById(R.id.layoutRegistration);
    if (Constants.HIDE_UNREGISTER_BUTTON) {
        relativeLayoutRegistration.setVisibility(View.GONE);
    } else {
        relativeLayoutRegistration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUnregisterDialog();
            }
        });
    }

    TextView textViewAgentVersion = (TextView) findViewById(R.id.textViewVersion);
    String versionText = BuildConfig.BUILD_TYPE + " v" + BuildConfig.VERSION_NAME + " ("
            + BuildConfig.VERSION_CODE + ") ";
    textViewAgentVersion.setText(versionText);

    if (Build.VERSION.SDK_INT >= 23) {
        List<String> missingPermissions = new ArrayList<>();

        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.READ_PHONE_STATE);
        }
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        // This is to handle permission obtaining for Android N devices where operations such
        // as mute that can cause a device to go into "do not disturb" will need additional
        // permission. Added here as well to support already enrolled devices to optain the
        // permission without reenrolling.
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M
                && !devicePolicyManager.isProfileOwnerApp(Constants.AGENT_PACKAGE)
                && notificationManager != null && !notificationManager.isNotificationPolicyAccessGranted()) {
            CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context,
                    getResources().getString(R.string.dialog_do_not_distrub_title),
                    getResources().getString(R.string.dialog_do_not_distrub_message),
                    getResources().getString(R.string.ok), doNotDisturbClickListener);
        }

        if (missingPermissions.isEmpty()) {
            NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.cancel(Constants.PERMISSION_MISSING,
                    Constants.PERMISSION_MISSING_NOTIFICATION_ID);
        } else {
            ActivityCompat.requestPermissions(AlreadyRegisteredActivity.this,
                    missingPermissions.toArray(new String[missingPermissions.size()]), 110);
        }
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            int locationSetting = Settings.Secure.getInt(context.getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
            if (locationSetting == 0) {
                Intent enableLocationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(enableLocationIntent);
                Toast.makeText(context, R.string.msg_need_location, Toast.LENGTH_LONG).show();
            }
        } catch (Settings.SettingNotFoundException e) {
            Log.w(TAG, "Location setting is not available on this device");
        }
    }

    boolean isRegistered = Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED);
    if (isRegistered) {
        if (CommonUtils.isNetworkAvailable(context)) {
            String serverIP = Constants.DEFAULT_HOST;
            String prefIP = Preference.getString(context, Constants.PreferenceFlag.IP);
            if (prefIP != null) {
                serverIP = prefIP;
            }
            regId = Preference.getString(context, Constants.PreferenceFlag.REG_ID);

            if (regId != null) {
                if (serverIP != null && !serverIP.isEmpty()) {
                    ServerConfig utils = new ServerConfig();
                    utils.setServerIP(serverIP);
                    if (utils.getHostFromPreferences(context) != null
                            && !utils.getHostFromPreferences(context).isEmpty()) {
                        CommonUtils.callSecuredAPI(AlreadyRegisteredActivity.this,
                                utils.getAPIServerURL(context) + Constants.DEVICES_ENDPOINT + regId
                                        + Constants.IS_REGISTERED_ENDPOINT,
                                HTTP_METHODS.GET, null, AlreadyRegisteredActivity.this,
                                Constants.IS_REGISTERED_REQUEST_CODE);
                    } else {
                        try {
                            CommonUtils.clearAppData(context);
                        } catch (AndroidAgentException e) {
                            String msg = "Device already dis-enrolled.";
                            Log.e(TAG, msg, e);
                        }
                        loadInitialActivity();
                    }
                } else {
                    Log.e(TAG, "There is no valid IP to contact server");
                }
            }
        } else {
            if (!Constants.HIDE_ERROR_DIALOG) {
                CommonDialogUtils.showNetworkUnavailableMessage(AlreadyRegisteredActivity.this);
            }
        }
    } else {
        loadInitialActivity();
    }
}

From source file:com.sentaroh.android.TaskAutomation.TaskExecutor.java

final static private void showMessageNotification(TaskManagerParms taskMgrParms, EnvironmentParms envParms,
        CommonUtilities util, TaskResponse tr, String m_text, int led_color, int led_on, int led_off) {
    NotificationManager nm = (NotificationManager) taskMgrParms.context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder nb = new NotificationCompat.Builder(taskMgrParms.context);
    nm.cancel("MSG", taskMgrParms.msgNotificationId);
    Intent in = new Intent();
    PendingIntent pi = PendingIntent.getActivity(taskMgrParms.context, 0, in,
            PendingIntent.FLAG_CANCEL_CURRENT);
    pi.cancel();//from w w w .ja va2s . c om
    nb.setContentIntent(pi).setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
            .setOngoing(false).setAutoCancel(true).setSmallIcon(R.drawable.action)
            .setContentTitle(taskMgrParms.context.getString(R.string.app_name)).setContentText(m_text)
            .setWhen(System.currentTimeMillis());
    if (led_color != 0)
        nb.setLights(led_color, led_on, led_off);
    Notification nf = nb.build();
    nm.notify("MSG", taskMgrParms.msgNotificationId, nf);
    synchronized (envParms) {
        if (taskMgrParms.msgNotificationId >= MAX_NOTIFICATION_COUNT)
            taskMgrParms.msgNotificationId = 1;
        else
            taskMgrParms.msgNotificationId++;
    }
}

From source file:com.cyanogenmod.messaging.quickmessage.QuickMessagePopup.java

/**
 * Clears the status bar notification and, optionally, mark all messages as read
 * This is used to clean up when we are done with all qm's
 *
 * @param markAsRead - should remaining qm's be maked as read?
 *///from   w  ww.j a  v a  2 s .c  om
private void clearNotification(boolean markAsRead) {
    // Dismiss the notification that brought us here.
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    StatusBarNotification[] statusBarNotifications = notificationManager.getActiveNotifications();
    final String packageName = getPackageName();
    for (StatusBarNotification statusBarNotification : statusBarNotifications) {
        if (packageName.equals(statusBarNotification.getPackageName())) {
            notificationManager.cancel(statusBarNotification.getTag(), statusBarNotification.getId());
            break;
        }
    }

    // Mark all contained conversations as seen
    if (markAsRead) {
        markAllMessagesRead();
    }

    // Clear the messages list
    mMessageList.clear();

    if (DEBUG)
        Log.d(LOG_TAG, "clearNotification(): Message list cleared. Size = " + mMessageList.size());
}

From source file:org.wso2.iot.agent.activities.AuthenticationActivity.java

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override/* www.  j  a va2s .c o m*/
public void onAPIAccessReceive(String status) {
    if (status != null) {
        if (status.trim().equals(Constants.Status.SUCCESSFUL)) {
            CommonDialogUtils.stopProgressDialog(progressDialog);
            if (isReLogin) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, R.string.authentication_successful, Toast.LENGTH_LONG).show();
                    }
                });
                LocalNotification.startPolling(context);
                Preference.removePreference(context, Constants.TOKEN_EXPIRED);
                NotificationManager mNotificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.cancel(Constants.TOKEN_EXPIRED, Constants.SIGN_IN_NOTIFICATION_ID);
                finish();
            } else {
                Preference.putString(context, Constants.USERNAME, username);
                // Check network connection availability before calling the API.
                if (CommonUtils.isNetworkAvailable(context)) {
                    getLicense();
                } else {
                    CommonDialogUtils.showNetworkUnavailableMessage(AuthenticationActivity.this);
                }
            }
        } else if (status.trim().equals(Constants.Status.AUTHENTICATION_FAILED)) {
            showAuthenticationError();
            // clearing client credentials from shared memory
            CommonUtils.clearClientCredentials(context);
        } else if (status.trim().equals(Constants.Status.INTERNAL_SERVER_ERROR)) {
            showInternalServerErrorMessage();
        } else {
            showAuthCommonErrorMessage();
        }
    } else {
        showAuthCommonErrorMessage();
    }

}

From source file:com.mishiranu.dashchan.ui.navigator.NavigatorActivity.java

@Override
protected void onFinish() {
    super.onFinish();
    if (readUpdateTask != null) {
        readUpdateTask.cancel();//from w  ww  . j  av a  2  s.  c om
        readUpdateTask = null;
    }
    uiManager.onFinish();
    watcherServiceClient.unbind(this);
    ClickableToast.unregister(clickableToastHolder);
    FavoritesStorage.getInstance().getObservable().unregister(this);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(newPostReceiver);
    cleanupPage();
    for (String chanName : ChanManager.getInstance().getAvailableChanNames()) {
        ChanConfiguration.get(chanName).commit();
    }
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancel(C.NOTIFICATION_TAG_UPDATE, 0);
    FavoritesStorage.getInstance().await(true);
}

From source file:com.philliphsu.clock2.alarms.background.UpcomingAlarmReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
    // Unmarshall the bytes into a parcel and create our Alarm with it.
    final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
    if (alarm == null) {
        throw new IllegalStateException("No alarm received");
    }/*from  w w w.  j a  v  a2s  .  co m*/

    final long id = alarm.getId();
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
    if (intent.getAction() == null || actionShowSnoozing) {
        // Prepare notification
        // http://stackoverflow.com/a/15803726/5055032
        // Notifications aren't updated on the UI thread, so we could have
        // done this in the background. However, no lengthy operations are
        // done here, so doing so is a premature optimization.
        String title;
        String text;
        if (actionShowSnoozing) {
            if (!alarm.isSnoozed()) {
                throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
            }
            title = alarm.label().isEmpty() ? context.getString(R.string.alarm) : alarm.label();
            text = context.getString(R.string.title_snoozing_until, formatTime(context, alarm.snoozingUntil()));
        } else {
            // No intent action required for default behavior
            title = context.getString(R.string.upcoming_alarm);
            text = formatTime(context, alarm.ringsAt());
            if (!alarm.label().isEmpty()) {
                text = alarm.label() + ", " + text;
            }
        }

        Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class).setAction(ACTION_DISMISS_NOW)
                .putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
        PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id, dismissIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification note = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_alarm_24dp)
                .setContentTitle(title).setContentText(text)
                .setContentIntent(ContentIntentUtils.create(context, MainActivity.PAGE_ALARMS, id))
                .addAction(R.drawable.ic_dismiss_alarm_24dp, context.getString(R.string.dismiss_now), piDismiss)
                .build();
        nm.notify(TAG, (int) id, note);
    } else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
        nm.cancel(TAG, (int) id);
    } else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
        new AlarmController(context, null).cancelAlarm(alarm, false, true);
    }
}

From source file:com.finchuk.clock2.alarms.background.UpcomingAlarmReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
    // Unmarshall the bytes into a parcel and create our Alarm with it.
    final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
    if (alarm == null) {
        throw new IllegalStateException("No alarm received");
    }/*from   ww  w .j  a va 2  s .co  m*/

    final long id = alarm.getId();
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
    if (intent.getAction() == null || actionShowSnoozing) {
        // Prepare notification
        // http://stackoverflow.com/a/15803726/5055032
        // Notifications aren't updated on the UI thread, so we could have
        // done this in the background. However, no lengthy operations are
        // done here, so doing so is a premature optimization.
        String title;
        String text;
        if (actionShowSnoozing) {
            if (!alarm.isSnoozed()) {
                throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
            }
            title = alarm.label().isEmpty() ? context.getString(R.string.alarm) : alarm.label();
            text = context.getString(R.string.title_snoozing_until,
                    TimeFormatUtils.formatTime(context, alarm.snoozingUntil()));
        } else {
            // No intent action required for default behavior
            title = context.getString(R.string.upcoming_alarm);
            text = TimeFormatUtils.formatTime(context, alarm.ringsAt());
            if (!alarm.label().isEmpty()) {
                text = alarm.label() + ", " + text;
            }
        }

        Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class).setAction(ACTION_DISMISS_NOW)
                .putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
        PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id, dismissIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification note = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_alarm_24dp)
                .setContentTitle(title).setContentText(text)
                .setContentIntent(ContentIntentUtils.create(context, MainActivity.PAGE_ALARMS, id))
                .addAction(R.drawable.ic_dismiss_alarm_24dp, context.getString(R.string.dismiss_now), piDismiss)
                .build();
        nm.notify(TAG, (int) id, note);
    } else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
        nm.cancel(TAG, (int) id);
    } else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
        new AlarmController(context, null).cancelAlarm(alarm, false, true);
    }
}