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.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java

/**
 * Stops the alarm repeater after a disconnection from a WiFi network
 * /*from   w  w w .  jav  a 2 s  .c o m*/
 * @param context  The context to use
 */
private void stopAlarmRepeater(Context context) {
    /**
     * Sends a message to clean the host collection, and stop the DiscoverServerService
     * should be safe because this method gets called on WiFi disconnect
     */
    Intent i = new Intent(context, this.getClass());
    i.setAction(context.getResources().getString(R.string.broadcast_cleanhostcollection));
    i.putExtra("stopservice", true);
    context.sendBroadcast(i);

    /**
     * Cancel the pending intent from the AlarmManager
     */
    PendingIntent senderstop = PendingIntent.getBroadcast(context, 0, new Intent(context, this.getClass()), 0);
    // Get the alarm manager
    if (alarmManager == null)
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(senderstop);
}

From source file:com.android.mms.transaction.RetrieveTransaction.java

public void run() {
    MmsLog.i(MmsApp.TXN_TAG, "RetrieveTransaction: run()");
    try {//from ww  w .  j a v  a 2 s  .c o  m
        NotificationInd nInd = (NotificationInd) PduPersister.getPduPersister(mContext).load(mUri);
        if (nInd.getExpiry() < System.currentTimeMillis() / 1000L) {
            MmsLog.d(MmsApp.TXN_TAG, "The message is expired!");
            sendExpiredRes();
            // Change the downloading state of the M-Notification.ind.
            DownloadManager.getInstance().markState(mUri, DownloadManager.STATE_DOWNLOADING);
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            notifyObservers();
            return;
        }

        // Change the downloading state of the M-Notification.ind.
        DownloadManager.getInstance().markState(mUri, DownloadManager.STATE_DOWNLOADING);

        /// M: For OP009, check if cancel download requested. @{
        /*            if (MmsConfig.isCancelDownloadEnable() && mIsCancelling) {
        mTransactionState.setState(TransactionState.SUCCESS);
        mTransactionState.setContentUri(mUri);
                
        if (MmsConfig.isCancelDownloadEnable()) {
            sMmsFailedNotifyPlugin.popupToast(mContext,
                IMmsFailedNotifyExt.CANCEL_DOWNLOAD, null);
        }
        mIsCancelling = false;
        final Uri trxnUri = getUri();
        sCancelDownloadPlugin.markStateExt(trxnUri, sCancelDownloadPlugin.STATE_COMPLETE);
        DownloadManager.getInstance().markState(trxnUri, DownloadManager.STATE_UNSTARTED);
                
        return;
                    }*/
        /// @}

        if (mOpRetrieveTransactionExt.run(mIsCancelling, mUri, mContext, getUri(), mContentLocation)) {
            mTransactionState.setState(TransactionState.SUCCESS);
            mTransactionState.setContentUri(mUri);
            mIsCancelling = false;
            return;
        }

        mPduFile = createPduFile(null, RETRIEVE_RESULT_NAME + mUri.getLastPathSegment());
        mPduFile.setWritable(true, false);
        //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED);
        //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);
        //intent.putExtra(TransactionBundle.URI, mUri.toString());
        Log.d(MmsApp.TXN_TAG, "RetrieveTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent downloadedIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(mSubId);
        Log.d(MmsApp.TXN_TAG, "download MMS with param, mContentLocation = " + mContentLocation + ", mUri = "
                + mUri + ", subId" + mSubId);
        /// M: Add MmsService configure param @{
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        manager.downloadMultimediaMessage(mContext, mContentLocation, pduFileUri,
                MmsConfig.getMmsServiceConfig(), downloadedIntent);
        /// @}

        // Make sure this thread isn't over the limits in message count.
        Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);

        /// OP009 MMS Feature: cancel download Mms @{
        /*            if (MmsConfig.isCancelDownloadEnable()) {
        sCancelDownloadPlugin.addHttpClient(mContentLocation, mUri);
                    }*/
        /// @}

        // Send ACK to the Proxy-Relay to indicate we have fetched the
        // MM successfully.
        // Don't mark the transaction as failed if we failed to send it.
        // sendAcknowledgeInd(retrieveConf);
    } catch (Throwable t) {
        Log.e(TAG, Log.getStackTraceString(t));
        mTransactionState.setState(TransactionState.FAILED);
        mTransactionState.setContentUri(mUri);
        notifyObservers();
    }
}

