Example usage for android.app PendingIntent getActivity

List of usage examples for android.app PendingIntent getActivity

Introduction

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

Prototype

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

Source Link

Document

Retrieve a PendingIntent that will start a new activity, like calling Context#startActivity(Intent) Context.startActivity(Intent) .

Usage

From source file:io.coldstart.android.GCMIntentService.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void SendInboxStyleNotification(String alertCount, String alertTime, String hostname,
        String payloadDetails) {/* w w  w  .  j  ava 2  s  .  c  o  m*/
    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    String Line1 = "", Line2 = "", Line3 = "", Line4 = "", Line5 = "";
    String[] separatedLines = payloadDetails.split("\n");

    int payloadLength = separatedLines.length;
    if (payloadLength > 5)
        payloadLength = 5;

    for (int i = 0; i < payloadLength; i++) {
        try {
            switch (i) {
            case 0: {
                Line1 = separatedLines[i];
            }
                break;

            case 1: {
                Line2 = separatedLines[i];
            }
                break;

            case 2: {
                Line3 = separatedLines[i];
            }
                break;

            case 3: {
                Line4 = separatedLines[i];
            }
                break;

            case 4: {
                Line5 = separatedLines[i];
            }
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Notification notification = new Notification.InboxStyle(
            new Notification.Builder(this).setContentTitle("SNMP trap received")
                    .setContentText(Line1 + " " + Line2 + "...").setSmallIcon(R.drawable.ic_stat_alert)
                    .setVibrate(new long[] { 0, 100, 200, 300 }).setAutoCancel(true).setSound(uri)
                    .setPriority(Notification.PRIORITY_MAX).setTicker("New SNMP traps have been received")
                    .setContentIntent(PendingIntent.getActivity(this, 0,
                            new Intent(this, TrapListActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                                    .putExtra("forceRefresh", true),
                            0))).setBigContentTitle("New SNMP traps have been received")
                                    .setSummaryText("Launch ColdStart.io to Manage These Events").addLine(Line1)
                                    .addLine(Line2).addLine(Line3).addLine(Line4).build();

    notification.defaults |= Notification.DEFAULT_SOUND;

    mNM.notify(43523, notification);
}

From source file:com.flowzr.export.flowzr.FlowzrSyncEngine.java

public static void notifyUser(final String msg, final int pct) {
    Intent notificationIntent = new Intent(context, FlowzrSyncActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    if (mNotifyBuilder == null) {
        mNotifyBuilder = new NotificationCompat.Builder(context).setAutoCancel(true)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(context.getString(R.string.flowzr_sync_inprogress))
                .setSmallIcon(R.drawable.icon);

        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        // Sets an ID for the notification, so it can be updated         
    }/*from w  w  w .  ja  v  a 2 s  . com*/
    mNotifyBuilder.setContentText(msg);
    mNotifyBuilder.setContentIntent(pendingIntent);
    mNotifyBuilder.setAutoCancel(true).build();
    if (pct != 0) {
        mNotifyBuilder.setProgress(100, pct, false);
    }
    mNotificationManager.notify(NOTIFICATION_ID, mNotifyBuilder.build());
}

From source file:com.skubit.android.billing.BillingServiceBinder.java

@Override
public Bundle getAuthorizationIntent(int apiVersion, String packageName, String scopes) throws RemoteException {
    Bundle bundle = new Bundle();
    if (apiVersion != 1) {
        bundle.putInt("RESPONSE_CODE", BillingResponseCodes.RESULT_BILLING_UNAVAILABLE);
        return bundle;
    }//from w  ww .j  a  va  2s.  co  m
    int packValidate = validatePackageIsOwnedByCaller(packageName);
    if (packValidate != BillingResponseCodes.RESULT_OK) {
        Log.d(TAG, "Package is not owned by caller: " + packageName);
        bundle.putInt("RESPONSE_CODE", packValidate);
        return bundle;
    }
    Intent authorizationIntent = makeAuthorizationIntent(packageName, scopes);
    PendingIntent pending = PendingIntent.getActivity(mContext, (packageName + ":").hashCode(),
            authorizationIntent, 0);
    bundle.putParcelable("AUTHORIZATION_INTENT", pending);

    bundle.putInt("RESPONSE_CODE", BillingResponseCodes.RESULT_OK);
    return bundle;
}

From source file:edu.missouri.bas.service.SensorService.java

@SuppressWarnings("deprecation")
@Override//  w  ww . ja  va  2  s  .com
public void onCreate() {

    super.onCreate();
    Log.d(TAG, "Starting sensor service");
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundsMap = new HashMap<Integer, Integer>();
    soundsMap.put(SOUND1, mSoundPool.load(this, R.raw.bodysensor_alarm, 1));
    soundsMap.put(SOUND2, mSoundPool.load(this, R.raw.voice_notification, 1));

    serviceContext = this;

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothMacAddress = mBluetoothAdapter.getAddress();
    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Get location manager
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    activityRecognition = new ActivityRecognitionScan(getApplicationContext());
    activityRecognition.startActivityRecognitionScan();

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    serviceWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorServiceLock");
    serviceWakeLock.acquire();

    //Initialize start time
    stime = System.currentTimeMillis();

    //Setup calendar object
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(stime);

    /*
     * Setup notification manager
     */

    notification = new Notification(R.drawable.icon2, "Recorded", System.currentTimeMillis());
    notification.defaults = 0;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
    notifyIntent.setClass(this, MainActivity.class);

    /*
     * Display notification that service has started
     */
    notification.tickerText = "Sensor Service Running";
    PendingIntent contentIntent = PendingIntent.getActivity(SensorService.this, 0, notifyIntent,
            Notification.FLAG_ONGOING_EVENT);
    notification.setLatestEventInfo(SensorService.this, getString(R.string.app_name),
            "Recording service started at: " + cal.getTime().toString(), contentIntent);

    notificationManager.notify(SensorService.SERVICE_NOTIFICATION_ID, notification);

    // locationControl = new LocationControl(this, mLocationManager, 1000 * 60, 200, 5000);   

    IntentFilter activityResultFilter = new IntentFilter(XMLSurveyActivity.INTENT_ACTION_SURVEY_RESULTS);
    SensorService.this.registerReceiver(alarmReceiver, activityResultFilter);

    IntentFilter sensorDataFilter = new IntentFilter(SensorService.ACTION_SENSOR_DATA);
    SensorService.this.registerReceiver(alarmReceiver, sensorDataFilter);
    Log.d(TAG, "Sensor service created.");

    try {
        prepareIO();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    prepareAlarms();

    Intent startSensors = new Intent(SensorService.ACTION_START_SENSORS);
    this.sendBroadcast(startSensors);

    Intent scheduleCheckConnection = new Intent(SensorService.ACTION_SCHEDULE_CHECK);
    scheduleCheck = PendingIntent.getBroadcast(serviceContext, 0, scheduleCheckConnection, 0);
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000 * 60 * 5, 1000 * 60 * 5, scheduleCheck);
    mLocationClient = new LocationClient(this, this, this);
}

From source file:com.CPTeam.VselCalc.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");
    if (update_file.length() > 0) {
        // raise notification
        Notification notification = new Notification(appIcon, appName + " update", System.currentTimeMillis());
        notification.flags |= NOTIFICATION_FLAGS;

        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Select to install";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);/*from  w  ww . jav a 2s  .  c  om*/
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        nm.notify(NOTIFICATION_ID, notification);
    } else {
        nm.cancel(NOTIFICATION_ID);
    }
}

From source file:com.andrewshu.android.reddit.common.Common.java

public static void newMailNotification(Context context, String mailNotificationStyle, int count) {
    Intent nIntent = new Intent(context, InboxActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, nIntent, 0);
    Notification notification = new Notification(R.drawable.mail, Constants.HAVE_MAIL_TICKER,
            System.currentTimeMillis());
    if (Constants.PREF_MAIL_NOTIFICATION_STYLE_BIG_ENVELOPE.equals(mailNotificationStyle)) {
        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.big_envelope_notification);
        notification.contentView = contentView;
    } else {//  w w  w  .  j  a v  a 2s . c om
        notification.setLatestEventInfo(context, Constants.HAVE_MAIL_TITLE,
                count + (count == 1 ? " unread message" : " unread messages"), contentIntent);
    }
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    notification.contentIntent = contentIntent;
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Constants.NOTIFICATION_HAVE_MAIL, notification);
}

From source file:com.github.vseguip.sweet.contacts.SweetContactSync.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Log.i(TAG, "onPerformSync()");
    // Get preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean fullSync = settings.getBoolean(mContext.getString(R.string.full_sync), false);
    if (fullSync)
        mAccountManager.setUserData(account, LAST_SYNC_KEY, null);
    performNetOperation(new SugarRunnable(account, syncResult, new ISugarRunnable() {
        @Override/* ww  w  .  j a va 2  s  .c  om*/
        public void run() throws URISyntaxException, OperationCanceledException, AuthenticatorException,
                IOException, AuthenticationException {
            Log.i(TAG, "Running PerformSync closure()");

            mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, true);
            SugarAPI sugar = SugarAPIFactory.getSugarAPI(mAccountManager, account);
            String lastDate = mAccountManager.getUserData(account, LAST_SYNC_KEY);
            List<ISweetContact> contacts = null;
            try {
                contacts = fetchContacts(sugar, lastDate);
            } catch (AuthenticationException ex) {
                // maybe expired session, invalidate token and request new
                // one
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            } catch (NullPointerException npe) {
                // maybe expired session, invalidate token and request new
                // one               
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            }
            // try again, it could be due to an expired session
            if (contacts == null) {
                contacts = fetchContacts(sugar, lastDate);
            }
            List<ISweetContact> modifiedContacts = ContactManager.getLocallyModifiedContacts(mContext, account);
            List<ISweetContact> createdContacts = ContactManager.getLocallyCreatedContacts(mContext, account);
            // Get latest date from server
            for (ISweetContact c : contacts) {
                String contactDate = c.getDateModified();
                if ((lastDate == null) || (lastDate.compareTo(contactDate) < 0)) {
                    lastDate = contactDate;
                }
            }
            // Determine conflicting contacts
            Set<String> conflictSet = getConflictSet(contacts, modifiedContacts);
            Map<String, ISweetContact> conflictingSugarContacts = filterIds(contacts, conflictSet);
            Map<String, ISweetContact> conflictingLocalContacts = filterIds(modifiedContacts, conflictSet);

            if (modifiedContacts.size() > 0) {
                // Send modified local non conflicting contacts to the
                // server
                List<String> newIds = sugar.sendNewContacts(mAuthToken, modifiedContacts, false);
                if (newIds.size() != modifiedContacts.size()) {
                    throw new OperationCanceledException("Error updating local contacts in the remote server");
                }
                ContactManager.cleanDirtyFlag(mContext, modifiedContacts);
            }
            if (createdContacts.size() > 0) {
                List<String> newIds = sugar.sendNewContacts(mAuthToken, createdContacts, true);
                if (newIds.size() != createdContacts.size()) {
                    // something wrong happened, it's probable the user will
                    // have to clear the data
                    throw new OperationCanceledException("Error creating local contacts in the remote server");
                }
                ContactManager.assignSourceIds(mContext, createdContacts, newIds);
                ContactManager.cleanDirtyFlag(mContext, createdContacts);
            }
            // Sync remote contacts locally.
            if (contacts.size() > 0) {
                ContactManager.syncContacts(mContext, account, contacts);
            }
            // resolve remaining conflicts
            List<ISweetContact> resolvedContacts = new ArrayList<ISweetContact>();
            for (String id : conflictSet) {
                ISweetContact local = conflictingLocalContacts.get(id);
                ISweetContact remote = conflictingSugarContacts.get(id);
                if (local.equals(remote)) {
                    // no need to sync
                    resolvedContacts.add(local);
                    conflictingLocalContacts.remove(id);
                    conflictingSugarContacts.remove(id);
                } else {
                    Log.i(TAG, "Local contact differs from remote contact " + local.getFirstName() + " "
                            + local.getLastName());
                    if (local.equalUIFields(remote)) {
                        // Differed in a non visible field like the account
                        // id or similar, use server version and resolve
                        // automatically
                        resolvedContacts.add(remote);
                        conflictingLocalContacts.remove(id);
                        conflictingSugarContacts.remove(id);
                    }
                }

            }
            ContactManager.cleanDirtyFlag(mContext, resolvedContacts);
            if (conflictingLocalContacts.size() > 0) {
                // Create a notification that can launch an mActivity to
                // resolve the pending conflict
                NotificationManager nm = (NotificationManager) mContext
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.icon,
                        mContext.getString(R.string.notify_sync_conflict_ticket), System.currentTimeMillis());
                Intent intent = new Intent(mContext, SweetConflictResolveActivity.class);
                intent.putExtra("account", account);
                SweetConflictResolveActivity.storeConflicts(conflictingLocalContacts, conflictingSugarContacts);

                notify.setLatestEventInfo(mContext, mContext.getString(R.string.notify_sync_conflict_title),
                        mContext.getString(R.string.notify_sync_conflict_message),
                        PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
                nm.notify(SweetConflictResolveActivity.NOTIFY_CONFLICT,
                        SweetConflictResolveActivity.NOTIFY_CONTACT, notify);

                throw new OperationCanceledException("Pending conflicts");
            }
            // Save the last sync time in the account if all went ok
            mAccountManager.setUserData(account, LAST_SYNC_KEY, lastDate);
        }
    }));
}

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

