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.embeddedlog.LightUpDroid.alarms.AlarmNotifications.java

public static void showHighPriorityNotification(Context context, AlarmInstance instance) {
    Log.v("Displaying high priority notification for alarm instance: " + instance.mId);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Resources resources = context.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(resources.getString(R.string.alarm_alert_predismiss_title))
            .setContentText(AlarmUtils.getAlarmText(context, instance))
            .setSmallIcon(R.drawable.stat_notify_alarm).setOngoing(true).setAutoCancel(false)
            .setPriority(NotificationCompat.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM);

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context, "DISMISS_TAG", instance,
            AlarmInstance.DISMISSED_STATE);
    notification.addAction(android.R.drawable.ic_menu_close_clear_cancel,
            resources.getString(R.string.alarm_alert_dismiss_now_text), PendingIntent.getBroadcast(context,
                    instance.hashCode(), dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content action if instance is owned by alarm
    long alarmId = instance.mAlarmId == null ? Alarm.INVALID_ID : instance.mAlarmId;
    Intent viewAlarmIntent = Alarm.createIntent(context, DeskClock.class, alarmId);
    viewAlarmIntent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.ALARM_TAB_INDEX);
    viewAlarmIntent.putExtra(AlarmClockFragment.SCROLL_TO_ALARM_INTENT_EXTRA, alarmId);
    viewAlarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    notification.setContentIntent(PendingIntent.getActivity(context, instance.hashCode(), viewAlarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    nm.cancel(instance.hashCode());/*from ww w . j  a  v a 2 s  .c om*/
    nm.notify(instance.hashCode(), notification.build());
}

From source file:com.iitb.wicroft.EventAlarmReceiver.java

void scheduleNextAlarm(Context context) {
    String msg = "EventAlarmeceiver - ScheduleNextAlarm ";

    if (!MainActivity.running) {
        msg += "scheduleNextAlarm : Experiment not 'running'";
        return;//  ww w . j a va 2  s .  co m
    }

    if (MainActivity.load == null) {
        msg += "scheduleNextAlarm : load null";
        return;
    }

    if (MainActivity.currEvent >= MainActivity.load.independent_events.size()) {
        msg += "scheduleNextAlarm : All independent events alarms over.";
        return;
    }

    // RequestEvent e = MainActivity.load.events.get(MainActivity.currEvent);
    Log.d("EventAlarmRx :nextalarm", " MainActivity.currEvent =  " + MainActivity.currEvent);
    RequestEvent e = new RequestEvent(MainActivity.load.independent_events.get(MainActivity.currEvent));
    Intent intent = new Intent(context, EventAlarmReceiver.class);
    intent.putExtra("eventid", (int) e.event_id);

    Random r = new Random();
    int i1 = r.nextInt(10000 - 0) + 0;
    PendingIntent sender = PendingIntent.getBroadcast(context, Constants.alarmRequestCode + i1, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    msg += "\n e.cal time in millisec : " + Long.toString(e.cal.getTimeInMillis())
            + "MainActivity.serverTimeDelta : " + Long.toString(MainActivity.serverTimeDelta);
    msg += "\n Scheduling " + e.event_id + "@" + MainActivity.sdf.format(e.cal.getTime());
    msg += "\n current time in ms :" + Long.toString(Calendar.getInstance().getTimeInMillis());
    msg += "\n alarmwakeup in ms" + Long.toString(e.cal.getTimeInMillis() - MainActivity.serverTimeDelta);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        // Do something for kitkat and above versions
        MainActivity.am.setExact(AlarmManager.RTC_WAKEUP,
                e.cal.getTimeInMillis() - MainActivity.serverTimeDelta, sender);
    } else {
        // do something for phones running an SDK before kitkat
        MainActivity.am.set(AlarmManager.RTC_WAKEUP, e.cal.getTimeInMillis() - MainActivity.serverTimeDelta,
                sender);
    }

    // Log.d(Constants.LOGTAG, MainActivity.sdf.format(cal.getTime()) + "Scheduling " + MainActivity.currEvent + "@" + MainActivity.sdf.format(e.cal.getTime()) + "\n");

    /*
     * [event_time_stamp - (server - local)] gives when alarm should be scheduled.
     * Why ? Details ahead :
     * For e.g if local 2.00, server 2.10. Difference (server - local) = 10
     * Now server says schedule alarm at 2.15. Alarms follow local time.
     * So now according to local time, alarm should be scheduled at
     * time 2.05 (because at that moment servertime will be 2.05 + 10 = 2.15)
     */

    MainActivity.currEvent++;
    // Log.d(Constants.LOGTAG, "Current event" + MainActivity.currEvent);

    Log.d(Constants.LOGTAG, msg);
    if (MainActivity.debugging_on) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Threads.writeToLogFile(MainActivity.debugfilename,
                format1.format(cal.getTime()) + " " + Utils.sdf.format(cal.getTime()) + msg);
    }

}

From source file:com.dmplayer.manager.MusicPlayerService.java

@SuppressLint("NewApi")
@Override/*www.  j  a  v a 2  s.c  o m*/
public int onStartCommand(Intent intent, int flags, int startId) {
    try {
        SongDetail messageObject = MediaController.getInstance().getPlayingSongDetail();
        if (messageObject == null) {
            DMPlayerUtility.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            });
            return START_STICKY;
        }
        if (supportLockScreenControls) {
            ComponentName remoteComponentName = new ComponentName(getApplicationContext(),
                    MusicPlayerReceiver.class.getName());
            try {
                if (remoteControlClient == null) {
                    audioManager.registerMediaButtonEventReceiver(remoteComponentName);
                    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                    mediaButtonIntent.setComponent(remoteComponentName);
                    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent,
                            0);
                    remoteControlClient = new RemoteControlClient(mediaPendingIntent);
                    audioManager.registerRemoteControlClient(remoteControlClient);
                }
                remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                        | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                        | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
            } catch (Exception e) {
                Log.e("tmessages", e.toString());
            }
        }
        createNotification(messageObject);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return START_STICKY;
}