From source file:info.snowhow.plugin.RecorderService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(LOG_TAG, "Received start id " + startId + ": " + intent);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        showNoGPSAlert();/* ww  w  . j a  va2 s. c o m*/
    }
    runningID = startId;
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.

    if (intent == null) {
        tf = sharedPref.getString("runningTrackFile", "");
        Log.w(LOG_TAG, "Intent is null, trying to continue to write to file " + tf + " lm " + locationManager);
        minimumPrecision = sharedPref.getFloat("runningPrecision", 0);
        distanceChange = sharedPref.getLong("runningDistanceChange", MINIMUM_DISTANCE_CHANGE_FOR_UPDATES);
        updateTime = sharedPref.getLong("runningUpdateTime", MINIMUM_TIME_BETWEEN_UPDATES);
        updateTimeFast = sharedPref.getLong("runningUpdateTimeFast", MINIMUM_TIME_BETWEEN_UPDATES_FAST);
        speedLimit = sharedPref.getLong("runningSpeedLimit", SPEED_LIMIT);
        adaptiveRecording = sharedPref.getBoolean("adaptiveRecording", false);
        int count = sharedPref.getInt("count", 0);
        if (count > 0) {
            firstPoint = false;
        }
        if (tf == null || tf == "") {
            Log.e(LOG_TAG, "No trackfile found ... exit clean here");
            cleanUp();
            return START_NOT_STICKY;
        }
    } else {
        tf = intent.getStringExtra("fileName");
        Log.d(LOG_TAG, "FILENAME for recording is " + tf);
        minimumPrecision = intent.getFloatExtra("precision", 0);
        distanceChange = intent.getLongExtra("distance_change", MINIMUM_DISTANCE_CHANGE_FOR_UPDATES);
        updateTime = intent.getLongExtra("update_time", MINIMUM_TIME_BETWEEN_UPDATES);
        updateTimeFast = intent.getLongExtra("update_time_fast", MINIMUM_TIME_BETWEEN_UPDATES_FAST);
        speedLimit = intent.getLongExtra("speed_limit", SPEED_LIMIT);
        adaptiveRecording = intent.getBooleanExtra("adaptiveRecording", false);
        editor.putString("runningTrackFile", tf);
        editor.putFloat("runningPrecision", minimumPrecision);
        editor.putLong("runningDistanceChange", distanceChange);
        editor.putLong("runningUpdateTime", updateTime);
        editor.putLong("runningUpdateTimeFast", updateTimeFast);
        editor.putLong("runningSpeedLimit", speedLimit);
        editor.putBoolean("adaptiveRecording", adaptiveRecording);
        editor.commit();
    }

    Intent cordovaMainIntent;
    try {
        PackageManager packageManager = this.getPackageManager();
        cordovaMainIntent = packageManager.getLaunchIntentForPackage(this.getPackageName());
        Log.d(LOG_TAG, "got cordovaMainIntent " + cordovaMainIntent);
        if (cordovaMainIntent == null) {
            throw new PackageManager.NameNotFoundException();
        }
    } catch (PackageManager.NameNotFoundException e) {
        cordovaMainIntent = new Intent();
    }
    PendingIntent pend = PendingIntent.getActivity(this, 0, cordovaMainIntent, 0);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ifString), 0);
    NotificationCompat.Action stop = new NotificationCompat.Action.Builder(android.R.drawable.ic_delete,
            "Stop recording", pendingIntent).build();
    note = new NotificationCompat.Builder(this).setContentTitle(applicationName + " GPS tracking")
            .setSmallIcon(android.R.drawable.ic_menu_mylocation).setOngoing(true).setContentIntent(pend)
            .setContentText("No location yet.");
    note.addAction(stop);

    nm = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
    nm.notify(0, note.build());

    recording = true;
    Log.d(LOG_TAG, "recording in handleIntent");
    try { // create directory first, if it does not exist
        File trackFile = new File(tf).getParentFile();
        if (!trackFile.exists()) {
            trackFile.mkdirs();
            Log.d(LOG_TAG, "done creating path for trackfile: " + trackFile);
        }
        Log.d(LOG_TAG, "going to create RandomAccessFile " + tf);
        myWriter = new RandomAccessFile(tf, "rw");
        if (intent != null) { // start new file
            // myWriter.setLength(0);    // delete all contents from file
            String trackName = intent.getStringExtra("trackName");
            String trackHead = initTrack(trackName).toString();
            myWriter.write(trackHead.getBytes());
            // we want to write JSON manually for streamed writing
            myWriter.seek(myWriter.length() - 1);
            myWriter.write(",\"coordinates\":[]}".getBytes());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "io error. cannot write to file " + tf);
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateTime, distanceChange, mgpsll);
    if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, updateTime, distanceChange,
                mnetll);
    }
    return START_STICKY;
}

