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:com.farmerbb.taskbar.service.NotificationService.java

@TargetApi(Build.VERSION_CODES.M)
@Override//from   w  ww  .jav a  2 s . c  o  m
public void onCreate() {
    super.onCreate();

    SharedPreferences pref = U.getSharedPreferences(this);
    if (pref.getBoolean("taskbar_active", false)) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(this)) {
            isHidden = U.getSharedPreferences(this).getBoolean("is_hidden", false);
            String label = getString(isHidden ? R.string.action_show : R.string.action_hide);

            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            PendingIntent receiverIntent = PendingIntent.getBroadcast(this, 0,
                    new Intent("com.farmerbb.taskbar.SHOW_HIDE_TASKBAR"), PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent receiverIntent2 = PendingIntent.getBroadcast(this, 0,
                    new Intent("com.farmerbb.taskbar.QUIT"), PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(pref.getBoolean("app_drawer_icon", false) ? R.drawable.ic_system
                            : R.drawable.ic_allapps)
                    .setContentIntent(contentIntent).setContentTitle(getString(R.string.taskbar_is_active))
                    .setContentText(getString(R.string.click_to_open_settings))
                    .setColor(ContextCompat.getColor(this, R.color.colorPrimary))
                    .addAction(0, label, receiverIntent)
                    .addAction(0, getString(R.string.action_quit), receiverIntent2)
                    .setPriority(Notification.PRIORITY_MIN).setShowWhen(false).setOngoing(true);

            startForeground(8675309, mBuilder.build());

            LocalBroadcastManager.getInstance(this)
                    .sendBroadcast(new Intent("com.farmerbb.taskbar.UPDATE_SWITCH"));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                TileService.requestListeningState(this, new ComponentName(BuildConfig.APPLICATION_ID,
                        QuickSettingsTileService.class.getName()));

            if (!isHidden) {
                registerReceiver(userForegroundReceiver, new IntentFilter(Intent.ACTION_USER_FOREGROUND));
                registerReceiver(userBackgroundReceiver, new IntentFilter(Intent.ACTION_USER_BACKGROUND));
            }
        } else {
            pref.edit().putBoolean("taskbar_active", false).apply();

            stopSelf();
        }
    } else
        stopSelf();
}

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

private void sendNotificationForConversation(Conversations.Conversation conversation) {
    // A pending Intent for reads
    PendingIntent readPendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
            conversation.getConversationId(), getMessageReadIntent(conversation.getConversationId()),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Build a RemoteInput for receiving voice input in a Car Notification or text input on
    // devices that support text input (like devices on Android N and above).
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_REMOTE_REPLY).setLabel(getString(R.string.reply))
            .build();//from  w  w w  . j  a  v  a 2 s . c o  m

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

    // Build an Android N compatible Remote Input enabled action.
    NotificationCompat.Action actionReplyByRemoteInput = new NotificationCompat.Action.Builder(
            R.drawable.notification_icon, getString(R.string.reply), replyIntent).addRemoteInput(remoteInput)
                    .build();

    // Create the UnreadConversation and populate it with the participant name,
    // read and reply intents.
    UnreadConversation.Builder unreadConvBuilder = new UnreadConversation.Builder(
            conversation.getParticipantName()).setLatestTimestamp(conversation.getTimestamp())
                    .setReadPendingIntent(readPendingIntent).setReplyAction(replyIntent, remoteInput);

    // Note: Add messages from oldest to newest to the UnreadConversation.Builder
    StringBuilder messageForNotification = new StringBuilder();
    for (Iterator<String> messages = conversation.getMessages().iterator(); messages.hasNext();) {
        String message = messages.next();
        unreadConvBuilder.addMessage(message);
        messageForNotification.append(message);
        if (messages.hasNext()) {
            messageForNotification.append(EOL);
        }
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.drawable.notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
                    R.drawable.android_contact))
            .setContentText(messageForNotification.toString()).setWhen(conversation.getTimestamp())
            .setContentTitle(conversation.getParticipantName()).setContentIntent(readPendingIntent)
            .extend(new CarExtender().setUnreadConversation(unreadConvBuilder.build())
                    .setColor(getApplicationContext().getResources().getColor(R.color.default_color_light)))
            .addAction(actionReplyByRemoteInput);

    MessageLogger.logMessage(getApplicationContext(),
            "Sending notification " + conversation.getConversationId() + " conversation: " + conversation);

    mNotificationManager.notify(conversation.getConversationId(), builder.build());
}

From source file:com.csipsimple.plugins.twvoip.CallHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    if (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_12VOIP_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, "");

        // 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)) {
            // Build pending intent
            Intent i = new Intent(ACTION_DO_TWVOIP_CALL);
            i.setClass(context, getClass());
            i.putExtra(Intent.EXTRA_PHONE_NUMBER, number);

            pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
            // = PendingIntent.getActivity(context, 0, i, 0);
        }//from  w  ww . j a  va 2s . c om

        // Build icon
        Bitmap bmp = null;
        Drawable icon = context.getResources().getDrawable(R.drawable.icon);
        BitmapDrawable bd = ((BitmapDrawable) icon);
        bmp = bd.getBitmap();

        // Build the result for the row (label, icon, pending intent, and
        // excluded phone number)
        Bundle results = getResultExtras(true);
        if (pendingIntent != null) {
            results.putParcelable(Intent.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent);
        }
        results.putString(Intent.EXTRA_TITLE, "12voip WebCallback");
        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_TWVOIP_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_12VOIP_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, "");

        // 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.12voip.com//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.javadog.cgeowear.cgeoWearService.java