From source file:com.battlelancer.seriesguide.util.Utils.java

/**
 * Run the notification service delayed by a minute to display and (re)schedule upcoming episode
 * alarms./*from   ww w  .j  a  v  a  2  s. co m*/
 */
public static void runNotificationServiceDelayed(Context context) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, OnAlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1 * DateUtils.MINUTE_IN_MILLIS, pi);
}

From source file:com.goftagram.telegram.messenger.MusicPlayerService.java

@SuppressLint("NewApi")
@Override// w ww  .  j a  v  a2  s. c o  m
public int onStartCommand(Intent intent, int flags, int startId) {
    try {
        MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
        if (messageObject == null) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            });
            return START_STICKY;
        }
        if (supportLockScreenControls) {
            ComponentName remoteComponentName = new ComponentName(getApplicationContext(),
                    MusicPlayerReceiver.class.getName());
            try {
                if (remoteControlClient == null) {
                    audioManager.registerMediaButtonEventReceiver(remoteComponentName);
                    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                    mediaButtonIntent.setComponent(remoteComponentName);
                    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent,
                            0);
                    remoteControlClient = new RemoteControlClient(mediaPendingIntent);
                    audioManager.registerRemoteControlClient(remoteControlClient);
                }
                remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                        | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                        | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
        createNotification(messageObject);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return START_STICKY;
}

From source file:co.codecrunch.musicplayerlite.manager.MusicPlayerService.java

@SuppressLint("NewApi")
@Override//from w  w  w .j ava 2 s .com
public int onStartCommand(Intent intent, int flags, int startId) {
    try {
        SongDetail messageObject = MediaController.getInstance().getPlayingSongDetail();
        if (messageObject == null) {
            MusicPlayerUtility.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            });
            return START_STICKY;
        }
        if (supportLockScreenControls) {
            ComponentName remoteComponentName = new ComponentName(getApplicationContext(),
                    MusicPlayerReceiver.class.getName());
            try {
                if (remoteControlClient == null) {
                    audioManager.registerMediaButtonEventReceiver(remoteComponentName);
                    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                    mediaButtonIntent.setComponent(remoteComponentName);
                    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent,
                            0);
                    remoteControlClient = new RemoteControlClient(mediaPendingIntent);
                    audioManager.registerRemoteControlClient(remoteControlClient);
                }
                remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                        | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                        | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
            } catch (Exception e) {
                Log.e("tmessages", e.toString());
            }
        }
        createNotification(messageObject);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return START_STICKY;
}

From source file:org.kegbot.app.service.CheckinService.java

private void registerAlarm() {
    unregisterAlarm();//from  w w  w  .j ava  2 s. co m
    Log.d(TAG, "Registering alarm.");
    final Intent intent = getCheckinIntent(this);
    mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    final long nextCheckin = SystemClock.elapsedRealtime() + CHECKIN_INTERVAL_MILLIS;
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextCheckin, CHECKIN_INTERVAL_MILLIS,
            mPendingIntent);
}

From source file:butter.droid.base.torrent.TorrentService.java