From source file:com.google.android.gcm.GCMRegistrar.java

static void internalUnregister(Context context) {
    Log.v(TAG, "Unregistering app " + context.getPackageName());
    Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
    intent.setPackage(GSF_PACKAGE);/*from   w  w  w  . j a  v  a 2  s  .  co m*/
    intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
            PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    context.startService(intent);
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

/**
 * Schedules an alarm through the AlarmManager. Alarms are typically scheduled at time when courses begin or end.
 * @param time the time at which the alarm will go off
 * @param action the action that will be called when the alarm goes off
 *///from w w w . j  av a 2  s. c  o  m
private void scheduleAlarm(long time, int action, int alarmId) {
    Log.d(TAG, "scheduling alarm action " + action + " @ " + new Date(time).toLocaleString() + " (aID:"
            + alarmId + ")");

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(this, OnAlarmReceiver.class).putExtra(ACTION, action)
            .putExtra(EXTRA_ALARM_ID, alarmId);
    PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    time = SystemClock.elapsedRealtime() + (time - System.currentTimeMillis()); //  convert unixtime to system runtime
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, pendingAlarmIntent);
}

From source file:com.home.pr.opendoor.MainActivity.java

public void schedulePeriodicUpdate() {
    /*final Handler handler = new Handler();
    handler.postDelayed(new Runnable(){//from   www  . j  av  a2  s.c o  m
    @Override
    public void run() {
        handler.postDelayed(this,10000);
        Intent intent = new Intent(getApplicationContext(), AdafruitDoorStatus.class);
        getApplicationContext().startService(intent);
    }
    },10000);*/
    Intent intent = new Intent(this, StatusReceiver.class);
    PendingIntent pIntent = PendingIntent.getBroadcast(this, StatusReceiver.REQUEST_CODE, intent, 0);
    long firstMillis = System.currentTimeMillis();
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 10000, pIntent);
}

From source file:com.github.jvanhie.discogsscrobbler.util.NowPlayingService.java

