Example usage for android.app PendingIntent getBroadcast

List of usage examples for android.app PendingIntent getBroadcast

Introduction

In this page you can find the example usage for android.app PendingIntent getBroadcast.

Prototype

public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will perform a broadcast, like calling Context#sendBroadcast(Intent) Context.sendBroadcast() .

Usage

From source file:de.appplant.cordova.plugin.notification.NotificationWrapper.java

/**
 * Schedule new notification//  ww w.j  a  v a2  s .co m
 */
public void schedule(Options options) {
    long triggerTime = options.getDate();

    persist(options.getId(), options.getJSONObject());

    //Intent is called when the Notification gets fired
    Intent intent = new Intent(context, receiver).setAction("" + options.getId()).putExtra(OPTIONS,
            options.getJSONObject().toString());

    AlarmManager am = getAlarmManager();
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    am.set(AlarmManager.RTC_WAKEUP, triggerTime, pi);
}

From source file:com.gsma.rcs.ri.RcsServiceNotifManager.java

@Override
public void onCreate() {
    if (LogUtils.isActive) {
        Log.d(LOGTAG, "Service started");
    }//from www . java  2  s.c  o m
    mCtx = this;
    mCnxIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_API_CONNECT), 0);
    mAlarmManager = (AlarmManager) mCtx.getSystemService(Context.ALARM_SERVICE);

    notifyImsUnregistered(RcsServiceRegistration.ReasonCode.UNSPECIFIED);

    mStartupEventReceiver = new RcsServiceStartupListener();
    registerReceiver(mStartupEventReceiver, new IntentFilter(RcsService.ACTION_SERVICE_UP));

    /* Register the broadcast receiver to pool periodically the API connections */
    registerReceiver(new ReceiveTimerToReConnectApi(), new IntentFilter(ACTION_API_CONNECT));

    mRetryCount = 0;
    connectToService(this);
}

From source file:com.commonsware.android.antidoze.ScheduledService.java

private void foregroundify() {
    NotificationCompat.Builder b = new NotificationCompat.Builder(this);
    Intent iActivity = new Intent(this, EventDemoActivity.class);
    PendingIntent piActivity = PendingIntent.getActivity(this, 0, iActivity, 0);
    Intent iReceiver = new Intent(this, StopReceiver.class);
    PendingIntent piReceiver = PendingIntent.getBroadcast(this, 0, iReceiver, 0);

    b.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setContentTitle(getString(R.string.app_name))
            .setContentIntent(piActivity).setSmallIcon(R.drawable.ic_launcher)
            .setTicker(getString(R.string.app_name))
            .addAction(R.drawable.ic_stop_white_24dp, getString(R.string.notif_stop), piReceiver);

    startForeground(NOTIFY_ID, b.build());
}

From source file:com.commonsware.android.sawmonitor.SAWDetector.java

static void seeSAW(Context ctxt, String pkg, String operation) {
    if (hasSAW(ctxt, pkg)) {
        Uri pkgUri = Uri.parse("package:" + pkg);
        Intent manage = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);

        manage.setData(pkgUri);/*  w  w  w.  j  a  va2s.com*/

        Intent whitelist = new Intent(ctxt, WhitelistReceiver.class);

        whitelist.setData(pkgUri);

        Intent main = new Intent(ctxt, MainActivity.class);

        main.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        NotificationManager mgr = (NotificationManager) ctxt.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null) {
            mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER, "Whatever",
                    NotificationManager.IMPORTANCE_DEFAULT));
        }

        NotificationCompat.Builder b = new NotificationCompat.Builder(ctxt, CHANNEL_WHATEVER);
        String text = String.format(ctxt.getString(R.string.msg_requested), operation, pkg);

        b.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis())
                .setContentTitle(ctxt.getString(R.string.msg_detected)).setContentText(text)
                .setSmallIcon(android.R.drawable.stat_notify_error)
                .setTicker(ctxt.getString(R.string.msg_detected))
                .setContentIntent(PendingIntent.getActivity(ctxt, 0, manage, PendingIntent.FLAG_UPDATE_CURRENT))
                .addAction(R.drawable.ic_verified_user_24dp, ctxt.getString(R.string.msg_whitelist),
                        PendingIntent.getBroadcast(ctxt, 0, whitelist, 0))
                .addAction(R.drawable.ic_settings_24dp, ctxt.getString(R.string.msg_settings),
                        PendingIntent.getActivity(ctxt, 0, main, 0));

        mgr.notify(NOTIFY_ID, b.build());
    }
}

From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java