public void startForeground() {
    if (Foreground.get().isForeground())
        return;/*from w  w  w . j av a 2s . c  o  m*/
    if (mCurrentActivityClass == null)
        return;

    Intent notificationIntent = new Intent(this, mCurrentActivityClass);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent stopIntent = new Intent();
    stopIntent.setAction(TorrentBroadcastReceiver.STOP);
    PendingIntent pendingStopIntent = PendingIntent.getBroadcast(this, TorrentBroadcastReceiver.REQUEST_CODE,
            stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action stopAction = new NotificationCompat.Action.Builder(
            R.drawable.abc_ic_clear_mtrl_alpha, getString(R.string.stop), pendingStopIntent).build();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notif_logo)
            .setContentTitle(getString(R.string.app_name) + " - " + getString(R.string.running))
            .setContentText(getString(R.string.tap_to_resume)).setOngoing(true).setOnlyAlertOnce(true)
            .setPriority(Notification.PRIORITY_LOW).setContentIntent(pendingIntent).addAction(stopAction)
            .setCategory(NotificationCompat.CATEGORY_SERVICE);

    if (mStreamStatus != null && mIsReady) {
        String downloadSpeed;
        DecimalFormat df = new DecimalFormat("#############0.00");
        if (mStreamStatus.downloadSpeed / 1024 < 1000) {
            downloadSpeed = df.format(mStreamStatus.downloadSpeed / 1024) + " KB/s";
        } else {
            downloadSpeed = df.format(mStreamStatus.downloadSpeed / (1024 * 1024)) + " MB/s";
        }
        String progress = df.format(mStreamStatus.progress);
        builder.setContentText(progress + "%, " + downloadSpeed);
    }

    Notification notification = builder.build();

    NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notifManager.notify(NOTIFICATION_ID, notification);
    startForeground(NOTIFICATION_ID, notification);

    if (mUpdateTimer == null) {
        mUpdateTimer = new Timer();
        mUpdateTimer.scheduleAtFixedRate(new UpdateTask(), 5000, 5000);
    }
}

From source file:com.amaze.filemanager.asynchronous.services.ZipService.java

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
    String mZipPath = intent.getStringExtra(KEY_COMPRESS_PATH);

    ArrayList<HybridFileParcelable> baseFiles = intent.getParcelableArrayListExtra(KEY_COMPRESS_FILES);

    File zipFile = new File(mZipPath);

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (!zipFile.exists()) {
        try {/*w ww .  ja  v a2s.  c om*/
            zipFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    accentColor = ((AppConfig) getApplication()).getUtilsProvider().getColorPreference()
            .getCurrentUserColorPreferences(this, sharedPreferences).accent;

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.putExtra(MainActivity.KEY_INTENT_PROCESS_VIEWER, true);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    customSmallContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_small);
    customBigContentViews = new RemoteViews(getPackageName(), R.layout.notification_service_big);

    Intent stopIntent = new Intent(KEY_COMPRESS_BROADCAST_CANCEL);
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1234, stopIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action action = new NotificationCompat.Action(R.drawable.ic_zip_box_grey600_36dp,
            getString(R.string.stop_ftp), stopPendingIntent);

    mBuilder = new NotificationCompat.Builder(this, NotificationConstants.CHANNEL_NORMAL_ID)
            .setSmallIcon(R.drawable.ic_zip_box_grey600_36dp).setContentIntent(pendingIntent)
            .setCustomContentView(customSmallContentViews).setCustomBigContentView(customBigContentViews)
            .setCustomHeadsUpContentView(customSmallContentViews)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle()).addAction(action).setOngoing(true)
            .setColor(accentColor);

    NotificationConstants.setMetadata(this, mBuilder, NotificationConstants.TYPE_NORMAL);
    startForeground(NotificationConstants.ZIP_ID, mBuilder.build());
    initNotificationViews();

    super.onStartCommand(intent, flags, startId);
    super.progressHalted();
    asyncTask = new CompressAsyncTask(this, baseFiles, mZipPath);
    asyncTask.execute();
    // If we get killed, after returning from here, restart
    return START_STICKY;
}

From source file:com.commonsware.android.webserver.secure.WebServerService.java

private void foregroundify() {
    NotificationCompat.Builder b = new NotificationCompat.Builder(this);
    Intent iActivity = new Intent(this, MainActivity.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.mipmap.ic_launcher)
            .setTicker(getString(R.string.app_name))
            .addAction(R.drawable.ic_stop_white_24dp, getString(R.string.notify_stop), piReceiver);

    startForeground(1337, b.build());/*from w ww  . ja  va  2s .  c o m*/
}