List of usage examples for android.content Intent removeExtra
public void removeExtra(String name)
From source file:com.chen.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. *///from w w w. j av a 2 s .c om private static void validateNotifications(Context context, final Folder folder, final Account account, boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final NotificationMap notificationMap = getNotificationMap(context); if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) { LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b", createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention); } else { LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b", notificationMap.size(), getAttention); } // The number of unread messages for this account and label. final Integer unread = notificationMap.getUnread(key); final int unreadCount = unread != null ? unread.intValue() : 0; final Integer unseen = notificationMap.getUnseen(key); int unseenCount = unseen != null ? unseen.intValue() : 0; Cursor cursor = null; try { final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon(); uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString()); // Do not allow this quick check to disrupt any active network-enabled conversation // cursor. uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK, Boolean.FALSE.toString()); cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION, null, null, null); if (cursor == null) { // This folder doesn't exist. LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist"); clearFolderNotification(context, account, folder, false); return; } final int cursorUnseenCount = cursor.getCount(); // Make sure the unseen count matches the number of items in the cursor. But, we don't // want to overwrite a 0 unseen count that was specified in the intent if (unseenCount != 0 && unseenCount != cursorUnseenCount) { LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count. unseen: %d cursor count: %d", unseenCount, cursorUnseenCount); unseenCount = cursorUnseenCount; } // For the purpose of the notifications, the unseen count should be capped at the num of // unread conversations. if (unseenCount > unreadCount) { unseenCount = unreadCount; } final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder); if (unseenCount == 0) { LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s", LogUtils.sanitizeName(LOG_TAG, account.name), LogUtils.sanitizeName(LOG_TAG, folder.persistentId)); nm.cancel(notificationId); return; } // We now have all we need to create the notification and the pending intent PendingIntent clickIntent; NotificationCompat.Builder notification = new NotificationCompat.Builder(context); notification.setSmallIcon(R.drawable.stat_notify_email); notification.setTicker(account.name); final long when; final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId); if (oldWhen != 0) { when = oldWhen; } else { when = System.currentTimeMillis(); } notification.setWhen(when); // The timestamp is now stored in the notification, so we can remove it from here NotificationActionUtils.sNotificationTimestamps.delete(notificationId); // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a // notification. Also this intent gets fired when the user taps on a notification as // the AutoCancel flag has been set final Intent cancelNotificationIntent = new Intent( MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS); cancelNotificationIntent.setPackage(context.getPackageName()); cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri)); cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account); cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder); notification.setDeleteIntent( PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0)); // Ensure that the notification is cleared when the user selects it notification.setAutoCancel(true); boolean eventInfoConfigured = false; final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox); final FolderPreferences folderPreferences = new FolderPreferences(context, account.getEmailAddress(), folder, isInbox); if (isInbox) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.getEmailAddress()); moveNotificationSetting(accountPreferences, folderPreferences); } if (!folderPreferences.areNotificationsEnabled()) { LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying"); // Don't notify return; } if (unreadCount > 0) { // How can I order this properly? if (cursor.moveToNext()) { final Intent notificationIntent; // Launch directly to the conversation, if there is only 1 unseen conversation final boolean launchConversationMode = (unseenCount == 1); if (launchConversationMode) { notificationIntent = createViewConversationIntent(context, account, folder, cursor); } else { notificationIntent = createViewConversationIntent(context, account, folder, null); } Analytics.getInstance().sendEvent("notification_create", launchConversationMode ? "conversation" : "conversation_list", folder.getTypeDescription(), unseenCount); if (notificationIntent == null) { LogUtils.e(LOG_TAG, "Null intent when building notification"); return; } // Amend the click intent with a hint that its source was a notification, // but remove the hint before it's used to generate notification action // intents. This prevents the following sequence: // 1. generate single notification // 2. user clicks reply, then completes Compose activity // 3. main activity launches, gets FROM_NOTIFICATION hint in intent notificationIntent.putExtra(Utils.EXTRA_FROM_NOTIFICATION, true); clickIntent = PendingIntent.getActivity(context, -1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notificationIntent.removeExtra(Utils.EXTRA_FROM_NOTIFICATION); configureLatestEventInfoFromConversation(context, account, folderPreferences, notification, cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when); eventInfoConfigured = true; } } final boolean vibrate = folderPreferences.isNotificationVibrateEnabled(); final String ringtoneUri = folderPreferences.getNotificationRingtoneUri(); final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled(); if (!ignoreUnobtrusiveSetting && notifyOnce) { // If the user has "unobtrusive notifications" enabled, only alert the first time // new mail is received in this account. This is the default behavior. See // bugs 2412348 and 2413490. notification.setOnlyAlertOnce(true); } LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.name), Boolean.toString(folderPreferences.isNotificationVibrateEnabled())); int defaults = 0; /* * We do not want to notify if this is coming back from an Undo notification, hence the * oldWhen check. */ if (getAttention && oldWhen == 0) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.name); if (accountPreferences.areNotificationsEnabled()) { if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri)); LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s", LogUtils.sanitizeName(LOG_TAG, account.name), vibrate, ringtoneUri); } } // TODO(skennedy) Why do we do any of the above if we're just going to bail here? if (eventInfoConfigured) { defaults |= Notification.DEFAULT_LIGHTS; notification.setDefaults(defaults); if (oldWhen != 0) { // We do not want to display the ticker again if we are re-displaying this // notification (like from an Undo notification) notification.setTicker(null); } nm.notify(notificationId, notification.build()); } else { LogUtils.i(LOG_TAG, "event info not configured - not notifying"); } } finally { if (cursor != null) { cursor.close(); } } }
From source file:im.neon.activity.VectorHomeActivity.java
/** * Process the content of the current intent to detect universal link data. * If data present, it means that the app was started through an URL link, but due * to the App was not initialized properly, it has been required to re start the App. * * To indicate the App has finished its Login/Splash/Home flow, a resume action * is sent to the receiver.// w w w . ja v a2 s . c o m */ private void processIntentUniversalLink() { Intent intent; Uri uri; if (null != (intent = getIntent())) { if (intent.hasExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI)) { Log.d(LOG_TAG, "## processIntentUniversalLink(): EXTRA_UNIVERSAL_LINK_URI present1"); uri = intent.getParcelableExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI); if (null != uri) { Intent myBroadcastIntent = new Intent( VectorUniversalLinkReceiver.BROADCAST_ACTION_UNIVERSAL_LINK_RESUME); myBroadcastIntent.putExtras(getIntent().getExtras()); myBroadcastIntent.putExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_SENDER_ID, VectorUniversalLinkReceiver.HOME_SENDER_ID); sendBroadcast(myBroadcastIntent); showWaitingView(); // use only once, remove since it has been used intent.removeExtra(VectorUniversalLinkReceiver.EXTRA_UNIVERSAL_LINK_URI); Log.d(LOG_TAG, "## processIntentUniversalLink(): Broadcast BROADCAST_ACTION_UNIVERSAL_LINK_RESUME sent"); } } } }
From source file:saphion.fragments.alarm.AlarmFragment.java
@Override public void onResume() { super.onResume(); // Check if another app asked us to create a blank new alarm. final Intent intent = getActivity().getIntent(); if (intent.hasExtra(ALARM_CREATE_NEW_INTENT_EXTRA)) { if (intent.getBooleanExtra(ALARM_CREATE_NEW_INTENT_EXTRA, false)) { // An external app asked us to create a blank alarm. startCreatingAlarm();/*from ww w .ja va2s .c om*/ } // Remove the CREATE_NEW extra now that we've processed it. intent.removeExtra(ALARM_CREATE_NEW_INTENT_EXTRA); } else if (intent.hasExtra(SCROLL_TO_ALARM_INTENT_EXTRA)) { long alarmId = intent.getLongExtra(SCROLL_TO_ALARM_INTENT_EXTRA, Alarm.INVALID_ID); if (alarmId != Alarm.INVALID_ID) { mScrollToAlarmId = alarmId; if (mCursorLoader != null && mCursorLoader.isStarted()) { // We need to force a reload here to make sure we have the // latest view // of the data to scroll to. mCursorLoader.forceLoad(); } } // Remove the SCROLL_TO_ALARM extra now that we've processed it. intent.removeExtra(SCROLL_TO_ALARM_INTENT_EXTRA); } // Make sure to use the child FragmentManager. We have to use that one // for the // case where an intent comes in telling the activity to load the // timepicker, // which means we have to use that one everywhere so that the fragment // can get // correctly picked up here if it's open. /* * TimePickerDialog tpd = (TimePickerDialog) getFragmentManager() * .findFragmentByTag(AlarmUtils.FRAG_TAG_TIME_PICKER); if (tpd != null) * { // The dialog is already open so we need to set the listener again. * tpd.setOnTimeSetListener(this); } */ }
From source file:org.runbuddy.tomahawk.activities.TomahawkMainActivity.java
private void handleIntent(Intent intent) { if (MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.equals(intent.getAction())) { intent.setAction(null);//from w w w . j a v a 2 s . c o m String playbackManagerId = getSupportMediaController().getExtras() .getString(PlaybackService.EXTRAS_KEY_PLAYBACKMANAGER); PlaybackManager playbackManager = PlaybackManager.getByKey(playbackManagerId); MediaPlayIntentHandler intentHandler = new MediaPlayIntentHandler( getSupportMediaController().getTransportControls(), playbackManager); intentHandler.mediaPlayFromSearch(intent.getExtras()); } if ("com.google.android.gms.actions.SEARCH_ACTION".equals(intent.getAction())) { intent.setAction(null); String query = intent.getStringExtra(SearchManager.QUERY); if (query != null && !query.isEmpty()) { DatabaseHelper.get().addEntryToSearchHistory(query); Bundle bundle = new Bundle(); bundle.putString(TomahawkFragment.QUERY_STRING, query); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC); FragmentUtils.replace(TomahawkMainActivity.this, SearchPagerFragment.class, bundle); } } if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) { intent.setAction(null); // if this Activity is being shown after the user clicked the notification if (mSlidingUpPanelLayout != null) { mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED); } } if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) { intent.removeExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); Bundle bundle = new Bundle(); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL); FragmentUtils.replace(this, PreferencePagerFragment.class, bundle); } if (intent.getData() != null) { final Uri data = intent.getData(); intent.setData(null); List<String> pathSegments = data.getPathSegments(); String host = data.getHost(); String scheme = data.getScheme(); if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk") || host.contains("beatsmusic.com") || host.contains("deezer.com") || host.contains("rdio.com") || host.contains("soundcloud.com")))) { PipeLine.get().lookupUrl(data.toString()); } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf")) || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) { TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) { @Override public void run() { Playlist pl = XspfParser.parse(data); if (pl != null) { final Bundle bundle = new Bundle(); bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey()); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle); } }); } } }; ThreadManager.get().execute(r); } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe") || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) { InstallPluginConfigDialog dialog = new InstallPluginConfigDialog(); Bundle args = new Bundle(); args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString()); dialog.setArguments(args); dialog.show(getSupportFragmentManager(), null); } else { String albumName; String trackName; String artistName; try { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, data); albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); retriever.release(); } catch (Exception e) { Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage()); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { String msg = TomahawkApp.getContext().getString(R.string.invalid_file); Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show(); } }); return; } if (TextUtils.isEmpty(trackName) && pathSegments != null) { trackName = pathSegments.get(pathSegments.size() - 1); } Query query = Query.get(trackName, albumName, artistName, false); Result result = Result.get(data.toString(), query.getBasicTrack(), UserCollectionStubResolver.get()); float trackScore = query.howSimilar(result); query.addTrackResult(result, trackScore); Bundle bundle = new Bundle(); List<Query> queries = new ArrayList<>(); queries.add(query); Playlist playlist = Playlist.fromQueryList(IdGenerator.getSessionUniqueStringId(), "", "", queries); playlist.setFilled(true); playlist.setName(artistName + " - " + trackName); bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey()); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC); FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle); } } }
From source file:org.thoughtcrime.securesms.conversation.ConversationActivity.java
@Override public void startActivity(Intent intent) { if (intent.getStringExtra(Browser.EXTRA_APPLICATION_ID) != null) { intent.removeExtra(Browser.EXTRA_APPLICATION_ID); }/*from w w w . jav a2 s . c o m*/ try { super.startActivity(intent); } catch (ActivityNotFoundException e) { Log.w(TAG, e); Toast.makeText(this, R.string.ConversationActivity_there_is_no_app_available_to_handle_this_link_on_your_device, Toast.LENGTH_LONG).show(); } }
From source file:com.nsqre.insquare.Utilities.PushNotification.MyGcmListenerService.java
/** * Create and show a simple notification containing the received GCM message. * Manages how the notification will be shown in the notification bar. * @param message GCM message received./* ww w .j a va2s . co m*/ */ private void sendNotification(String message, String squareName, String squareId) { Intent intent = new Intent(this, BottomNavActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); SharedPreferences notificationPreferences = getSharedPreferences("NOTIFICATION_MAP", MODE_PRIVATE); int notificationCount = 0; int squareCount = notificationPreferences.getInt("squareCount", 0); if (squareId.equals(notificationPreferences.getString("actualSquare", ""))) { return; } if (!notificationPreferences.contains(squareId)) { notificationPreferences.edit().putInt("squareCount", squareCount + 1).apply(); } notificationPreferences.edit().putInt(squareId, notificationPreferences.getInt(squareId, 0) + 1).apply(); for (String square : notificationPreferences.getAll().keySet()) { if (!"squareCount".equals(square) && !"actualSquare".equals(square)) { notificationCount += notificationPreferences.getInt(square, 0); } } squareCount = notificationPreferences.getInt("squareCount", 0); Log.d(TAG, notificationPreferences.getAll().toString()); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setSmallIcon(R.drawable.nsqre_map_pin_empty_inside); notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)); if (squareCount == 1) { SharedPreferences messagePreferences = getSharedPreferences(squareId, MODE_PRIVATE); intent.putExtra("squareId", squareId); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); messagePreferences.edit().putString(String.valueOf(notificationCount), message).commit(); if (messagePreferences.getAll().size() <= 6) { for (int i = 1; i <= messagePreferences.getAll().keySet().size(); i++) { inboxStyle.addLine(messagePreferences.getString(String.valueOf(i), "")); } } else { for (int i = messagePreferences.getAll().size() - 6; i <= messagePreferences.getAll().keySet() .size(); i++) { inboxStyle.addLine(messagePreferences.getString(String.valueOf(i), "")); } } notificationBuilder.setContentTitle(squareName); notificationBuilder.setStyle(inboxStyle.setBigContentTitle(squareName).setSummaryText("inSquare")); notificationBuilder.setContentText( notificationCount > 1 ? "Hai " + notificationCount + " nuovi messaggi" : message); } else { intent.putExtra("map", 0); intent.removeExtra("squareId"); notificationBuilder.setContentTitle("inSquare"); notificationBuilder .setContentText("Hai " + (notificationCount) + " nuovi messaggi in " + squareCount + " piazze"); } notificationBuilder.setAutoCancel(true); notificationBuilder.setSound(defaultSoundUri); notificationBuilder.setVibrate(new long[] { 300, 300, 300, 300, 300 }); notificationBuilder.setLights(Color.RED, 1000, 3000); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_CANCEL_CURRENT); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); updateSquares("", "", "update"); SharedPreferences mutePreferences = getSharedPreferences("NOTIFICATION_MUTE_MAP", MODE_PRIVATE); if (mutePreferences.contains(squareId)) { String expireDate = mutePreferences.getString(squareId, ""); long myExpireDate = Long.parseLong(expireDate, 10); if (myExpireDate < (new Date().getTime())) { mutePreferences.edit().remove(squareId).apply(); notificationManager.notify(0, notificationBuilder.build()); } } else { notificationManager.notify(0, notificationBuilder.build()); } }
From source file:nl.mpcjanssen.simpletask.Simpletask.java
private void handleIntent() { if (!m_app.isAuthenticated()) { Log.v(TAG, "handleIntent: not authenticated"); startLogin();//from ww w. jav a 2 s . com return; } if (!m_app.initialSyncDone()) { m_sync_dialog = new ProgressDialog(this, m_app.getActiveTheme()); m_sync_dialog.setIndeterminate(true); m_sync_dialog.setMessage("Initial Dropbox sync in progress, please wait...."); m_sync_dialog.setCancelable(false); m_sync_dialog.show(); } else if (m_sync_dialog != null) { m_sync_dialog.cancel(); } mFilter = new ActiveFilter(); m_leftDrawerList = (ListView) findViewById(R.id.left_drawer); m_rightDrawerList = (ListView) findViewById(R.id.right_drawer_list); m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // Set the list's click listener m_leftDrawerList.setOnItemClickListener(new DrawerItemClickListener()); if (m_drawerLayout != null) { m_drawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ m_drawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.changelist, /* "open drawer" description */ R.string.app_label /* "close drawer" description */ ) { /** * Called when a drawer has settled in a completely closed * state. */ public void onDrawerClosed(View view) { // setTitle(R.string.app_label); } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { // setTitle(R.string.changelist); } }; // Set the drawer toggle as the DrawerListener m_drawerLayout.setDrawerListener(m_drawerToggle); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } m_drawerToggle.syncState(); } // Show search or filter results Intent intent = getIntent(); if (Constants.INTENT_START_FILTER.equals(intent.getAction())) { mFilter.initFromIntent(intent); Log.v(TAG, "handleIntent: launched with filter" + mFilter); Log.v(TAG, "handleIntent: saving filter in prefs"); mFilter.saveInPrefs(TodoApplication.getPrefs()); } else { // Set previous filters and sort Log.v(TAG, "handleIntent: from m_prefs state"); mFilter.initFromPrefs(TodoApplication.getPrefs()); } // Initialize Adapter if (m_adapter == null) { m_adapter = new TaskAdapter(getLayoutInflater()); } m_adapter.setFilteredTasks(); getListView().setAdapter(this.m_adapter); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); lv.setMultiChoiceModeListener(new ActionBarListener()); lv.setClickable(true); lv.setOnItemClickListener(this); // If we were started with a selected task, // select it now and clear it from the intent String selectedTask = intent.getStringExtra(Constants.INTENT_SELECTED_TASK); if (!Strings.isEmptyOrNull(selectedTask)) { String[] parts = selectedTask.split(":", 2); setSelectedTask(Integer.valueOf(parts[0]), parts[1]); intent.removeExtra(Constants.INTENT_SELECTED_TASK); setIntent(intent); } else { // Set the adapter for the list view updateDrawers(); } if (m_savedInstanceState != null) { ArrayList<String> selection = m_savedInstanceState.getStringArrayList("selection"); int position = m_savedInstanceState.getInt("position"); if (selection != null) { for (String selected : selection) { String[] parts = selected.split(":", 2); setSelectedTask(Integer.valueOf(parts[0]), parts[1]); } } lv.setSelectionFromTop(position, 0); } }
From source file:github.daneren2005.dsub.fragments.NowPlayingFragment.java
private boolean menuItemSelected(int menuItemId, final DownloadFile song) { List<Entry> songs;/* ww w . j av a 2 s . c om*/ switch (menuItemId) { case R.id.menu_show_album: case R.id.menu_show_artist: Entry entry = song.getSong(); Intent intent = new Intent(context, SubsonicFragmentActivity.class); intent.putExtra(Constants.INTENT_EXTRA_VIEW_ALBUM, true); String albumId; String albumName; if (menuItemId == R.id.menu_show_album) { if (Util.isTagBrowsing(context)) { albumId = entry.getAlbumId(); } else { albumId = entry.getParent(); } albumName = entry.getAlbum(); } else { if (Util.isTagBrowsing(context)) { albumId = entry.getArtistId(); } else { albumId = entry.getGrandParent(); if (albumId == null) { intent.putExtra(Constants.INTENT_EXTRA_NAME_CHILD_ID, entry.getParent()); } } albumName = entry.getArtist(); intent.putExtra(Constants.INTENT_EXTRA_NAME_ARTIST, true); } intent.putExtra(Constants.INTENT_EXTRA_NAME_ID, albumId); intent.putExtra(Constants.INTENT_EXTRA_NAME_NAME, albumName); intent.putExtra(Constants.INTENT_EXTRA_FRAGMENT_TYPE, "Artist"); if (Util.isOffline(context)) { try { // This should only be successful if this is a online song in offline mode Integer.parseInt(entry.getParent()); String root = FileUtil.getMusicDirectory(context).getPath(); String id = root + "/" + entry.getPath(); id = id.substring(0, id.lastIndexOf("/")); if (menuItemId == R.id.menu_show_album) { intent.putExtra(Constants.INTENT_EXTRA_NAME_ID, id); } id = id.substring(0, id.lastIndexOf("/")); if (menuItemId != R.id.menu_show_album) { intent.putExtra(Constants.INTENT_EXTRA_NAME_ID, id); intent.putExtra(Constants.INTENT_EXTRA_NAME_NAME, entry.getArtist()); intent.removeExtra(Constants.INTENT_EXTRA_NAME_CHILD_ID); } } catch (Exception e) { // Do nothing, entry.getParent() is fine } } intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Util.startActivityWithoutTransition(context, intent); return true; case R.id.menu_lyrics: { SubsonicFragment fragment = new LyricsFragment(); Bundle args = new Bundle(); args.putString(Constants.INTENT_EXTRA_NAME_ARTIST, song.getSong().getArtist()); args.putString(Constants.INTENT_EXTRA_NAME_TITLE, song.getSong().getTitle()); fragment.setArguments(args); replaceFragment(fragment); return true; } case R.id.menu_remove_all: Util.confirmDialog(context, R.string.download_menu_remove_all, "", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new SilentBackgroundTask<Void>(context) { @Override protected Void doInBackground() throws Throwable { getDownloadService().setShufflePlayEnabled(false); getDownloadService().clear(); return null; } @Override protected void done(Void result) { context.closeNowPlaying(); } }.execute(); } }); return true; case R.id.menu_screen_on_off: if (getDownloadService().getKeepScreenOn()) { context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getDownloadService().setKeepScreenOn(false); } else { context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getDownloadService().setKeepScreenOn(true); } context.supportInvalidateOptionsMenu(); return true; case R.id.menu_remove_played: if (getDownloadService().isRemovePlayed()) { getDownloadService().setRemovePlayed(false); } else { getDownloadService().setRemovePlayed(true); } context.supportInvalidateOptionsMenu(); return true; case R.id.menu_shuffle: new SilentBackgroundTask<Void>(context) { @Override protected Void doInBackground() throws Throwable { getDownloadService().shuffle(); return null; } @Override protected void done(Void result) { Util.toast(context, R.string.download_menu_shuffle_notification); } }.execute(); return true; case R.id.menu_save_playlist: List<Entry> entries = new LinkedList<Entry>(); for (DownloadFile downloadFile : getDownloadService().getSongs()) { entries.add(downloadFile.getSong()); } createNewPlaylist(entries, true); return true; case R.id.menu_star: toggleStarred(song.getSong()); return true; case R.id.menu_rate: setRating(song.getSong()); return true; case R.id.menu_toggle_timer: if (getDownloadService().getSleepTimer()) { getDownloadService().stopSleepTimer(); context.supportInvalidateOptionsMenu(); } else { startTimer(); } return true; case R.id.menu_add_playlist: songs = new ArrayList<Entry>(1); songs.add(song.getSong()); addToPlaylist(songs); return true; case R.id.menu_info: displaySongInfo(song.getSong()); return true; case R.id.menu_share: songs = new ArrayList<Entry>(1); songs.add(song.getSong()); createShare(songs); return true; case R.id.menu_equalizer: { DownloadService downloadService = getDownloadService(); if (downloadService != null) { EqualizerController controller = downloadService.getEqualizerController(); if (controller != null) { SubsonicFragment fragment = new EqualizerFragment(); replaceFragment(fragment); setControlsVisible(true); return true; } } // Any failed condition will get here Util.toast(context, "Failed to start equalizer. Try restarting."); return true; } default: return false; } }
From source file:github.popeen.dsub.fragments.NowPlayingFragment.java
private boolean menuItemSelected(int menuItemId, final DownloadFile song) { List<Entry> songs;// w w w . jav a 2 s .co m switch (menuItemId) { case R.id.menu_show_album: case R.id.menu_show_artist: Entry entry = song.getSong(); Intent intent = new Intent(context, SubsonicFragmentActivity.class); intent.putExtra(Constants.INTENT_EXTRA_VIEW_ALBUM, true); String albumId; String albumName; if (menuItemId == R.id.menu_show_album) { if (Util.isTagBrowsing(context)) { albumId = entry.getAlbumId(); } else { albumId = entry.getParent(); } albumName = entry.getAlbum(); } else { if (Util.isTagBrowsing(context)) { albumId = entry.getArtistId(); } else { albumId = entry.getGrandParent(); if (albumId == null) { intent.putExtra(Constants.INTENT_EXTRA_NAME_CHILD_ID, entry.getParent()); } } albumName = entry.getArtist(); intent.putExtra(Constants.INTENT_EXTRA_NAME_ARTIST, true); } intent.putExtra(Constants.INTENT_EXTRA_NAME_ID, albumId); intent.putExtra(Constants.INTENT_EXTRA_NAME_NAME, albumName); intent.putExtra(Constants.INTENT_EXTRA_FRAGMENT_TYPE, "Artist"); if (Util.isOffline(context)) { try { // This should only be successful if this is a online song in offline mode Integer.parseInt(entry.getParent()); String root = FileUtil.getMusicDirectory(context).getPath(); String id = root + "/" + entry.getPath(); id = id.substring(0, id.lastIndexOf("/")); if (menuItemId == R.id.menu_show_album) { intent.putExtra(Constants.INTENT_EXTRA_NAME_ID, id); } id = id.substring(0, id.lastIndexOf("/")); if (menuItemId != R.id.menu_show_album) { intent.putExtra(Constants.INTENT_EXTRA_NAME_ID, id); intent.putExtra(Constants.INTENT_EXTRA_NAME_NAME, entry.getArtist()); intent.removeExtra(Constants.INTENT_EXTRA_NAME_CHILD_ID); } } catch (Exception e) { // Do nothing, entry.getParent() is fine } } intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Util.startActivityWithoutTransition(context, intent); return true; case R.id.menu_lyrics: { SubsonicFragment fragment = new LyricsFragment(); Bundle args = new Bundle(); args.putString(Constants.INTENT_EXTRA_NAME_ARTIST, song.getSong().getArtist()); args.putString(Constants.INTENT_EXTRA_NAME_TITLE, song.getSong().getTitle()); fragment.setArguments(args); replaceFragment(fragment); return true; } case R.id.menu_remove_all: Util.confirmDialog(context, R.string.download_menu_remove_all, "", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new SilentBackgroundTask<Void>(context) { @Override protected Void doInBackground() throws Throwable { getDownloadService().setShufflePlayEnabled(false); getDownloadService().clear(); return null; } @Override protected void done(Void result) { context.closeNowPlaying(); } }.execute(); } }); return true; case R.id.menu_screen_on_off: if (getDownloadService().getKeepScreenOn()) { context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getDownloadService().setKeepScreenOn(false); } else { context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getDownloadService().setKeepScreenOn(true); } context.supportInvalidateOptionsMenu(); return true; case R.id.menu_rate: UpdateHelper.setRating(context, song.getSong()); return true; case R.id.menu_toggle_timer: if (getDownloadService().getSleepTimer()) { getDownloadService().stopSleepTimer(); context.supportInvalidateOptionsMenu(); } else { startTimerDialog(); } return true; case R.id.menu_info: displaySongInfo(song.getSong()); return true; case R.id.menu_share: songs = new ArrayList<Entry>(1); songs.add(song.getSong()); createShare(songs); return true; case R.id.menu_equalizer: { DownloadService downloadService = getDownloadService(); if (downloadService != null) { EqualizerController controller = downloadService.getEqualizerController(); if (controller != null) { SubsonicFragment fragment = new EqualizerFragment(); replaceFragment(fragment); setControlsVisible(true); return true; } } // Any failed condition will get here Util.toast(context, "Failed to start equalizer. Try restarting."); return true; } default: return false; } }
From source file:com.dycody.android.idealnote.ListFragment.java
/** * Notes list adapter initialization and association to view *//*from www. ja va2 s. c o m*/ void initNotesList(Intent intent) { Log.d(Constants.TAG, "initNotesList intent: " + intent.getAction()); progress_wheel.setAlpha(1); list.setAlpha(0); // Search for a tag // A workaround to simplify it's to simulate normal search if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_BROWSABLE)) { searchTags = intent.getDataString().replace(UrlCompleter.HASHTAG_SCHEME, ""); goBackOnToggleSearchLabel = true; } // Searching searchQuery = searchQueryInstant; searchQueryInstant = null; if (searchTags != null || searchQuery != null || Intent.ACTION_SEARCH.equals(intent.getAction())) { // Using tags if (searchTags != null && intent.getStringExtra(SearchManager.QUERY) == null) { searchQuery = searchTags; NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByTag", searchQuery); } else { // Get the intent, verify the action and get the query if (intent.getStringExtra(SearchManager.QUERY) != null) { searchQuery = intent.getStringExtra(SearchManager.QUERY); searchTags = null; } NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByPattern", searchQuery); } toggleSearchLabel(true); } else { // Check if is launched from a widget with categories if ((Constants.ACTION_WIDGET_SHOW_LIST.equals(intent.getAction()) && intent.hasExtra(Constants.INTENT_WIDGET)) || !TextUtils.isEmpty(mainActivity.navigationTmp)) { String widgetId = intent.hasExtra(Constants.INTENT_WIDGET) ? intent.getExtras().get(Constants.INTENT_WIDGET).toString() : null; if (widgetId != null) { String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, ""); String categoryId = TextHelper.checkIntentCategory(sqlCondition); mainActivity.navigationTmp = !TextUtils.isEmpty(categoryId) ? categoryId : null; } intent.removeExtra(Constants.INTENT_WIDGET); if (mainActivity.navigationTmp != null) { Long categoryId = Long.parseLong(mainActivity.navigationTmp); NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByCategory", categoryId); } else { NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true); } } else { NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true); } } }