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: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  v a2 s .  co  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.rjfun.cordova.sms.SMSPlugin.java

private PluginResult sendSMS(JSONArray addressList, String text, CallbackContext callbackContext) {
    Log.d(LOGTAG, ACTION_SEND_SMS);//from   w  w w  .ja  v  a  2 s .  co  m
    if (this.cordova.getActivity().getPackageManager().hasSystemFeature("android.hardware.telephony")) {
        int n;
        if ((n = addressList.length()) > 0) {
            PendingIntent sentIntent = PendingIntent.getBroadcast((Context) this.cordova.getActivity(), (int) 0,
                    (Intent) new Intent("SENDING_SMS"), (int) 0);
            SmsManager sms = SmsManager.getDefault();
            for (int i = 0; i < n; ++i) {
                String address;
                if ((address = addressList.optString(i)).length() <= 0)
                    continue;
                sms.sendTextMessage(address, null, text, sentIntent, (PendingIntent) null);
            }
        } else {
            PendingIntent sentIntent = PendingIntent.getActivity((Context) this.cordova.getActivity(), (int) 0,
                    (Intent) new Intent("android.intent.action.VIEW"), (int) 0);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.putExtra("sms_body", text);
            intent.setType("vnd.android-dir/mms-sms");
            try {
                sentIntent.send(this.cordova.getActivity().getApplicationContext(), 0, intent);
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "OK"));
    } else {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "SMS is not supported"));
    }
    return null;
}

From source file:com.marianhello.bgloc.LocationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    log.info("Received start startId: {} intent: {}", startId, intent);

    if (provider != null) {
        provider.onDestroy();/*from  w w  w .ja  v  a 2  s .  co m*/
    }

    if (intent == null) {
        //service has been probably restarted so we need to load config from db
        ConfigurationDAO dao = DAOFactory.createConfigurationDAO(this);
        try {
            config = dao.retrieveConfiguration();
        } catch (JSONException e) {
            log.error("Config exception: {}", e.getMessage());
            config = new Config(); //using default config
        }
    } else {
        if (intent.hasExtra("config")) {
            config = intent.getParcelableExtra("config");
        } else {
            config = new Config(); //using default config
        }
    }

    log.debug("Will start service with: {}", config.toString());

    LocationProviderFactory spf = new LocationProviderFactory(this);
    provider = spf.getInstance(config.getLocationProvider());

    if (config.getStartForeground()) {
        // Build a Notification required for running service in foreground.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(config.getNotificationTitle());
        builder.setContentText(config.getNotificationText());
        if (config.getSmallNotificationIcon() != null) {
            builder.setSmallIcon(getDrawableResource(config.getSmallNotificationIcon()));
        } else {
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
        }
        if (config.getLargeNotificationIcon() != null) {
            builder.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),
                    getDrawableResource(config.getLargeNotificationIcon())));
        }
        if (config.getNotificationIconColor() != null) {
            builder.setColor(this.parseNotificationIconColor(config.getNotificationIconColor()));
        }

        // Add an onclick handler to the notification
        Context context = getApplicationContext();
        String packageName = context.getPackageName();
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE
                | Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
    }

    provider.startRecording();

    //We want this service to continue running until it is explicitly stopped
    return START_STICKY;
}

From source file:com.digi.android.wva.VehicleInfoService.java

/**
 * Depending on if the service is currently set as 'connected'
 * (check value of {@code isConnected} boolean), either call
 * {@link #startForeground(int, Notification)} to put up the
 * "service is running" notification, or call
 * {@link #stopForeground(boolean) stopForeground(true)} to remove the
 * notification (because the service isn't listening).
  *//from  w  ww .  j  a v  a 2s .co m
  * <p>This method is protected, rather than private, due to a bug between JaCoCo and
  * the Android build tools which causes the instrumented bytecode to be invalid when this
  * method is private:
  * http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode
  * </p>
 */