private void play(final int trackNumber) {
    //do we even have something to play?
    if (trackList == null || trackList.size() == 0)
        return;/*from ww w . j  a v a2  s. c  o  m*/

    track = trackList.get(trackNumber);

    //don't play headings, on to the next! (if there is a next)
    if (track.type.equals("heading")) {
        if (trackNumber + 1 < trackList.size()) {
            play(trackNumber + 1);
        } else {
            stop();
        }
        return;
    }

    isPlaying = true;
    artist = track.artist;
    album = track.album;
    currentTrack = trackNumber;
    mNotificationBuilder.setContentTitle(track.title).setContentText(track.artist + " - " + track.album)
            .setWhen(System.currentTimeMillis()).setSmallIcon(android.R.drawable.ic_media_play);
    //fetch the duration (will return immediately when available) and start the alarm for when it's done
    mLastfm.getDuration(track, new Lastfm.LastfmWaiter() {
        @Override
        public void onResult(boolean success) {
            //set nowplaying, scrobbling happens on the alarm callback
            mLastfm.updateNowPlaying(track, new Lastfm.LastfmWaiter() {
                @Override
                public void onResult(boolean success) {
                    //the user already sees the notification, no need for extras notifications atm.
                }
            });

            //notify user
            startForeground(NOTIFICATION_ID, mNotificationBuilder.build());
            //update listeners to track change
            sendBroadcast(new Intent(TRACK_CHANGE));

            Intent intent = new Intent(NowPlayingService.this, NowPlayingAlarm.class);
            if (trackNumber < trackList.size() - 1) {
                intent.putExtra(NEXT_TRACK_ID, (trackNumber + 1));
                intent.putExtra(NEXT_TRACK_TITLE, trackList.get(trackNumber + 1).title);
            } else {
                //this is the last track, alarm will be used to stop the service (by issuing pos = -1 and title = first song title)
                intent.putExtra(NEXT_TRACK_ID, -1);
                intent.putExtra(NEXT_TRACK_TITLE, trackList.get(0).title);
            }
            mTrackStart = SystemClock.elapsedRealtime();
            int duration = Track.formatDurationToSeconds(track.duration);
            if (duration == 0)
                duration = Lastfm.DEFAULT_TRACK_DURATION;
            if (mTrackDone != 0)
                duration -= mTrackDone;
            mAlarmIntent = PendingIntent.getBroadcast(NowPlayingService.this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mTrackStart + duration * 1000,
                    mAlarmIntent);

        }
    });

}

From source file:com.hhunj.hhudata.ForegroundService.java

protected void clockRing() {
    Intent intent = new Intent(this, RepeatingAlarm.class);

    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

    long firstTime = m_workStartTime.getTime();
    long elaps = 24 * 60 * 60 * 1000;
    //long elaps = 15 * 1000;
    // Schedule the alarm!
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, elaps, sender);

    // Tell the user about what we did.
    if (mToast != null) {
        mToast.cancel();/*from   w  w w. j  a  v a2s  .c  om*/
    }
    mToast = Toast.makeText(this, "R.string.repeating_scheduled", Toast.LENGTH_LONG);
    mToast.show();

}

From source file:at.jclehner.rxdroid.NotificationReceiver.java

private PendingIntent createOperation(Bundle extras) {
    Intent intent = new Intent(mContext, NotificationReceiver.class);
    intent.setAction(Intent.ACTION_MAIN);

    if (extras != null)
        intent.putExtras(extras);/*from w  w  w.  j  ava 2s .c  om*/

    return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:org.mythdroid.util.UpdateService.java

private void checkMythDroid() {

    if (MDVer == null)
        return;/* w w w  .j a v  a 2s.c  o m*/

    Version runningVer;
    try {
        runningVer = new Version(getPackageManager().getPackageInfo(getPackageName(), 0).versionName, null);
    } catch (NameNotFoundException e) {
        return;
    }

    if (runningVer.compareTo(MDVer) >= 0) {
        LogUtil.debug("Already running latest version of MythDroid"); //$NON-NLS-1$
        return;
    }

    LogUtil.debug("Version " + MDVer.toString() + //$NON-NLS-1$
            " is available (current version is " + runningVer.toString() + ")" //$NON-NLS-1$ //$NON-NLS-2$
    );

    final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final Notification notification = new Notification(R.drawable.logo,
            Messages.getString("UpdateService.0") + "MythDroid" + //$NON-NLS-1$ //$NON-NLS-2$
                    Messages.getString("UpdateService.1"), //$NON-NLS-1$
            System.currentTimeMillis());

    notification.flags = Notification.FLAG_AUTO_CANCEL;

    final Intent intent = new Intent(MDACTION);
    intent.putExtra(VER, MDVer.toString());
    intent.putExtra(URL, MDVer.url.toString());

    notification.setLatestEventInfo(getApplicationContext(),
            "MythDroid" + Messages.getString("UpdateService.2"), //$NON-NLS-1$ //$NON-NLS-2$
            MDVer.toString() + Messages.getString("UpdateService.1") + //$NON-NLS-1$ 
                    Messages.getString("UpdateService.3"), //$NON-NLS-1$
            PendingIntent.getBroadcast(this, 0, intent, 0));

    nm.notify(CHECKMD, notification);

}