/**
 * Starts this service in the foreground and supplies the 3-page Android Wear home screen notification.
 *///from w w  w  .  j av  a2  s . c  om
private void showOngoingNotification() {
    //Action 2 - 'Stop Navigating' (kills watch and phone apps)
    Intent killAppIntent = new Intent(ListenerService.PATH_KILL_APP);
    PendingIntent killAppPendingIntent = PendingIntent.getBroadcast(this, 0, killAppIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Action 1 - 'Show Compass'
    Intent launchIntent = new Intent(this, CompassActivity.class);
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    launchIntent.setAction(ListenerService.PATH_INIT);
    PendingIntent launchPendingIntent = PendingIntent.getActivity(this, 0, launchIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Main Notification
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.notification1_body))
            .addAction(R.drawable.ic_show_compass, getString(R.string.notification2_label), launchPendingIntent)
            .addAction(R.drawable.ic_stop_navigation, getString(R.string.notification3_label),
                    killAppPendingIntent)
            .extend(new NotificationCompat.WearableExtender()
                    .setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.background_image)));

    startForeground(NOTIFICATION_ID, notificationBuilder.build());
}

From source file:com.chess.genesis.net.GenesisNotifier.java

public static void ScheduleWakeup(final Context context) {
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, Pref.getInt(context, R.array.pf_notifierPolling));
    final long start = cal.getTimeInMillis();
    final long interval = start - System.currentTimeMillis();

    final Intent intent = new Intent(context, GenesisAlarm.class);
    final PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, start, interval, pintent);
}

From source file:com.example.android.supportv4.media.MediaNotificationManager.java

public MediaNotificationManager(MediaBrowserServiceSupport service) {
    mService = service;/*from w ww  .  j a  v a  2 s.com*/
    updateSessionToken();

    mNotificationColor = ResourceHelper.getThemeColor(mService, android.R.attr.colorPrimary, Color.DKGRAY);

    mNotificationManager = NotificationManagerCompat.from(mService);

    String pkg = mService.getPackageName();
    mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_PAUSE).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_PLAY).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_NEXT).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

@Override
public void onCreate() {
    super.onCreate();
    contentResolver = getContentResolver();
    cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    sharedPreferences = getSharedPreferences(PlacesConstants.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE);
    sharedPreferencesEditor = sharedPreferences.edit();
    sharedPreferenceSaver = PlatformSpecificImplementationFactory.getSharedPreferenceSaver(this);

    Intent retryIntent = new Intent(PlacesConstants.RETRY_QUEUED_CHECKINS_ACTION);
    retryQueuedCheckinsPendingIntent = PendingIntent.getBroadcast(this, 0, retryIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:ca.hoogit.hooold.Scheduling.Sms.java

public void single(Context context, SmsManager manager, String recipient, int count) {
    Intent sent = generateIntent(Consts.INTENT_SMS_SENT, recipient, count);
    PendingIntent pendingSent = PendingIntent.getBroadcast(context, (int) id, sent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    Intent delivered = generateIntent(Consts.INTENT_SMS_DELIVERED, recipient, count);
    PendingIntent pendingDelivered = PendingIntent.getBroadcast(context, (int) id, delivered,
            PendingIntent.FLAG_CANCEL_CURRENT);

    manager.sendTextMessage(recipient, null, messageBody, pendingSent, pendingDelivered);
}

From source file:com.google.android.apps.iosched.gcm.GCMIntentService.java

@Override
protected void onMessage(Context context, Intent intent) {
    if (UIUtils.isGoogleTV(context)) {
        // Google TV uses SyncHelper directly.
        return;/*from w w w .  ja va  2 s.c o m*/
    }
    String announcement = intent.getStringExtra("announcement");
    if (announcement != null) {
        displayNotification(context, announcement);
        return;
    }

    int jitterMillis = (int) (sRandom.nextFloat() * TRIGGER_SYNC_MAX_JITTER_MILLIS);
    final String debugMessage = "Received message to trigger sync; " + "jitter = " + jitterMillis + "ms";
    LOGI(TAG, debugMessage);

    if (BuildConfig.DEBUG) {
        displayNotification(context, debugMessage);
    }

    ((AlarmManager) context.getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC,
            System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast(context, 0,
                    new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT));
}

From source file:com.example.android.activenotifications.ActiveNotificationsFragment.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/*from  w w w. j  a  va  2 s . c  o m*/
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.add_notification: {
                addNotificationAndUpdateSummaries();
                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(ActiveNotificationsActivity.ACTION_NOTIFICATION_DELETE);
    mDeletePendingIntent = PendingIntent.getBroadcast(getActivity(), REQUEST_CODE, deleteIntent, 0);
    // [END create_pending_intent_for_deletion]
}