protected void showNotificationIfRunning() {
    // First, c
    WvaApplication app = (WvaApplication) getApplication();
    if (app != null && app.isTesting())
        return;

    if (isConnected) {
        NotificationCompat.Builder builder;
        builder = new NotificationCompat.Builder(getApplicationContext());
        PendingIntent contentIntent;
        Intent intent = new Intent(VehicleInfoService.this, DashboardActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        contentIntent = PendingIntent.getActivity(VehicleInfoService.this, 0, intent, 0);
        builder.setContentTitle("Digi WVA Service")
                .setContentText("Connected to " + (TextUtils.isEmpty(connectIp) ? "(null)" : connectIp))
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setSmallIcon(R.drawable.notif_small).setOngoing(true).setContentIntent(contentIntent);

        startForeground(NOTIF_ID, builder.build());
    } else {
        try {
            stopForeground(true);
        } catch (Exception e) {
            // Might happen if startForeground not called before
            e.printStackTrace();
        }
    }
}

From source file:kr.co.bettersoft.checkmileage.activities.GCMIntentService.java

/**
 * generateNotification//w ww .  j av  a2 s .  com
 * Issues a notification to inform the user that server has sent a message.
 * @param context
 * @param message
 * @return
 */
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when); // sdf
    String title = context.getString(R.string.app_name);
    String mileageUpdateStr = context.getString(R.string.mileage_noti);
    Intent notificationIntent;
    /*
     * MILEAGE :  ? ??  ? ???.
     * MARKETING : ?? ?    ?.
     * Check Mileage     ?. : test ..
     * 
     * <string name="gcm_new_msgkkk"> </string>
     */
    String new_msg = " ";

    if (message.equals(new_msg)) {
        Log.d(TAG, "new msg - test");
        notificationIntent = new Intent(context, DummyActivity.class);
        //            notificationIntent.putExtra("RunMode", "TEST");                  // ?? ? . ?? .. ?   ..
        notificationIntent.putExtra("RunMode", "MILEAGE"); //

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | Intent.FLAG_ACTIVITY_CLEAR_TOP 
        //                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);

        //        }else if(message.contains("MILEAGE")){
        //        }else if(message.contains(mileageUpdateStr)){         // ?? ?. ()
    } else if (message.equals(mileageUpdateStr)) { // ?? ?. ().
        Log.d(TAG, "update mileage");
        MyMileagePageActivity.searched = false;
        //           notificationIntent = new Intent(context, MainActivity.class);      // ? ?  ?..
        notificationIntent = new Intent(context, DummyActivity.class);
        notificationIntent.putExtra("RunMode", "MILEAGE");

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | Intent.FLAG_ACTIVITY_CLEAR_TOP 
        //                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    } else if (message.equals("MARKETING")) {
        Log.d(TAG, "noti event push");
        //           notificationIntent = new Intent(context, MainActivity.class);      // ? ?  ? ?  ..
        notificationIntent = new Intent(context, DummyActivity.class);
        notificationIntent.putExtra("RunMode", "MARKETING");
        notificationIntent.putExtra("MESSAGE", "New Event");
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | Intent.FLAG_ACTIVITY_CLEAR_TOP 
        //                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    } else { //  ?.
        Log.d(TAG, "noti event push");
        //           notificationIntent = new Intent(context, MainActivity.class);      // ? ?  ? ?  ..
        notificationIntent = new Intent(context, DummyActivity.class);
        notificationIntent.putExtra("RunMode", "MARKETING");
        notificationIntent.putExtra("MESSAGE", message);

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
        //                    | Intent.FLAG_ACTIVITY_CLEAR_TOP 
        //                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    }
}

From source file:net.ccghe.emocha.services.ServerService.java

private void showNotification(String tickertxt, String displayTxt, int max, int progress) {
    NotificationManager notifMgr = (NotificationManager) this.getSystemService(Service.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainMenu.class), 0);

    // construct the Notification object.
    Notification notif = new Notification();

    notif.tickerText = tickertxt;//w ww  .  j  a  v  a2  s . c  o  m
    notif.icon = R.drawable.icon;

    nmView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
    nmView.setProgressBar(R.id.progressbar, max, progress, false);
    nmView.setTextViewText(R.id.TextView01, displayTxt);

    notif.contentView = nmView;

    notif.contentIntent = contentIntent;
    notifMgr.notify(R.layout.custom_notification_layout, notif);
}

From source file:com.pti.mates.GcmIntentService.java

