List of usage examples for android.app PendingIntent getBroadcast
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags)
From source file:com.bhb27.isu.tools.Tools.java
public static void DoNotification(Context context) { NotificationCompat.Builder notification = new NotificationCompat.Builder(context); notification.setSmallIcon(R.drawable.ic_notification); notification.setContentTitle(context.getString(R.string.notification_title)); notification.setOngoing(true);//from w w w .j a va 2s . co m NotificationManager notificationManager = (NotificationManager) context .getSystemService(context.NOTIFICATION_SERVICE); Intent yesReceiver = new Intent(); yesReceiver.setAction(Constants.YES_ACTION); PendingIntent pendingIntentYes = PendingIntent.getBroadcast(context, 12345, yesReceiver, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Action actiony = new NotificationCompat.Action.Builder(R.drawable.ic_notification, context.getString(R.string.yes), pendingIntentYes).build(); notification.addAction(actiony); Intent dismissReceiver = new Intent(); dismissReceiver.setAction(Constants.DISSMISS_ACTION); PendingIntent pendingIntentYes2 = PendingIntent.getBroadcast(context, 12345, dismissReceiver, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Action actionn = new NotificationCompat.Action.Builder(R.drawable.ic_notification, context.getString(R.string.dismiss), pendingIntentYes2).build(); notification.addAction(actionn); notificationManager.notify(10, notification.build()); }
From source file:com.jmstudios.redmoon.receiver.AutomaticFilterChangeReceiver.java
public static void cancelTurnOnAlarm(Context context) { Intent commands = new Intent(context, AutomaticFilterChangeReceiver.class); commands.setData(Uri.parse("turnOnIntent")); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, commands, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pendingIntent);//from w ww . j a v a 2 s . com }
From source file:com.commonsware.android.webserver.WebServerService.java
private void foregroundify() { NotificationCompat.Builder b = new NotificationCompat.Builder(this); Intent iReceiver = new Intent(this, StopReceiver.class); PendingIntent piReceiver = PendingIntent.getBroadcast(this, 0, iReceiver, 0); b.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL); buildForegroundNotification(b);/*from w w w . j a va 2 s . c o m*/ b.addAction(R.drawable.ic_stop_white_24dp, getString(R.string.notify_stop), piReceiver); startForeground(NOTIFY_ID, b.build()); }
From source file:com.example.gemswin.screencastrecevertest.MainActivity_Reciever.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_reciever); WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress()); TextView text = (TextView) findViewById(R.id.textView); planetList = new ArrayList<String>(); mTextureView = (TextureView)findViewById(R.id.textureView); mTextureView.setSurfaceTextureListener(this); mTextureView.requestLayout();//from ww w. ja v a2 s .com mTextureView.invalidate(); mTextureView.setOpaque(false); logout = (Button) findViewById(R.id.logout); cast = (Button) findViewById(R.id.castAsmaster); doubtbutton = (Button) findViewById(R.id.doubt); viewbutton = (Button) findViewById(R.id.viewdoubt); pref = new PrefManager(getApplicationContext()); text.setText(ip); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pref.logout(); Intent i = new Intent(MainActivity_Reciever.this, LoginActivity.class); startActivity(i); finish(); } }); cast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new allowcast().execute(); } }); viewbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //pref.logout(); // LOOK HERE ASH /*Intent i = new Intent(MainActivity_Reciever.this,DoubtActivity.class); startActivity(i);*/ new viewdoubttask().execute(); } }); doubtbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //pref.logout(); // LOOK HERE ASH /*Intent i = new Intent(MainActivity_Reciever.this,DoubtActivity.class); startActivity(i);*/ DoubtBox(); } }); mTask = new ReceiverAsyncTask(this); mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); Intent intent1 = new Intent(this, MyBroadcastReceiver.class); intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getBroadcast( getApplicationContext(), 234324243, intent1, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent); }
From source file:com.jio.appstore.download.DownloadNotifier.java
private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info);/*from w ww . j av a 2s . c o m*/ } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { // build a synthetic uri for intent identification purposes final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build(); final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent( PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); builder.setAutoCancel(true); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { action = Constants.ACTION_OPEN; } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent( PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; Long spd = mDownloadSpeed.get(info.mId); if (spd != null) { speed += spd; } // speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatElapsedTime(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText(res.getString(R.string.notification_download_waiting)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle( res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle( res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText(res.getString(R.string.notification_download_waiting)); inboxStyle.setSummaryText(res.getString(R.string.notification_download_waiting)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } }
From source file:com.dslr.dashboard.PtpService.java
@Override public void onCreate() { Log.d(TAG, "onCreate"); super.onCreate(); mGpsHelper = new GpsLocationHelper(this); IntentFilter usbDetachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbDeviceDetached, usbDetachedFilter); mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); registerReceiver(mUsbPermissionReceiver, filter); // get the shared preferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); // create the ptpdevice mPtpDevice = new PtpDevice(this); try {//ww w . j a v a 2s. com mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); } catch (Exception e) { Log.d(TAG, "UsbManager not available: " + e.getMessage()); } }
From source file:com.klinker.android.twitter.utils.NotificationUtils.java
public static void refreshNotification(Context context, boolean noTimeline) { AppSettings settings = AppSettings.getInstance(context); SharedPreferences sharedPrefs = context.getSharedPreferences( "com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); int currentAccount = sharedPrefs.getInt("current_account", 1); //int[] unreadCounts = new int[] {4, 1, 2}; // for testing int[] unreadCounts = getUnreads(context); int timeline = unreadCounts[0]; int realTimelineCount = timeline; // if they don't want that type of notification, simply set it to zero if (!settings.timelineNot || (settings.pushNotifications && settings.liveStreaming) || noTimeline) { unreadCounts[0] = 0;//from ww w. java 2 s. c o m } if (!settings.mentionsNot) { unreadCounts[1] = 0; } if (!settings.dmsNot) { unreadCounts[2] = 0; } if (unreadCounts[0] == 0 && unreadCounts[1] == 0 && unreadCounts[2] == 0) { } else { Intent markRead = new Intent(context, MarkReadService.class); PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0); String shortText = getShortText(unreadCounts, context, currentAccount); String longText = getLongText(unreadCounts, context, currentAccount); // [0] is the full title and [1] is the screenname String[] title = getTitle(unreadCounts, context, currentAccount); boolean useExpanded = useExp(context); boolean addButton = addBtn(unreadCounts); if (title == null) { return; } Intent resultIntent; if (unreadCounts[1] != 0 && unreadCounts[0] == 0) { // it is a mention notification (could also have a direct message) resultIntent = new Intent(context, RedirectToMentions.class); } else if (unreadCounts[2] != 0 && unreadCounts[0] == 0 && unreadCounts[1] == 0) { // it is a direct message resultIntent = new Intent(context, RedirectToDMs.class); } else { resultIntent = new Intent(context, MainActivity.class); } PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0); NotificationCompat.Builder mBuilder; Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class); mBuilder = new NotificationCompat.Builder(context).setContentTitle(title[0]) .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)) .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(getIcon(context, unreadCounts, title[1])) .setContentIntent(resultPendingIntent).setAutoCancel(true) .setTicker(TweetLinkUtils.removeColorHtml(shortText, settings)) .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)) .setPriority(NotificationCompat.PRIORITY_HIGH); if (unreadCounts[1] > 1 && unreadCounts[0] == 0 && unreadCounts[2] == 0) { // inbox style notification for mentions mBuilder.setStyle(getMentionsInboxStyle(unreadCounts[1], currentAccount, context, TweetLinkUtils.removeColorHtml(shortText, settings))); } else if (unreadCounts[2] > 1 && unreadCounts[0] == 0 && unreadCounts[1] == 0) { // inbox style notification for direct messages mBuilder.setStyle(getDMInboxStyle(unreadCounts[1], currentAccount, context, TweetLinkUtils.removeColorHtml(shortText, settings))); } else { // big text style for an unread count on timeline, mentions, and direct messages mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml( settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText))); } // Pebble notification if (sharedPrefs.getBoolean("pebble_notification", false)) { sendAlertToPebble(context, title[0], shortText); } // Light Flow notification sendToLightFlow(context, title[0], shortText); int homeTweets = unreadCounts[0]; int mentionsTweets = unreadCounts[1]; int dmTweets = unreadCounts[2]; int newC = 0; if (homeTweets > 0) { newC++; } if (mentionsTweets > 0) { newC++; } if (dmTweets > 0) { newC++; } if (settings.notifications && newC > 0) { if (settings.vibrate) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } if (settings.sound) { try { mBuilder.setSound(Uri.parse(settings.ringtone)); } catch (Exception e) { mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); } } if (settings.led) mBuilder.setLights(0xFFFFFF, 1000, 1000); // Get an instance of the NotificationManager service NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); if (addButton) { // the reply and read button should be shown Intent reply; if (unreadCounts[1] == 1) { reply = new Intent(context, NotificationCompose.class); } else { reply = new Intent(context, NotificationDMCompose.class); } Log.v("username_for_noti", title[1]); sharedPrefs.edit().putString("from_notification", "@" + title[1] + " " + title[2]).commit(); MentionsDataSource data = MentionsDataSource.getInstance(context); long id = data.getLastIds(currentAccount)[0]; PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0); sharedPrefs.edit().putLong("from_notification_long", id).commit(); sharedPrefs.edit() .putString("from_notification_text", "@" + title[1] + ": " + TweetLinkUtils.removeColorHtml(shortText, settings)) .commit(); // Create the remote input RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY) .setLabel("@" + title[1] + " ").build(); // Create the notification action NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder( R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply), replyPending).addRemoteInput(remoteInput).build(); NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder( R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read), readPending); mBuilder.addAction(replyAction); mBuilder.addAction(action.build()); } else { // otherwise, if they can use the expanded notifications, the popup button will be shown Intent popup = new Intent(context, RedirectToPopup.class); popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); popup.putExtra("from_notification", true); PendingIntent popupPending = PendingIntent.getActivity(context, 0, popup, 0); NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder( R.drawable.ic_popup, context.getResources().getString(R.string.popup), popupPending); mBuilder.addAction(action.build()); } // Build the notification and issues it with notification manager. notificationManager.notify(1, mBuilder.build()); // if we want to wake the screen on a new message if (settings.wakeScreen) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG"); wakeLock.acquire(5000); } } // if there are unread tweets on the timeline, check them for favorite users if (settings.favoriteUserNotifications && realTimelineCount > 0) { favUsersNotification(currentAccount, context); } } try { ContentValues cv = new ContentValues(); cv.put("tag", "com.klinker.android.twitter/com.klinker.android.twitter.ui.MainActivity"); // add the direct messages and mentions cv.put("count", unreadCounts[1] + unreadCounts[2]); context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv); } catch (IllegalArgumentException ex) { /* Fine, TeslaUnread is not installed. */ } catch (Exception ex) { /* Some other error, possibly because the format of the ContentValues are incorrect. Log but do not crash over this. */ ex.printStackTrace(); } }
From source file:com.android.mms.transaction.ReadRecTransaction.java
public void run() { MmsLog.d(MmsApp.TXN_TAG, "ReadRecTransaction: process()"); // prepare for ReadRec int readReportState = 0; String messageId = null;//from w w w. j a va2 s . co m long msgId = 0; EncodedStringValue[] sender = new EncodedStringValue[1]; Cursor cursor = null; cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(), mUri, new String[] { Mms.MESSAGE_ID, Mms.READ_REPORT, Mms._ID }, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { messageId = cursor.getString(0); readReportState = cursor.getInt(1); msgId = cursor.getLong(2); } // if curosr==null, this means the mms is deleted during // processing. // exception will happened. catched by out catch clause. // so do not catch exception here. } finally { cursor.close(); } } MmsLog.d(MmsApp.TXN_TAG, "messageid:" + messageId + ",and readreport flag:" + readReportState + ", mSubId = " + mSubId); cursor = null; cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(), Uri.parse("content://mms/" + msgId + "/addr"), new String[] { Mms.Addr.ADDRESS, Mms.Addr.CHARSET }, Mms.Addr.TYPE + " = " + PduHeaders.FROM, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { String address = cursor.getString(0); int charSet = cursor.getInt(1); MmsLog.d(MmsApp.TXN_TAG, "find address:" + address + ",charset:" + charSet); sender[0] = new EncodedStringValue(charSet, PduPersister.getBytes(address)); } // if cursor == null exception will catched by out catch clause. } finally { cursor.close(); } } try { ReadRecInd readRecInd = new ReadRecInd( new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()), messageId.getBytes(), PduHeaders.CURRENT_MMS_VERSION, PduHeaders.READ_STATUS_READ, // always // set // read. sender); readRecInd.setDate(System.currentTimeMillis() / 1000); Uri uri = PduPersister.getPduPersister(mContext).persist(readRecInd, Mms.Outbox.CONTENT_URI, true, MmsPreferenceActivity.getIsGroupMmsEnabled(mContext), null); byte[] datas = new PduComposer(mContext, readRecInd).make(); mPduFile = createPduFile(datas, READREP_REQ_NAME + uri.getLastPathSegment()); if (mPduFile == null) { Log.e(MmsApp.TXN_TAG, "create pdu file req failed!"); return; } //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED); //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId); //intent.putExtra(TransactionBundle.URI, mUri.toString()); Log.d(MmsApp.TXN_TAG, "ReadRecTransaction mUri:" + mUri); final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext, MmsReceiver.class); intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId); PendingIntent sentIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile); SmsManager.getSmsManagerForSubscriptionId(mSubId).sendMultimediaMessage(mContext, pduFileUri, null, null, sentIntent); } catch (InvalidHeaderValueException e) { Log.e(TAG, "Invalide header value", e); getState().setState(FAILED); getState().setContentUri(mUri); notifyObservers(); } catch (MmsException e) { Log.e(TAG, "Persist message failed", e); getState().setState(FAILED); getState().setContentUri(mUri); notifyObservers(); } catch (Throwable t) { Log.e(TAG, Log.getStackTraceString(t)); getState().setState(FAILED); getState().setContentUri(mUri); notifyObservers(); } }
From source file:com.evandroid.musica.broadcastReceiver.MusicBroadcastReceiver.java
@Override public void onReceive(Context context, Intent intent) { /** Google Play Music //bool streaming long position //long albumId String album //bool currentSongLoaded String track //long ListPosition long ListSize //long id bool playing //long duration int previewPlayType //bool supportsRating int domain //bool albumArtFromService String artist //int rating bool local //bool preparing bool inErrorState */// w ww .j av a 2 s . com Bundle extras = intent.getExtras(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context); boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true); if (extras != null) try { extras.getInt("state"); } catch (BadParcelableException e) { return; } if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000) || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000) || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200)) || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000) || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000) || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200))) return; String artist = extras.getString("artist"); String track = extras.getString("track"); long position = extras.containsKey("position") ? extras.getLong("position") : -1; if (extras.get("position") instanceof Double) position = Double.valueOf(extras.getDouble("position")).longValue(); boolean isPlaying = extras.getBoolean("playing", true); if (intent.getAction().equals("com.amazon.mp3.metachanged")) { artist = extras.getString("com.amazon.mp3.artist"); track = extras.getString("com.amazon.mp3.track"); } else if (intent.getAction().equals("com.spotify.music.metadatachanged")) isPlaying = spotifyPlaying; else if (intent.getAction().equals("com.spotify.music.playbackstatechanged")) spotifyPlaying = isPlaying; if ((artist == null || "".equals(artist)) //Could be problematic || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts return; SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE); String currentArtist = current.getString("artist", ""); String currentTrack = current.getString("track", ""); SharedPreferences.Editor editor = current.edit(); editor.putString("artist", artist); editor.putString("track", track); editor.putLong("position", position); editor.putBoolean("playing", isPlaying); if (isPlaying) { long currentTime = System.currentTimeMillis(); editor.putLong("startTime", currentTime); } editor.apply(); autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false); int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0")); if (autoUpdate && App.isActivityVisible()) { Intent internalIntent = new Intent("Broadcast"); internalIntent.putExtra("artist", artist).putExtra("track", track); LyricsViewFragment.sendIntent(context, internalIntent); forceAutoUpdate(false); } SQLiteDatabase db = new DatabaseHelper(context).getReadableDatabase(); boolean inDatabase = DatabaseHelper.presenceCheck(db, new String[] { artist, track, artist, track }); db.close(); if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) { Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS", new String[] { artist, track }); Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist) .putExtra("track", track); PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT); PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch, context.getString(R.string.wearable_prompt), wearablePending).build(); NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context); NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context); if ("0".equals(sharedPref.getString("pref_theme", "0"))) notifBuilder.setColor(context.getResources().getColor(R.color.primary)); notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name)) .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending) .setVisibility(-1) // Notification.VISIBILITY_SECRET .setGroup("Lyrics_Notification").setGroupSummary(true); wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif) .setContentTitle(context.getString(R.string.app_name)) .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending) .setVisibility(-1) // Notification.VISIBILITY_SECRET .setGroup("Lyrics_Notification").setOngoing(false).setGroupSummary(false) .extend(new NotificationCompat.WearableExtender().addAction(wearableAction)); if (notificationPref == 2) { notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN } else notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW Notification notif = notifBuilder.build(); Notification wearableNotif = wearableNotifBuilder.build(); if (notificationPref == 2) notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; else notif.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManagerCompat.from(context).notify(0, notif); try { context.getPackageManager().getPackageInfo("com.google.android.wearable.app", PackageManager.GET_META_DATA); NotificationManagerCompat.from(context).notify(8, wearableNotif); } catch (PackageManager.NameNotFoundException ignored) { } } else if (track.equals(current.getString("track", ""))) NotificationManagerCompat.from(context).cancel(0); }
From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java
/** * Determines if the muting service is running (ON) or stopped (OFF). * The muting service is defined as running if there is an alarm scheduled that will either mute or unmute * the phone at a specific time. It is stopped if no alarm is scheduled. * http://code.google.com/p/android/issues/detail?id=3776 * http://stackoverflow.com/questions/2110620/how-to-handle-an-alarm-triggered-each-day-in-android * @return true if the muting service is running or false if it is stopped */// w w w . ja v a2 s . co m private boolean isRunning() { Intent alarmIntent = new Intent(this, OnAlarmReceiver.class).putExtra(ACTION, ACTION_NONE); boolean isRunning = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_NO_CREATE) != null; Log.d(TAG, "isRunning(): " + isRunning); return isRunning; }