/**
 * This function creates a new Alarm by given alarm type. if not {@link AlarmType#NONE}
 * value was given as a type alarm will be called Daily, Weekly or Monthly staring from
 * time when this function was called. All alarms which were created before will be canceled.
 *
 * @param context Application context//from w w w .  java  2 s .c  om
 * @param type Alarm Type, accepted values are
 *              {@link AlarmType#NONE} if need to cancel all alarms,
 *              {@link AlarmType#DAILY} alarm will called daily
 *              {@link AlarmType#WEEKLY} alarm will called weekly
 *              {@link AlarmType#MONTHLY} alarm will called monthly
 */
public static void createAlarm(final Context context, AlarmType type) {

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());

    switch (type) {
    case DAILY:
        calendar.add(Calendar.DATE, 1);
        break;

    case WEEKLY:
        calendar.add(Calendar.DATE, 7);
        break;

    case MONTHLY:
        calendar.add(Calendar.MONTH, 1);
        break;
    }

    // Create Alarm Manager Object.
    if (mAlarmManager == null)
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    //
    Intent intent = new Intent(context, AlarmReceiver.class);
    if (mAlarmIntent == null)
        mAlarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    // Remove all previously created alarms, before creating new one.
    if (mAlarmManager != null) {
        mAlarmManager.cancel(mAlarmIntent);

        // By default Disable Boot Receiver.
        int componentEnabledState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
        // For enabling/disabling Boot Receiver.
        ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
        PackageManager pm = context.getPackageManager();

        // Set new alarm if provided interval is not none.
        if (!AlarmType.NONE.equals(type)) {
            Logger.debug("AlarmReceiver", String
                    .format("----> Next Update Date: %1$tA %1$tb %1$td %1$tY at %1$tI:%1$tM %1$Tp", calendar));
            // Enables Boot Receiver.
            componentEnabledState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
            // Set repeating alarm.
            final long timeInMillis = calendar.getTimeInMillis();
            mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, type.getValue(),
                    mAlarmIntent);

            // Stores next Alert Time.
            PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, timeInMillis);

        } else {
            PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1);
        }

        pm.setComponentEnabledSetting(receiver, componentEnabledState, PackageManager.DONT_KILL_APP);
    }
}

From source file:com.example.android.automessagingcodelab.MessagingService.java

private void sendNotificationForConversation(int conversationId, String sender, String message,
        long timestamp) {
    // A pending Intent for reads
    PendingIntent readPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), conversationId,
            getMessageReadIntent(conversationId), PendingIntent.FLAG_UPDATE_CURRENT);

    /// Add the code to create the UnreadConversation

    // Build a RemoteInput for receiving voice input in a Car Notification
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).build();

    // Building a Pending Intent for the reply action to trigger
    PendingIntent replyIntent = PendingIntent.getBroadcast(getApplicationContext(), conversationId,
            getMessageReplyIntent(conversationId), PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the UnreadConversation and populate it with the participant name,
    // read and reply intents.
    UnreadConversation.Builder unreadConversationBuilder = new UnreadConversation.Builder(sender)
            .setLatestTimestamp(timestamp).setReadPendingIntent(readPendingIntent)
            .setReplyAction(replyIntent, remoteInput);

    // Note: Add messages from oldest to newest to the UnreadConversation.Builder
    // Since we are sending a single message here we simply add the message.
    // In a real world application there could be multiple messages which should be ordered
    // and added from oldest to newest.
    unreadConversationBuilder.addMessage(message);

    /// End create UnreadConversation

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.drawable.notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
                    R.drawable.android_contact))
            .setContentText(message).setWhen(timestamp).setContentTitle(sender)
            .setContentIntent(readPendingIntent)
            /// Extend the notification with CarExtender.
            .extend(new CarExtender().setUnreadConversation(unreadConversationBuilder.build()))
            .setColor(getResources().getColor(R.color.default_color_light));
    /// End/*from   w w  w .j a va  2  s.c o m*/
    ;

    Log.d(TAG, "Sending notification " + conversationId + " conversation: " + message);

    NotificationManagerCompat.from(this).notify(conversationId, builder.build());
}

