List of usage examples for android.app NotificationManager cancel
public void cancel(int id)
From source file:android.app.Activity.java
/** * Called as part of the activity lifecycle when an activity is going into * the background, but has not (yet) been killed. The counterpart to * {@link #onResume}.// w ww .jav a 2 s . c om * * <p>When activity B is launched in front of activity A, this callback will * be invoked on A. B will not be created until A's {@link #onPause} returns, * so be sure to not do anything lengthy here. * * <p>This callback is mostly used for saving any persistent state the * activity is editing, to present a "edit in place" model to the user and * making sure nothing is lost if there are not enough resources to start * the new activity without first killing this one. This is also a good * place to do things like stop animations and other things that consume a * noticeable amount of CPU in order to make the switch to the next activity * as fast as possible, or to close resources that are exclusive access * such as the camera. * * <p>In situations where the system needs more memory it may kill paused * processes to reclaim resources. Because of this, you should be sure * that all of your state is saved by the time you return from * this function. In general {@link #onSaveInstanceState} is used to save * per-instance state in the activity and this method is used to store * global persistent data (in content providers, files, etc.) * * <p>After receiving this call you will usually receive a following call * to {@link #onStop} (after the next activity has been resumed and * displayed), however in some cases there will be a direct call back to * {@link #onResume} without going through the stopped state. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onResume * @see #onSaveInstanceState * @see #onStop */ protected void onPause() { if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this); getApplication().dispatchActivityPaused(this); mCalled = true; /* remove the migration notification */ NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(Process.myUid()); /* set Bundle for migration */ if (isAvailable()) { Bundle tmpBundle = new Bundle(); performSaveInstanceState(tmpBundle); systemMigrate(tmpBundle); } }
From source file:com.krayzk9s.imgurholo.services.DownloadService.java
@Override protected void onHandleIntent(Intent intent) { final NotificationManager notificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); ids = intent.getParcelableArrayListExtra("ids"); albumName = "/"; downloaded = 0;/*w ww . j av a 2 s. c o m*/ if (ids.size() > 0) { albumName += intent.getStringExtra("albumName") + "/"; File myDirectory = new File( android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName); if (!myDirectory.exists()) { myDirectory.mkdirs(); } } for (int i = 0; i < ids.size(); i++) { try { final String type = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE) .split("/")[1]; final String id = ids.get(i).getJSONObject().getString("id"); final String link = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK); Log.d("data", ids.get(i).getJSONObject().toString()); Log.d(ImgurHoloActivity.IMAGE_DATA_TYPE, ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE).split("/")[1]); Log.d("id", ids.get(i).getJSONObject().getString("id")); Log.d(ImgurHoloActivity.IMAGE_DATA_LINK, ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK)); final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setContentTitle(getString(R.string.picture_download)) .setContentText(getString(R.string.download_in_progress)) .setSmallIcon(R.drawable.icon_desaturated); Ion.with(getApplicationContext(), link).progress(new ProgressCallback() { @Override public void onProgress(int i, int i2) { notificationBuilder.setProgress(i2, i, false); } }).write(new File( android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + albumName + id + "." + type)) .setCallback(new FutureCallback<File>() { @Override public void onCompleted(Exception e, File file) { if (file == null) return; downloaded += 1; if (downloaded == ids.size()) { NotificationCompat.Builder notificationComplete = new NotificationCompat.Builder( getApplicationContext()); if (ids.size() == 1) { Intent viewImageIntent = new Intent(Intent.ACTION_VIEW); viewImageIntent.setDataAndType(Uri.fromFile(file), "image/*"); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); shareIntent.setType("image/*"); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); PendingIntent viewImagePendingIntent = PendingIntent.getActivity( getApplicationContext(), (int) System.currentTimeMillis(), viewImageIntent, 0); PendingIntent sharePendingIntent = PendingIntent.getActivity( getApplicationContext(), (int) System.currentTimeMillis(), shareIntent, 0); notificationComplete.setContentTitle(getString(R.string.download_complete)) .setSmallIcon(R.drawable.icon_desaturated) .setContentText(String.format(getString(R.string.download_progress), downloaded)) .setContentIntent(viewImagePendingIntent) .addAction(R.drawable.dark_social_share, getString(R.string.share), sharePendingIntent); } else { Intent i = new Intent(Intent.ACTION_PICK); i.setDataAndType( Uri.fromFile(new File( android.os.Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES) + albumName)), "image/*"); PendingIntent viewImagePendingIntent = PendingIntent.getActivity( getApplicationContext(), (int) System.currentTimeMillis(), i, 0); notificationComplete.setContentTitle(getString(R.string.download_complete)) .setSmallIcon(R.drawable.icon_desaturated).setContentText(String .format(getString(R.string.download_progress), downloaded)) .setContentIntent(viewImagePendingIntent); } notificationManager.cancel(0); notificationManager.cancel(1); notificationManager.notify(1, notificationComplete.build()); } MediaScannerConnection.scanFile(getApplicationContext(), new String[] { android.os.Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES) + albumName + id + "." + type }, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(final String path, final Uri uri) { Log.i("Scanning", String.format("Scanned path %s -> URI = %s", path, uri.toString())); } }); } }); notificationManager.notify(0, notificationBuilder.build()); } catch (JSONException e) { Log.e("Error!", e.toString()); } } }
From source file:org.pocketworkstation.pckeyboard.LatinIME.java
private void setNotification(boolean visible) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); if (visible && mNotificationReceiver == null) { createNotificationChannel();/*w w w.j ava2s .co m*/ int icon = R.drawable.icon; CharSequence text = "Keyboard notification enabled."; long when = System.currentTimeMillis(); // TODO: clean this up? mNotificationReceiver = new NotificationReceiver(this); final IntentFilter pFilter = new IntentFilter(NotificationReceiver.ACTION_SHOW); pFilter.addAction(NotificationReceiver.ACTION_SETTINGS); registerReceiver(mNotificationReceiver, pFilter); Intent notificationIntent = new Intent(NotificationReceiver.ACTION_SHOW); PendingIntent contentIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, notificationIntent, 0); //PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Intent configIntent = new Intent(NotificationReceiver.ACTION_SETTINGS); PendingIntent configPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 2, configIntent, 0); String title = "Show Hacker's Keyboard"; String body = "Select this to open the keyboard. Disable in settings."; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.icon_hk_notification).setColor(0xff220044).setAutoCancel(false) //Make this notification automatically dismissed when the user touches it -> false. .setTicker(text).setContentTitle(title).setContentText(body).setContentIntent(contentIntent) .setOngoing(true).addAction(R.drawable.icon_hk_notification, getString(R.string.notification_action_settings), configPendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT); /* Notification notification = new Notification.Builder(getApplicationContext()) .setAutoCancel(false) //Make this notification automatically dismissed when the user touches it -> false. .setTicker(text) .setContentTitle(title) .setContentText(body) .setWhen(when) .setSmallIcon(icon) .setContentIntent(contentIntent) .getNotification(); notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; mNotificationManager.notify(ID, notification); */ NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); // notificationId is a unique int for each notification that you must define notificationManager.notify(NOTIFICATION_ONGOING_ID, mBuilder.build()); } else if (mNotificationReceiver != null) { mNotificationManager.cancel(NOTIFICATION_ONGOING_ID); unregisterReceiver(mNotificationReceiver); mNotificationReceiver = null; } }
From source file:org.tvbrowser.tvbrowser.TvBrowser.java
private void editDontWantToSee() { if (!SettingConstants.UPDATING_FILTER) { Set<String> currentExclusions = PrefUtils.getStringSetValue(R.string.I_DONT_WANT_TO_SEE_ENTRIES, null); final ArrayList<ExclusionEdit> mCurrentExclusionList = new ArrayList<TvBrowser.ExclusionEdit>(); if (currentExclusions != null && !currentExclusions.isEmpty()) { for (String exclusion : currentExclusions) { mCurrentExclusionList.add(new ExclusionEdit(exclusion)); }/* w w w . j a va 2 s.com*/ } Collections.sort(mCurrentExclusionList); final ArrayAdapter<ExclusionEdit> exclusionAdapter = new ArrayAdapter<TvBrowser.ExclusionEdit>( TvBrowser.this, android.R.layout.simple_list_item_1, mCurrentExclusionList); View view = getLayoutInflater().inflate(R.layout.dont_want_to_see_exclusion_edit_list, getParentViewGroup(), false); ListView list = (ListView) view.findViewById(R.id.dont_want_to_see_exclusion_list); list.setAdapter(exclusionAdapter); final Runnable cancel = new Runnable() { @Override public void run() { } }; AdapterView.OnItemClickListener onClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final ExclusionEdit edit = exclusionAdapter.getItem(position); View editView = getLayoutInflater().inflate(R.layout.dont_want_to_see_edit, getParentViewGroup(), false); final TextView exclusion = (TextView) editView.findViewById(R.id.dont_want_to_see_value); final CheckBox caseSensitive = (CheckBox) editView .findViewById(R.id.dont_want_to_see_case_sensitve); exclusion.setText(edit.mExclusion); caseSensitive.setSelected(edit.mIsCaseSensitive); Runnable editPositive = new Runnable() { @Override public void run() { if (exclusion.getText().toString().trim().length() > 0) { edit.mExclusion = exclusion.getText().toString(); edit.mIsCaseSensitive = caseSensitive.isSelected(); exclusionAdapter.notifyDataSetChanged(); } } }; showAlertDialog(getString(R.string.action_dont_want_to_see), null, editView, null, editPositive, null, cancel, false, false); } }; list.setOnItemClickListener(onClickListener); list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { getMenuInflater().inflate(R.menu.don_want_to_see_context, menu); MenuItem item = menu.findItem(R.id.dont_want_to_see_delete); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { ExclusionEdit edit = exclusionAdapter .getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position); exclusionAdapter.remove(edit); exclusionAdapter.notifyDataSetChanged(); return true; } }); } }); Thread positive = new Thread() { @Override public void run() { SettingConstants.UPDATING_FILTER = true; final NotificationCompat.Builder builder = new NotificationCompat.Builder(TvBrowser.this); builder.setSmallIcon(R.drawable.ic_stat_notify); builder.setOngoing(true); builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see)); builder.setContentText( getResources().getText(R.string.dont_want_to_see_refresh_notification_text)); final int notifyID = 2; final NotificationManager notification = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notification.notify(notifyID, builder.build()); updateProgressIcon(true); HashSet<String> newExclusions = new HashSet<String>(); final ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>(); for (ExclusionEdit edit : mCurrentExclusionList) { String exclusion = edit.getExclusion(); newExclusions.add(exclusion); exclusionList.add(new DontWantToSeeExclusion(exclusion)); } new Thread() { public void run() { Cursor programs = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA, new String[] { TvBrowserContentProvider.KEY_ID, TvBrowserContentProvider.DATA_KEY_TITLE }, null, null, TvBrowserContentProvider.KEY_ID); programs.moveToPosition(-1); builder.setProgress(programs.getCount(), 0, true); notification.notify(notifyID, builder.build()); ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>(); int keyColumn = programs.getColumnIndex(TvBrowserContentProvider.KEY_ID); int titleColumn = programs.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE); DontWantToSeeExclusion[] exclusionArr = exclusionList .toArray(new DontWantToSeeExclusion[exclusionList.size()]); while (programs.moveToNext()) { builder.setProgress(programs.getCount(), programs.getPosition(), false); notification.notify(notifyID, builder.build()); String title = programs.getString(titleColumn); boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr); long progID = programs.getLong(keyColumn); ContentValues values = new ContentValues(); values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0); ContentProviderOperation.Builder opBuilder = ContentProviderOperation.newUpdate( ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE, progID)); opBuilder.withValues(values); updateValuesList.add(opBuilder.build()); } notification.cancel(notifyID); programs.close(); if (!updateValuesList.isEmpty()) { try { getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY, updateValuesList); UiUtils.sendDontWantToSeeChangedBroadcast(getApplicationContext(), true); handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG) .show(); } }); } catch (RemoteException e) { e.printStackTrace(); } catch (OperationApplicationException e) { e.printStackTrace(); } } updateProgressIcon(false); SettingConstants.UPDATING_FILTER = false; } }.start(); Editor edit = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit(); edit.putStringSet(getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES), newExclusions); edit.commit(); } }; showAlertDialog(getString(R.string.action_dont_want_to_see_edit), null, view, null, positive, null, cancel, false, true); } }
From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java
@Override public void onReceive(Context context, Intent pintent) { Log.v(TAG, "ALARM: received alarm"); NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (player != null) { Log.v(TAG, "Releasing media player..."); try {//from w w w. j a v a2s .c o m player.release(); player = null; } catch (Exception e) { e.printStackTrace(); player = null; } finally { // do nothing } } // Cancel notification and return... if (CANCEL_NOTIFICATION.equals(pintent.getAction())) { Log.v(TAG, "Cancelling notification..."); mNM.cancelAll(); return; } // ...or display a new one Log.v(TAG, "Showing notification..."); player = new MediaPlayer(); int setTime = pintent.getIntExtra("SetTime", 0); String setTimeStr = TimerUtils.time2humanStr(context, setTime); Log.v(TAG, "Time: " + setTime); CharSequence text = context.getText(R.string.Notification); CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr); // Load the settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean led = prefs.getBoolean("LED", true); boolean vibrate = prefs.getBoolean("Vibrate", true); String notificationUri = ""; boolean useAdvTime = prefs.getBoolean("useAdvTime", false); String advTimeString = prefs.getString("advTimeString", ""); String[] advTime = null; int advTimeIndex = 1; if (useAdvTime && advTimeString.length() > 0) { advTime = advTimeString.split("\\^"); advTimeIndex = prefs.getInt("advTimeIndex", 1); String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound if (thisAdvTime.length == 3) notificationUri = thisAdvTime[1]; if (notificationUri.equals("sys_def")) notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); } else notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); Log.v(TAG, "notification uri: " + notificationUri); if (notificationUri.equals("system")) notificationUri = prefs.getString("SystemUri", ""); else if (notificationUri.equals("file")) notificationUri = prefs.getString("FileUri", ""); else if (notificationUri.equals("tts")) { notificationUri = ""; final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done)); Intent ttsIntent = new Intent(context, TTSService.class); ttsIntent.putExtra("spoken_text", ttsString); context.startService(ttsIntent); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext()) .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest); Uri uri = null; // Play a sound! if (!notificationUri.equals("")) uri = Uri.parse(notificationUri); // Vibrate if (vibrate && uri == null) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } // Have a light if (led) { mBuilder.setLights(0xff00ff00, 300, 1000); } mBuilder.setAutoCancel(true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, TimerActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(TimerActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); // Create intent for cancelling the notification Context appContext = context.getApplicationContext(); Intent intent = new Intent(appContext, TimerReceiver.class); intent.setAction(CANCEL_NOTIFICATION); // Cancel the pending cancellation and create a new one PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); if (uri != null) { //remove notification sound mBuilder.setSound(null); try { if (player != null && player.isPlaying()) { player.release(); player = new MediaPlayer(); } int currVolume = prefs.getInt("tone_volume", 0); if (currVolume != 0) { float log1 = (float) (Math.log(100 - currVolume) / Math.log(100)); player.setVolume(1 - log1, 1 - log1); } player.setDataSource(context, uri); player.prepare(); player.setLooping(false); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); player.start(); if (vibrate) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(1000); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (prefs.getBoolean("AutoClear", false)) { // Determine duration of notification sound int duration = 5000; if (uri != null) { MediaPlayer cancelPlayer = new MediaPlayer(); try { cancelPlayer.setDataSource(context, uri); cancelPlayer.prepare(); duration = Math.max(duration, cancelPlayer.getDuration() + 2000); } catch (java.io.IOException ex) { Log.e(TAG, "Cannot get sound duration: " + ex); duration = 30000; // on error, default to 30 seconds } finally { cancelPlayer.release(); } cancelPlayer.release(); } Log.v(TAG, "Notification duration: " + duration + " ms"); // Schedule cancellation AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration, pendingCancelIntent); } if (useAdvTime && advTimeString.length() > 0) { Intent broadcast = new Intent(); SharedPreferences.Editor editor = prefs.edit(); if (advTimeIndex < advTime.length) { editor.putInt("advTimeIndex", advTimeIndex + 1); String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound int time = Integer.parseInt(thisAdvTime[0]); broadcast.putExtra("time", time); // Save new time editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); // editor.putString("NotificationUri", thisAdvTime[1]); mNM.cancelAll(); Log.v(TAG, "Starting next iteration of the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); } else { broadcast.putExtra("stop", true); editor.putInt("advTimeIndex", 1); } broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); editor.apply(); } else if (prefs.getBoolean("AutoRestart", false)) { int time = pintent.getIntExtra("SetTime", 0); if (time != 0) { mNM.cancel(0); Log.v(TAG, "Restarting the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); // Save new time SharedPreferences.Editor editor = prefs.edit(); editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); editor.apply(); Intent broadcast = new Intent(); broadcast.putExtra("time", time); broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); } } mNotificationManager.notify(0, mBuilder.build()); Log.d(TAG, "ALARM: alarm finished"); }
From source file:org.tvbrowser.tvbrowser.TvBrowser.java
private void synchronizeDontWantToSee(final boolean replace) { new Thread() { public void run() { if (!SettingConstants.UPDATING_FILTER) { SettingConstants.UPDATING_FILTER = true; Context applicationContext = getApplicationContext(); NotificationCompat.Builder builder; builder = new NotificationCompat.Builder(TvBrowser.this); builder.setSmallIcon(R.drawable.ic_stat_notify); builder.setOngoing(true); builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see)); builder.setContentText(getResources().getText(R.string.dont_want_to_see_notification_text)); int notifyID = 2; NotificationManager notification = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); notification.notify(notifyID, builder.build()); updateProgressIcon(true); URL documentUrl;//from w ww . j ava2 s.c o m try { documentUrl = new URL( "http://android.tvbrowser.org/data/scripts/syncDown.php?type=dontWantToSee"); URLConnection connection = documentUrl.openConnection(); SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE); String car = pref.getString(SettingConstants.USER_NAME, null); String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null); if (car != null && bicycle != null) { String userpass = car + ":" + bicycle; String basicAuth = "basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP); connection.setRequestProperty("Authorization", basicAuth); BufferedReader read = new BufferedReader(new InputStreamReader( new GZIPInputStream(connection.getInputStream()), "UTF-8")); String line = null; StringBuilder exclusionBuilder = new StringBuilder(); HashSet<String> exclusions = new HashSet<String>(); ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>(); while ((line = read.readLine()) != null) { if (line.contains(";;") && line.trim().length() > 0) { exclusions.add(line); exclusionList.add(new DontWantToSeeExclusion(line)); exclusionBuilder.append(line).append("\n"); } } String key = getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES); SharedPreferences pref1 = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this); Set<String> oldValues = pref1.getStringSet(key, null); if (exclusions.size() > 0) { if (!replace && oldValues != null) { for (String old : oldValues) { if (!exclusions.contains(old)) { exclusions.add(old); exclusionList.add(new DontWantToSeeExclusion(old)); exclusionBuilder.append(old).append("\n"); } } } Editor edit = pref1.edit(); edit.putStringSet(key, exclusions); edit.commit(); DontWantToSeeExclusion[] exclusionArr = exclusionList .toArray(new DontWantToSeeExclusion[exclusionList.size()]); Cursor c = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA, new String[] { TvBrowserContentProvider.KEY_ID, TvBrowserContentProvider.DATA_KEY_TITLE }, null, null, TvBrowserContentProvider.KEY_ID); c.moveToPosition(-1); builder.setProgress(c.getCount(), 0, true); notification.notify(notifyID, builder.build()); ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>(); int keyColumn = c.getColumnIndex(TvBrowserContentProvider.KEY_ID); int titleColumn = c.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE); while (c.moveToNext()) { builder.setProgress(c.getCount(), c.getPosition(), false); notification.notify(notifyID, builder.build()); String title = c.getString(titleColumn); boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr); long progID = c.getLong(keyColumn); ContentValues values = new ContentValues(); values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0); ContentProviderOperation.Builder opBuilder = ContentProviderOperation .newUpdate(ContentUris.withAppendedId( TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE, progID)); opBuilder.withValues(values); updateValuesList.add(opBuilder.build()); } c.close(); if (!updateValuesList.isEmpty()) { try { getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY, updateValuesList); UiUtils.sendDontWantToSeeChangedBroadcast(applicationContext, true); handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG) .show(); } }); } catch (RemoteException e) { e.printStackTrace(); } catch (OperationApplicationException e) { e.printStackTrace(); } } if (!replace && exclusionBuilder.length() > 0) { startSynchronizeUp(false, exclusionBuilder.toString(), "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee", null, null); } } else { if (!replace && oldValues != null && !oldValues.isEmpty()) { for (String old : oldValues) { exclusionBuilder.append(old).append("\n"); } startSynchronizeUp(false, exclusionBuilder.toString(), "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee", null, null); } handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync, Toast.LENGTH_LONG).show(); } }); } } } catch (Throwable t) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync, Toast.LENGTH_LONG).show(); } }); } notification.cancel(notifyID); updateProgressIcon(false); SettingConstants.UPDATING_FILTER = false; } } }.start(); }
From source file:org.telegram.messenger.MessagesController.java
private void showInAppNotification(MessageObject messageObject) { if (!UserConfig.clientActivated) { return;/*from w ww.ja v a 2 s . c o m*/ } if (ApplicationLoader.lastPauseTime != 0) { ApplicationLoader.lastPauseTime = System.currentTimeMillis(); FileLog.e("tmessages", "reset sleep timeout by recieved message"); } if (messageObject == null) { return; } SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); boolean globalEnabled = preferences.getBoolean("EnableAll", true); if (!globalEnabled) { return; } if (ApplicationLoader.lastPauseTime == 0) { boolean inAppSounds = preferences.getBoolean("EnableInAppSounds", true); boolean inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); boolean inAppPreview = preferences.getBoolean("EnableInAppPreview", true); if (inAppSounds || inAppVibrate || inAppPreview) { long dialog_id = messageObject.messageOwner.dialog_id; int user_id = messageObject.messageOwner.from_id; int chat_id = 0; if (dialog_id == 0) { if (messageObject.messageOwner.to_id.chat_id != 0) { dialog_id = -messageObject.messageOwner.to_id.chat_id; chat_id = messageObject.messageOwner.to_id.chat_id; } else if (messageObject.messageOwner.to_id.user_id != 0) { if (messageObject.messageOwner.to_id.user_id == UserConfig.clientUserId) { dialog_id = messageObject.messageOwner.from_id; } else { dialog_id = messageObject.messageOwner.to_id.user_id; } } } else { TLRPC.EncryptedChat chat = encryptedChats.get((int) (dialog_id >> 32)); if (chat == null) { return; } } if (dialog_id == 0) { return; } TLRPC.User user = users.get(user_id); if (user == null) { return; } TLRPC.Chat chat; if (chat_id != 0) { chat = chats.get(chat_id); if (chat == null) { return; } } String key = "notify_" + dialog_id; boolean value = preferences.getBoolean(key, true); if (!value) { return; } if (inAppPreview) { NotificationCenter.Instance.postNotificationName(701, messageObject); } if (inAppVibrate) { Vibrator v = (Vibrator) ApplicationLoader.applicationContext .getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(100); } if (inAppSounds) { playNotificationSound(); } } } else { long dialog_id = messageObject.messageOwner.dialog_id; int chat_id = messageObject.messageOwner.to_id.chat_id; int user_id = messageObject.messageOwner.to_id.user_id; if (user_id != 0 && user_id == UserConfig.clientUserId) { user_id = messageObject.messageOwner.from_id; } if (dialog_id == 0) { if (chat_id != 0) { dialog_id = -chat_id; } else if (user_id != 0) { dialog_id = user_id; } } if (dialog_id != 0) { String key = "notify_" + dialog_id; boolean value = preferences.getBoolean(key, true); if (!value) { return; } } boolean groupEnabled = preferences.getBoolean("EnableGroup", true); if (chat_id != 0 && !globalEnabled) { return; } TLRPC.FileLocation photoPath = null; boolean globalVibrate = preferences.getBoolean("EnableVibrateAll", true); boolean groupVibrate = preferences.getBoolean("EnableVibrateGroup", true); boolean groupPreview = preferences.getBoolean("EnablePreviewGroup", true); boolean userPreview = preferences.getBoolean("EnablePreviewAll", true); String defaultPath = null; Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI; if (defaultUri != null) { defaultPath = defaultUri.getPath(); } String globalSound = preferences.getString("GlobalSoundPath", defaultPath); String chatSound = preferences.getString("GroupSoundPath", defaultPath); String userSoundPath = null; String chatSoundPath = null; NotificationManager mNotificationManager = (NotificationManager) ApplicationLoader.applicationContext .getSystemService(Context.NOTIFICATION_SERVICE); Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); String msg = null; if ((int) dialog_id != 0) { if (chat_id != 0) { intent.putExtra("chatId", chat_id); } if (user_id != 0) { intent.putExtra("userId", user_id); } if (chat_id == 0 && user_id != 0) { TLRPC.User u = users.get(user_id); if (u == null) { return; } if (u.photo != null && u.photo.photo_small != null && u.photo.photo_small.volume_id != 0 && u.photo.photo_small.local_id != 0) { photoPath = u.photo.photo_small; } if (userPreview) { if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationContactJoined, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationContactNewPhoto, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { String date = String.format("%s %s %s", Utilities.formatterYear .format(((long) messageObject.messageOwner.date) * 1000), ApplicationLoader.applicationContext.getString(R.string.OtherAt), Utilities.formatterDay .format(((long) messageObject.messageOwner.date) * 1000)); msg = ApplicationLoader.applicationContext.getString( R.string.NotificationUnrecognizedDevice, UserConfig.currentUser.first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address); } } else { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageText, Utilities.formatName(u.first_name, u.last_name), messageObject.messageOwner.message); } else { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageNoText, Utilities.formatName(u.first_name, u.last_name)); } } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessagePhoto, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageVideo, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageContact, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageMap, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageDocument, Utilities.formatName(u.first_name, u.last_name)); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageAudio, Utilities.formatName(u.first_name, u.last_name)); } } } else { msg = ApplicationLoader.applicationContext.getString(R.string.NotificationMessageNoText, Utilities.formatName(u.first_name, u.last_name)); } } else if (chat_id != 0 && user_id == 0) { TLRPC.Chat chat = chats.get(chat_id); if (chat == null) { return; } TLRPC.User u = users.get(messageObject.messageOwner.from_id); if (u == null) { return; } if (u.photo != null && u.photo.photo_small != null && u.photo.photo_small.volume_id != 0 && u.photo.photo_small.local_id != 0) { photoPath = u.photo.photo_small; } if (groupPreview) { if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { if (messageObject.messageOwner.action.user_id == UserConfig.clientUserId) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationInvitedToGroup, Utilities.formatName(u.first_name, u.last_name), chat.title); } else { TLRPC.User u2 = users.get(messageObject.messageOwner.action.user_id); if (u2 == null) { return; } msg = ApplicationLoader.applicationContext.getString( R.string.NotificationGroupAddMember, Utilities.formatName(u.first_name, u.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); } } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationEditedGroupName, Utilities.formatName(u.first_name, u.last_name), messageObject.messageOwner.action.title); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationEditedGroupPhoto, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) { if (messageObject.messageOwner.action.user_id == UserConfig.clientUserId) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationGroupKickYou, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.action.user_id == u.id) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationGroupLeftMember, Utilities.formatName(u.first_name, u.last_name), chat.title); } else { TLRPC.User u2 = users.get(messageObject.messageOwner.action.user_id); if (u2 == null) { return; } msg = ApplicationLoader.applicationContext.getString( R.string.NotificationGroupKickMember, Utilities.formatName(u.first_name, u.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); } } } else { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupText, Utilities.formatName(u.first_name, u.last_name), chat.title, messageObject.messageOwner.message); } else { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupNoText, Utilities.formatName(u.first_name, u.last_name), chat.title); } } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupPhoto, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupVideo, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupContact, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupMap, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupDocument, Utilities.formatName(u.first_name, u.last_name), chat.title); } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupAudio, Utilities.formatName(u.first_name, u.last_name), chat.title); } } } else { msg = ApplicationLoader.applicationContext.getString( R.string.NotificationMessageGroupNoText, Utilities.formatName(u.first_name, u.last_name), chat.title); } } } else { msg = ApplicationLoader.applicationContext.getString(R.string.YouHaveNewMessage); int enc_id = (int) (dialog_id >> 32); intent.putExtra("encId", enc_id); } if (msg == null) { return; } boolean needVibrate = false; if (user_id != 0) { userSoundPath = preferences.getString("sound_path_" + user_id, null); needVibrate = globalVibrate; } if (chat_id != 0) { chatSoundPath = preferences.getString("sound_chat_path_" + chat_id, null); needVibrate = groupVibrate; } String choosenSoundPath = null; if (user_id != 0) { if (userSoundPath != null) { choosenSoundPath = userSoundPath; } else if (globalSound != null) { choosenSoundPath = globalSound; } } else if (chat_id != 0) { if (chatSoundPath != null) { choosenSoundPath = chatSoundPath; } else if (chatSound != null) { choosenSoundPath = chatSound; } } else { choosenSoundPath = globalSound; } intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( ApplicationLoader.applicationContext) .setContentTitle(ApplicationLoader.applicationContext.getString(R.string.AppName)) .setSmallIcon(R.drawable.notification) .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg) .setAutoCancel(true).setTicker(msg); if (photoPath != null) { Bitmap img = FileLoader.Instance.getImageFromMemory(photoPath, null, null, "50_50", false); // String fileNameFinal = u.photo.photo_small.volume_id + "_" + u.photo.photo_small.local_id + ".jpg"; // File cacheFileFinal = new File(Utilities.getCacheDir(), fileNameFinal); // if (cacheFileFinal.exists()) { // photoPath // } if (img != null) { mBuilder.setLargeIcon(img); } } if (needVibrate) { mBuilder.setVibrate(new long[] { 0, 100, 0, 100 }); } if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (choosenSoundPath.equals(defaultPath)) { mBuilder.setSound(defaultUri); } else { mBuilder.setSound(Uri.parse(choosenSoundPath)); } } mBuilder.setContentIntent(contentIntent); mNotificationManager.cancel(1); Notification notification = mBuilder.build(); notification.ledARGB = 0xff00ff00; notification.ledOnMS = 1000; notification.ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS; try { mNotificationManager.notify(1, notification); } catch (Exception e) { FileLog.e("tmessages", e); } } }