private void sendNotificationMate(String msg) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    /*Cursor caux;//w  ww. j  av  a2s .  c  o m
    caux = getApplicationContext().getContentResolver().query(DataProvider.CONTENT_URI_PROFILE, new String[] {DataProvider.COL_ID}, DataProvider.COL_FBID + "=" + senderid, null, null);
    Intent intent = new Intent(this, ChatActivity.class);
    intent.putExtra(Common.PROFILE_ID, caux.getString(caux.getColumnIndex(DataProvider.COL_ID)));*/
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(getApplicationContext(), MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Congratulations!")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:net.majorkernelpanic.spydroid.SpydroidActivity.java

public void onStart() {
    super.onStart();

    // Lock screen
    wl.acquire();/*  ww  w. j  av  a2 s .c o m*/

    Intent notificationIntent = new Intent(this, SpydroidActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    Notification notification = builder.setContentIntent(pendingIntent).setWhen(System.currentTimeMillis())
            .setTicker(getText(R.string.notification_title)).setSmallIcon(R.drawable.icon)
            .setContentTitle(getText(R.string.notification_title))
            .setContentText(getText(R.string.notification_content)).build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);

}

From source file:com.userhook.UserHook.java

public static Notification handlePushMessage(Map<String, String> data) {

    String message = data.get("message");
    String title = "";

    if (data.containsKey("title") && data.get("title") != null) {
        title = data.get("title");
    } else {//  ww  w  . j  a v a 2  s .  co  m
        title = applicationContext.getApplicationInfo().loadLabel(applicationContext.getPackageManager())
                .toString();
    }

    Map<String, Object> payload = new HashMap<>();
    if (data.containsKey("payload")) {
        try {
            JSONObject json = new JSONObject(data.get("payload"));
            payload = UHJsonUtils.toMap(json);

            // check if this is a feedback reply
            if (json.has("new_feedback") && json.getBoolean("new_feedback")) {
                UserHook.setHasNewFeedback(true);
            } else {
                UserHook.setHasNewFeedback(false);
            }

        } catch (JSONException e) {
            Log.e("uh", "error parsing push notification payload");
        }
    }

    // message received
    Intent intent;

    if (pushMessageListener != null) {
        intent = pushMessageListener.onPushMessage(payload);
    } else {
        // default to opening the main activity
        intent = applicationContext.getPackageManager()
                .getLaunchIntentForPackage(applicationContext.getPackageName());
    }

    // convert data to a try Map<String,String> since it will come in as an ArrayMap
    if (data instanceof ArrayMap) {
        HashMap<String, String> hashMap = new HashMap<>();
        for (String key : data.keySet()) {
            hashMap.put(key, data.get(key));
        }
        data = hashMap;
    }

    intent.putExtra(UserHook.UH_PUSH_DATA, (Serializable) data);
    intent.putExtra(UserHook.UH_PUSH_TRACKED, false);
    if (payload.size() > 0) {
        intent.putExtra(UserHook.UH_PUSH_PAYLOAD, data.get("payload"));
    }

    //PendingIntent.FLAG_UPDATE_CURRENT is required to pass along our Intent Extras
    PendingIntent pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    try {
        ApplicationInfo appInfo = applicationContext.getPackageManager()
                .getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);

        int pushIcon = appInfo.icon;
        // check for a custom push icon
        if (pushNotificationIcon > 0) {
            pushIcon = pushNotificationIcon;
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext)
                .setSmallIcon(pushIcon).setContentText(message).setContentTitle(title).setAutoCancel(true)
                .setContentIntent(pendingIntent);

        // use default sound
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);

        return notificationBuilder.build();

    } catch (Exception e) {
        Log.e("uh", "error create push notification", e);
        return null;
    }

}

From source file:com.pandoroid.PandoraRadioService.java

public void setNotification() {
    if (!m_paused) {
        try {/*from   w  w  w.  j  a  v  a 2 s .c  om*/
            Song tmp_song;
            tmp_song = m_song_playback.getSong();
            Notification notification = new Notification(R.drawable.icon, "Pandoroid Radio",
                    System.currentTimeMillis());
            Intent notificationIntent = new Intent(this, PandoroidPlayer.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_SONG_PLAYING,
                    notificationIntent, 0);
            notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;
            notification.setLatestEventInfo(getApplicationContext(), tmp_song.getTitle(),
                    tmp_song.getArtist() + " on " + tmp_song.getAlbum(), contentIntent);
            startForeground(NOTIFICATION_SONG_PLAYING, notification);
        } catch (Exception e) {
        }
    }
}