From source file:com.example.android.activenotifications.ActiveNotificationFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    mNumberOfNotifications = (TextView) view.findViewById(R.id.number_of_notifications);

    // Supply actions to the button that is displayed on screen.
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override// w ww  . j a  va 2  s.  co m
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.add_notification: {
                addNotificationAndReadNumber();
                break;
            }
            }
        }
    };
    view.findViewById(R.id.add_notification).setOnClickListener(onClickListener);

    // [BEGIN create_pending_intent_for_deletion]
    // Create a PendingIntent to be fired upon deletion of a Notification.
    Intent deleteIntent = new Intent(ActiveNotificationActivity.ACTION_NOTIFICATION_DELETE);
    mDeletePendingIntent = PendingIntent.getBroadcast(getActivity(), 2323 /* requestCode */, deleteIntent, 0);
    // [END create_pending_intent_for_deletion]
}

From source file:com.csipsimple.plugins.betamax.CallHandlerWeb.java

@Override
public void onReceive(Context context, Intent intent) {
    if (Utils.ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) {

        PendingIntent pendingIntent = null;
        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_TW_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_TW_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_TW_NBR, "");
        String provider = prefs.getString(CallHandlerConfig.KEY_TW_PROVIDER, "");

        // We must handle that clean way cause when call just to
        // get the row in account list expect this to reply correctly
        if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(user) && !TextUtils.isEmpty(nbr)
                && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(provider)) {
            // Build pending intent
            Intent i = new Intent(ACTION_DO_WEB_CALL);
            i.setClass(context, getClass());
            i.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
            pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

        }//  w  ww  .j av a2 s . c o  m

        // Build icon
        Bitmap bmp = Utils.getBitmapFromResource(context, R.drawable.icon_web);

        // Build the result for the row (label, icon, pending intent, and
        // excluded phone number)
        Bundle results = getResultExtras(true);
        if (pendingIntent != null) {
            results.putParcelable(Utils.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent);
        }

        // Text for the row
        String providerName = "";
        Resources r = context.getResources();
        if (!TextUtils.isEmpty(provider)) {
            String[] arr = r.getStringArray(R.array.provider_values);
            String[] arrEntries = r.getStringArray(R.array.provider_entries);
            int i = 0;
            for (String prov : arr) {
                if (prov.equalsIgnoreCase(provider)) {
                    providerName = arrEntries[i];
                    break;
                }
                i++;
            }
        }
        results.putString(Intent.EXTRA_TITLE, providerName + " " + r.getString(R.string.web_callback));
        Log.d(THIS_FILE, "icon is " + bmp);
        if (bmp != null) {
            results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, bmp);
        }

        // DO *NOT* exclude from next tel: intent cause we use a http method
        // results.putString(Intent.EXTRA_PHONE_NUMBER, number);

    } else if (ACTION_DO_WEB_CALL.equals(intent.getAction())) {

        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_TW_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_TW_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_TW_NBR, "");
        String provider = prefs.getString(CallHandlerConfig.KEY_TW_PROVIDER, "");

        // params
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        params.add(new BasicNameValuePair("username", user));
        params.add(new BasicNameValuePair("password", pwd));
        params.add(new BasicNameValuePair("from", nbr));
        params.add(new BasicNameValuePair("to", number));
        String paramString = URLEncodedUtils.format(params, "utf-8");

        String requestURL = "https://www." + provider + "/myaccount/makecall.php?" + paramString;

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(requestURL);

        // Create a response handler
        HttpResponse httpResponse;
        try {
            httpResponse = httpClient.execute(httpGet);
            Log.d(THIS_FILE, "response code is " + httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent());
                BufferedReader br = new BufferedReader(isr);

                String line;
                String fullReply = "";
                boolean foundSuccess = false;
                while ((line = br.readLine()) != null) {
                    if (!TextUtils.isEmpty(line) && line.toLowerCase().contains("success")) {
                        showToaster(context, "Success... wait a while you'll called back");
                        foundSuccess = true;
                        break;
                    }
                    if (!TextUtils.isEmpty(line)) {
                        fullReply = fullReply.concat(line);
                    }
                }
                if (!foundSuccess) {
                    showToaster(context, "Error : server error : " + fullReply);
                }
            } else {
                showToaster(context, "Error : invalid request " + httpResponse.getStatusLine().getStatusCode());
            }
        } catch (ClientProtocolException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        } catch (IOException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        }

    }
}

From source file:com.devnoobs.bmr.Powiadomienia.java

public void cancelAlarm() {
    Intent i = new Intent(S);
    PendingIntent sender = PendingIntent.getBroadcast(c, 0, i, 0);
    AlarmManager alarmManager = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);/* w  ww.  j ava 2s.  c o m*/
    showToast("Powiadomienie wylaczone");
}

From source file:cn.studyjams.s2.sj0119.NForget.AlarmReceiver.java

public void setAlarm(Context context, Calendar calendar, int ID) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using notification time
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}