List of usage examples for android.app PendingIntent getActivity
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, @Flags int flags)
From source file:com.googlecode.android_scripting.facade.ui.NFCBeamTask.java
@SuppressLint("NewApi") public void launchNFC() { Log.d(TAG, "launchNFC:" + beamStat); if (beamStat == 0) { _nfcAdapter.setNdefPushMessageCallback(this, getActivity()); _nfcAdapter.setOnNdefPushCompleteCallback(this, getActivity()); // start NFC Connection /*_nfcPendingIntent = PendingIntent.getActivity(getActivity().getApplicationContext(), 0, new Intent(getActivity().getApplicationContext(), FutureActivity.class) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); /*from www . ja v a 2 s. co m*/ IntentFilter ndefDetected = new IntentFilter( NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndefDetected.addDataType("application/com.hipipal.qpy.nfc"); } catch (MalformedMimeTypeException e) { throw new RuntimeException("Could not add MIME type.", e); } _readTagFilters = new IntentFilter[] { ndefDetected };*/ } else if (beamStat == 1) { //_nfcAdapter.setNdefPushMessageCallback(this, getActivity()); //_nfcAdapter.setOnNdefPushCompleteCallback(this, getActivity()); // start NFC Connection _nfcPendingIntent = PendingIntent.getActivity(getActivity().getApplicationContext(), 0, new Intent(getActivity().getApplicationContext(), FutureActivity.class) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndefDetected.addDataType("application/com.hipipal.qpy.nfc"); } catch (MalformedMimeTypeException e) { throw new RuntimeException("Could not add MIME type.", e); } _readTagFilters = new IntentFilter[] { ndefDetected }; } }
From source file:com.iss.android.wearable.datalayer.MainActivity.java
private void initializeSelfRestarting() { pendingInt = PendingIntent.getActivity(this, 0, new Intent(getIntent()), getIntent().getFlags()); // Intent that kills the app after a certain amount of time after the app has crashed murderousIntent = new Intent(this, SensorsDataService.class); // start handler which starts pending-intent after Application Crash /*Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override//from ww w .j ava 2 s. co m public void uncaughtException(Thread paramThread, Throwable paramThrowable) { Log.d("Killer", "kills"); // something went wrong ... this cannot continue like this anymore ... // we need to start everything from scratch ... AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 10000, pendingInt); // under the circumstances I have no choice but to murder the service and the app itself ... // put it out of its misery ... stopService(murderousIntent); android.os.Process.killProcess(android.os.Process.myPid()); // It will hunt me until the end of my days in my nightmares... // My darkest secret, slowly eating on my soul and driving me mad ... System.exit(2); } });/**/ }
From source file:mobisocial.musubi.identity.AphidIdentityProvider.java
private void sendNotification(String account) { Intent launch = new Intent(mContext, SettingsActivity.class); launch.putExtra(SettingsActivity.ACTION, SettingsActivity.SettingsAction.ACCOUNT.toString()); PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, launch, PendingIntent.FLAG_CANCEL_CURRENT); (new PresenceAwareNotify(mContext)).notify(SIGNIN_TEXT, account + " account failed to connect", contentIntent);//from w w w .j av a 2 s. c o m }
From source file:at.jclehner.rxdroid.NotificationReceiver.java
private PendingIntent createDrugListIntent(Date date) { final Intent intent = new Intent(mContext, DrugListActivity.class); intent.putExtra(DrugListActivity.EXTRA_STARTED_FROM_NOTIFICATION, true); intent.putExtra(DrugListActivity.EXTRA_DATE, date); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); return PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
From source file:net.sf.asap.PlayerService.java
public void run() { // read file/* w w w. j av a2s . c o m*/ String filename = uri.getPath(); byte[] module = new byte[ASAPInfo.MAX_MODULE_LENGTH]; int moduleLen; try { InputStream is; switch (uri.getScheme()) { case "file": if (Util.isZip(filename)) { String zipFilename = filename; filename = uri.getFragment(); is = new ZipInputStream(zipFilename, filename); } else is = new FileInputStream(filename); break; case "http": is = httpGet(uri); break; default: throw new FileNotFoundException(uri.toString()); } moduleLen = Util.readAndClose(is, module); } catch (IOException ex) { showError(R.string.error_reading_file); return; } // load file try { asap.load(filename, module, moduleLen); info = asap.getInfo(); switch (song) { case SONG_DEFAULT: song = info.getDefaultSong(); break; case SONG_LAST: song = info.getSongs() - 1; break; default: break; } playSong(); } catch (Exception ex) { showError(R.string.invalid_file); return; } PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Player.class), 0); String title = info.getTitleOrFilename(); Notification notification = new Notification(R.drawable.icon, title, System.currentTimeMillis()); notification.flags |= Notification.FLAG_ONGOING_EVENT; notification.setLatestEventInfo(this, title, info.getAuthor(), contentIntent); startForegroundCompat(NOTIFICATION_ID, notification); // playback int channelConfig = info.getChannels() == 1 ? AudioFormat.CHANNEL_CONFIGURATION_MONO : AudioFormat.CHANNEL_CONFIGURATION_STEREO; int bufferLen = AudioTrack.getMinBufferSize(ASAP.SAMPLE_RATE, channelConfig, AudioFormat.ENCODING_PCM_16BIT) >> 1; if (bufferLen < 16384) bufferLen = 16384; final byte[] byteBuffer = new byte[bufferLen << 1]; final short[] shortBuffer = new short[bufferLen]; audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, ASAP.SAMPLE_RATE, channelConfig, AudioFormat.ENCODING_PCM_16BIT, bufferLen << 1, AudioTrack.MODE_STREAM); audioTrack.play(); for (;;) { synchronized (this) { if (bufferLen < shortBuffer.length || isPaused()) { try { wait(); } catch (InterruptedException ex) { } } if (stop) { audioTrack.stop(); return; } } synchronized (asap) { int pos = seekPosition; if (pos >= 0) { seekPosition = -1; try { asap.seek(pos); } catch (Exception ex) { } } bufferLen = asap.generate(byteBuffer, byteBuffer.length, ASAPSampleFormat.S16_L_E) >> 1; } for (int i = 0; i < bufferLen; i++) shortBuffer[i] = (short) ((byteBuffer[i << 1] & 0xff) | byteBuffer[i << 1 | 1] << 8); audioTrack.write(shortBuffer, 0, bufferLen); } }
From source file:com.maass.android.imgur_uploader.ImgurUpload.java
/** * This method uploads an image from the given uri. It does the uploading in * small chunks to make sure it doesn't over run the memory. * /* w w w . j av a 2 s .c o m*/ * @param uri * image location * @return map containing data from interaction */ private String readPictureDataAndUpload(final Uri uri) { Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)"); try { final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); final int totalFileLength = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); // Create custom progress notification mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress), System.currentTimeMillis()); // set as ongoing mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT; // set custom view to notification mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength); //empty intent for the notification final Intent progressIntent = new Intent(); final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0); mProgressNotification.contentIntent = contentIntent; // add notification to manager mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); final InputStream inputStream = getContentResolver().openInputStream(uri); final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis()) + Long.toHexString((new Random()).nextLong()); final String boundary = "--" + boundaryString; final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json")) .openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\""); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(CHUNK_SIZE); final OutputStream hrout = conn.getOutputStream(); final PrintStream hout = new PrintStream(hrout); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"key\""); hout.println("Content-Type: text/plain"); hout.println(); hout.println(API_KEY); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"image\""); hout.println("Content-Transfer-Encoding: base64"); hout.println(); hout.flush(); { final Base64OutputStream bhout = new Base64OutputStream(hrout); final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES]; int read = 0; int totalRead = 0; long lastLogTime = 0; while (read >= 0) { read = inputStream.read(pictureData); if (read > 0) { bhout.write(pictureData, 0, read); totalRead += read; if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) { lastLogTime = System.currentTimeMillis(); Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength + " bytes (" + (100 * totalRead) / totalFileLength + "%)"); //make a final version of the total read to make the handler happy final int totalReadFinal = totalRead; mHandler.post(new Runnable() { public void run() { mProgressNotification.contentView = generateProgressNotificationView( totalReadFinal, totalFileLength); mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); } }); } bhout.flush(); hrout.flush(); } } Log.d(this.getClass().getName(), "Finishing upload..."); // This close is absolutely necessary, this tells the // Base64OutputStream to finish writing the last of the data // (and including the padding). Without this line, it will miss // the last 4 chars in the output, missing up to 3 bytes in the // final output. bhout.close(); Log.d(this.getClass().getName(), "Upload complete..."); mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead, false); } hout.println(boundary); hout.flush(); hrout.close(); inputStream.close(); Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server"); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder rData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { rData.append(line).append('\n'); } return rData.toString(); } catch (final IOException e) { Log.e(this.getClass().getName(), "Upload failed", e); } return null; }
From source file:com.owncloud.android.ui.activity.FileDisplayActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { Log_OC.d(TAG, "onCreate() start"); // Log.d(TAG,"called first"); super.onCreate(savedInstanceState); // this calls onAccountChanged() // when ownCloud Account is valid // requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (AccountUtils.getCurrentOwnCloudAccount(getBaseContext()) != null) { Intent intent = new Intent(this, InitialPageActivity.class); startActivity(intent);//w ww .j a va 2 s . c om } mHandler = new Handler(); // / bindings to transference services mUploadConnection = new ListServiceConnection(); mDownloadConnection = new ListServiceConnection(); bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE); bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE); shareNotifier = new NotificationCompat.Builder(this).setContentTitle("File Shared") .setSmallIcon(R.drawable.icon); Button shareButton = (Button) findViewById(R.id.shareItem); Intent fileShareIntent = new Intent(this, FileDisplayActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, 0, fileShareIntent, 0); shareNotifier.setContentIntent(pIntent); shareNotifier.setAutoCancel(true); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); dataSource = new DbFriends(this); // ContentResolver.setIsSyncable(getAccount(), // AccountAuthenticator.AUTHORITY, 1); // ContentResolver.setSyncAutomatically(getAccount(), // AccountAuthenticator.AUTHORITY,true); // broadcast receiver that is called by the service which downloads the // files to the phone instantdownloadreceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("message"); instantDownloadFile(); // make the http request and update the ui to include the sharer // information // unregisterReceiver(instantdownloadreceiver); } }; // PIN CODE request ; best location is to decide, let's try this first if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) { requestPinCode(); } // / file observer Intent observer_intent = new Intent(this, FileObserverService.class); observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST); startService(observer_intent); // / Load of saved instance state if (savedInstanceState != null) { mWaitingToPreview = (OCFile) savedInstanceState .getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW); } else { mWaitingToPreview = null; } // / USER INTERFACE // Inflate and set the layout view setContentView(R.layout.files); mDualPane = getResources().getBoolean(R.bool.large_land_layout); mLeftFragmentContainer = findViewById(R.id.left_fragment_container); mRightFragmentContainer = findViewById(R.id.right_fragment_container); if (savedInstanceState == null) { createMinFragments(); } // Action bar setup mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item); getSupportActionBar().setHomeButtonEnabled(true); // mandatory since // Android ICS, // according to the // official // documentation setSupportProgressBarIndeterminateVisibility(false); // always AFTER // setContentView(...) // ; to work around // bug in its // implementation Log_OC.d(TAG, "onCreate() end"); }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushIntentService.java
private void generateNotification(Context context, String ticker, String title, String msg, int icon, Intent intent, String sound, int notificationId, MFPInternalPushMessage message) { int androidSDKVersion = Build.VERSION.SDK_INT; long when = System.currentTimeMillis(); Notification notification = null; NotificationCompat.Builder builder = new NotificationCompat.Builder(this); if (message.getGcmStyle() != null && androidSDKVersion > 21) { NotificationCompat.Builder mBuilder = null; NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); try {//from w w w. j av a2s .com JSONObject gcmStyleObject = new JSONObject(message.getGcmStyle()); String type = gcmStyleObject.getString(TYPE); if (type != null && type.equalsIgnoreCase(PICTURE_NOTIFICATION)) { Bitmap remote_picture = null; NotificationCompat.BigPictureStyle notificationStyle = new NotificationCompat.BigPictureStyle(); notificationStyle.setBigContentTitle(ticker); notificationStyle.setSummaryText(gcmStyleObject.getString(TITLE)); try { remote_picture = new getBitMapBigPictureNotification() .execute(gcmStyleObject.getString(URL)).get(); } catch (Exception e) { logger.error( "MFPPushIntentService:generateNotification() - Error while fetching image file."); } if (remote_picture != null) { notificationStyle.bigPicture(remote_picture); } mBuilder = new NotificationCompat.Builder(context); notification = mBuilder.setSmallIcon(icon).setLargeIcon(remote_picture).setAutoCancel(true) .setContentTitle(title) .setContentIntent(PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT)) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentText(msg).setStyle(notificationStyle).build(); } else if (type != null && type.equalsIgnoreCase(BIGTEXT_NOTIFICATION)) { NotificationCompat.BigTextStyle notificationStyle = new NotificationCompat.BigTextStyle(); notificationStyle.setBigContentTitle(ticker); notificationStyle.setSummaryText(gcmStyleObject.getString(TITLE)); notificationStyle.bigText(gcmStyleObject.getString(TEXT)); mBuilder = new NotificationCompat.Builder(context); notification = mBuilder.setSmallIcon(icon).setAutoCancel(true).setContentTitle(title) .setContentIntent(PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT)) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentText(msg).setStyle(notificationStyle).build(); } else if (type != null && type.equalsIgnoreCase(INBOX_NOTIFICATION)) { NotificationCompat.InboxStyle notificationStyle = new NotificationCompat.InboxStyle(); notificationStyle.setBigContentTitle(ticker); notificationStyle.setSummaryText(gcmStyleObject.getString(TITLE)); String lines = gcmStyleObject.getString(LINES).replaceAll("\\[", "").replaceAll("\\]", ""); String[] lineArray = lines.split(","); for (String line : lineArray) { notificationStyle.addLine(line); } mBuilder = new NotificationCompat.Builder(context); notification = mBuilder.setSmallIcon(icon).setAutoCancel(true).setContentTitle(title) .setContentIntent(PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT)) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentText(msg).setStyle(notificationStyle).build(); } notification.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(notificationId, notification); } catch (JSONException e) { logger.error("MFPPushIntentService:generateNotification() - Error while parsing JSON."); } } else { if (androidSDKVersion > 10) { builder.setContentIntent(PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT)).setSmallIcon(icon).setTicker(ticker).setWhen(when) .setAutoCancel(true).setContentTitle(title).setContentText(msg) .setSound(getNotificationSoundUri(context, sound)); if (androidSDKVersion > 15) { int priority = getPriorityOfMessage(message); builder.setPriority(priority); notification = builder.build(); } if (androidSDKVersion > 19) { //As new material theme is very light, the icon is not shown clearly //hence setting the background of icon to black builder.setColor(Color.BLACK); Boolean isBridgeSet = message.getBridge(); if (!isBridgeSet) { // show notification only on current device. builder.setLocalOnly(true); } notification = builder.build(); int receivedVisibility = 1; String visibility = message.getVisibility(); if (visibility != null && visibility.equalsIgnoreCase(MFPPushConstants.VISIBILITY_PRIVATE)) { receivedVisibility = 0; } if (receivedVisibility == Notification.VISIBILITY_PRIVATE && message.getRedact() != null) { builder.setContentIntent(PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT)).setSmallIcon(icon).setTicker(ticker) .setWhen(when).setAutoCancel(true).setContentTitle(title) .setContentText(message.getRedact()) .setSound(getNotificationSoundUri(context, sound)); notification.publicVersion = builder.build(); } } if (androidSDKVersion > 21) { String setPriority = message.getPriority(); if (setPriority != null && setPriority.equalsIgnoreCase(MFPPushConstants.PRIORITY_MAX)) { //heads-up notification builder.setContentText(msg).setFullScreenIntent(PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT), true); notification = builder.build(); } } } else { notification = builder .setContentIntent( PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)) .setSmallIcon(icon).setTicker(ticker).setWhen(when).setAutoCancel(true) .setContentTitle(title).setContentText(msg) .setSound(getNotificationSoundUri(context, sound)).build(); } NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationId, notification); } }
From source file:anastasoft.rallyvision.activity.MenuPrincipal.java
private void createNotification() { Intent resultIntent = new Intent(this, MenuPrincipal.class); // Because clicking the notification opens a new ("special") activity, there's // no need to create an artificial back stack. PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_notify).setContentTitle(getString(R.string.notification_title)) .setContentText(getString(R.string.notification_text)).setContentInfo(getString(R.string.app_name)) .setAutoCancel(true).setOngoing(true).setTicker(getString(R.string.notification_ticker)); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // mId allows you to setState the notification later on. Notification notification = mBuilder.build(); mNotificationManager.notify(NOTIFICATION_ID, notification); }
From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java
private static void issueBlogNotification(Context context) { String title = context.getString(R.string.notification_title); String message = context.getString(R.string.blog_notification_content); PendingIntent pendingIntent;// www. j av a2 s.c o m try { pendingIntent = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.PAPYROS_BLOG_URL)), PendingIntent.FLAG_UPDATE_CURRENT); } catch (Exception e) { e.printStackTrace(); return; } NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(title) .setContentText(message).setContentIntent(pendingIntent) .setSmallIcon(R.mipmap.notification_small_icon) .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) .setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(BLOG_NOTIFICATION_ID, builder.build()); }