private void notify(String title, String message) {

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

    Notification notification = new Notification(R.drawable.logo, title, System.currentTimeMillis());

    notification.flags = Notification.FLAG_AUTO_CANCEL;

    notification.setLatestEventInfo(getApplicationContext(), title, message,
            PendingIntent.getActivity(Globals.appContext, 0, new Intent(), 0));

    nm.notify(-1, notification);// w  w  w.  j  a va2  s . com
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void setNotification(FireMixtape song) {
    if (mPlaying == null) {
        stopForeground(true);//from w w  w.  j ava2s .  c om
        return;
    }
    setMetadata(song);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Notification is created in setMetadata
        return;
    }

    if (mNotification == null || mNotificationView == null) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 1, notificationIntent, 0);

        mNotificationView = new RemoteViews(getPackageName(), R.layout.notification);

        mNotification = new Notification.Builder(this).setSmallIcon(R.mipmap.sunaminotif)
                .setContentIntent(pendingIntent).setContent(mNotificationView).build();
    }

    Intent servicePlayIntent = new Intent(getApplicationContext(), TheBrain.class);
    servicePlayIntent.setAction(TheBrain.TOGGLE_PLAY);
    servicePlayIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    PendingIntent pendingPlayIntent = PendingIntent.getService(mContext, 1, servicePlayIntent, 0);
    Intent serviceNextIntent = new Intent(getApplicationContext(), TheBrain.class);
    serviceNextIntent.setAction(TheBrain.PLAY_NEXT);
    serviceNextIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    PendingIntent pendingNextIntent = PendingIntent.getService(mContext, 1, serviceNextIntent, 0);
    Intent serviceStopIntent = new Intent(getApplicationContext(), TheBrain.class);
    serviceStopIntent.setAction(TheBrain.PLAY_STOP);
    serviceStopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    PendingIntent pendingStopIntent = PendingIntent.getService(mContext, 1, serviceStopIntent, 0);

    mNotificationView.setTextViewText(R.id.notif_title, song.title);
    mNotificationView.setTextViewText(R.id.notif_artist, song.artist);
    mNotificationView.setOnClickPendingIntent(R.id.play_notif_button, pendingPlayIntent);
    mNotificationView.setOnClickPendingIntent(R.id.next_notif_button, pendingNextIntent);
    mNotificationView.setOnClickPendingIntent(R.id.close_notif_button, pendingStopIntent);

    setNotificationStatus(true);
}

From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java

private void showBatchUploadNotification(String text, int progress, boolean noClear) {
    if (notification == null) {
        notification = new Notification(R.drawable.ic_icon_export, text, System.currentTimeMillis());

        // final Intent appIntent = new Intent(this, SIDE.class);
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, 0);

        notification.setLatestEventInfo(this, getString(R.string.app_name), text, contentIntent);

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.batch_upload_notification_layout);
        contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_icon_export);
        notification.contentView = contentView;
    }/*from  w  w  w . j  a va 2 s . co  m*/

    notification.contentView.setTextViewText(R.id.status_text, text);
    notification.contentView.setProgressBar(R.id.progress_bar, MAX_PROGRESS, progress, false);

    if (noClear) {
        notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    } else {
        notificationManager.cancel(R.id.batch_upload);

        notification.flags ^= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    }
    notificationManager.notify(R.id.batch_upload, notification);
}