Example usage for android.content Intent FLAG_ACTIVITY_SINGLE_TOP

List of usage examples for android.content Intent FLAG_ACTIVITY_SINGLE_TOP

Introduction

In this page you can find the example usage for android.content Intent FLAG_ACTIVITY_SINGLE_TOP.

Prototype

int FLAG_ACTIVITY_SINGLE_TOP

To view the source code for android.content Intent FLAG_ACTIVITY_SINGLE_TOP.

Click Source Link

Document

If set, the activity will not be launched if it is already running at the top of the history stack.

Usage

From source file:eu.inmite.apps.smsjizdenka.util.NotificationUtil.java

public static void notifyMessage(Context c, String message) {
    Intent i = new Intent(c, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.putExtra(MainActivity.EXTRA_MESSAGE, message);
    PendingIntent contentIntent = PendingIntent.getActivity(c, NOTIFICATION_MESSAGE, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
    String title = c.getString(R.string.application_name);
    String text = message;//from  w  w w . j  a  va2  s.c  o m
    fireNotification(c, NOTIFICATION_VERIFY, contentIntent, title, text, null, null, title,
            R.drawable.notification_small_ready, R.drawable.notification_big_ready, null, false);
    Preferences.set(c, Preferences.MESSAGE_READ, false);
}

From source file:nl.hnogames.domoticz.NFCSettingsActivity.java

protected void onResume() {
    super.onResume();

    try {// ww  w  .java  2s  .  c o m
        // creating pending intent:
        PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // creating intent receiver for NFC events:
        IntentFilter filter = new IntentFilter();
        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);

        // enabling foreground dispatch for getting intent from NFC event:
        if (mNfcAdapter == null) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

            if (mNfcAdapter != null) {
                UsefulBits.showSnackbar(this, coordinatorLayout, R.string.nfc_register, Snackbar.LENGTH_SHORT);
            } else {
                UsefulBits.showSnackbar(this, coordinatorLayout, R.string.nfc_not_supported,
                        Snackbar.LENGTH_SHORT);
            }
        }
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, new IntentFilter[] { filter },
                    this.techList);
    } catch (Exception ex) {
        Log.e(this.getClass().getSimpleName(), ex.getMessage());
    }
}

From source file:com.microsoft.rightsmanagement.ui.UserPolicyViewerActivity.java

/**
 * Show UI./*www  . j  a  v  a2s. c  o  m*/
 * 
 * @param requestCode the request code for startActivityForResult
 * @param parentActivity the parent activity that invokes startActivityForResult
 * @param userPolicy user policy instance that provides data to display on the UI
 * @param supportedRights rights to check access for and display
 * @param policyViewerActivityRequestOption PolicyViewerActivityRequestOptions
 * @param policyViewerActivityCompletionCallback callback that's invoked upon completion of activity.
 * @throws InvalidParameterException the invalid parameter exception
 */
public static void show(int requestCode, Activity parentActivity, UserPolicy userPolicy,
        LinkedHashSet<String> supportedRights, int policyViewerActivityRequestOption,
        CompletionCallback<Integer> policyViewerActivityCompletionCallback) {
    Logger.ms(TAG, "show");
    parentActivity = validateActivityInputParameter(parentActivity);
    userPolicy = validateUserPolicyInputParameter(userPolicy);
    policyViewerActivityCompletionCallback = validateCompletionCallbackInputParameter(
            policyViewerActivityCompletionCallback);
    policyViewerActivityRequestOption = validatePolicyViewerActivityRequestOption(
            policyViewerActivityRequestOption);
    // put callback
    int requestCallbackId = policyViewerActivityCompletionCallback.hashCode();
    sCallbackManager.putWaitingRequest(requestCallbackId, policyViewerActivityCompletionCallback);
    // set launch intent
    Intent intent = new Intent(parentActivity, UserPolicyViewerActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(REQUEST_CALLBACK_ID, requestCallbackId);
    intent.putExtra(REQUEST_RESULT_POLICY_VIEWER_OPTIONS, policyViewerActivityRequestOption);
    intent.putExtra(REQUEST_RESULT_USER_POLICY_MODEL,
            (new UserPolicyModel(userPolicy, supportedRights, parentActivity.getApplicationContext())));
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    parentActivity.startActivityForResult(intent, requestCode);
    Logger.me(TAG, "show");
}

From source file:com.klinker.android.twitter.services.TalonPullNotificationService.java

@Override
public void onCreate() {
    super.onCreate();

    if (TalonPullNotificationService.isRunning) {
        stopSelf();/*from  w ww .  j  av a  2  s  .  com*/
        return;
    }

    TalonPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    pullUnread = sharedPreferences.getInt("pull_unread", 0);

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

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    Intent popup = new Intent(this, RedirectToPopup.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    popup.putExtra("from_notification", true);
    PendingIntent popupPending = PendingIntent.getActivity(this, 0, popup, 0);

    Intent compose = new Intent(this, WidgetCompose.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent composePending = PendingIntent.getActivity(this, 0, compose, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.talon_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
        mBuilder.addAction(R.drawable.ic_popup, getResources().getString(R.string.popup), popupPending);
        mBuilder.addAction(R.drawable.ic_send_dark, getResources().getString(R.string.tweet), composePending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;
                int rep = 0;

                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    ids = new ArrayList<Long>();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }

                    rep++;
                } while ((currCursor = idObject.getNextCursor()) != 0 && rep < 3);

                ids.add(settings.myId);

                idsLoaded = true;

                startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.klinker.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TalonPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TalonPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}

From source file:com.actionbarsherlock.sample.hcgallery.CameraFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.switch_cam:
        // Release this camera -> mCameraCurrentlyLocked
        if (mCamera != null) {
            mCamera.stopPreview();//from w  w  w .ja  v a 2  s  .c o m
            mPreview.setCamera(null);
            mCamera.release();
            mCamera = null;
        }

        // Acquire the next camera and request Preview to reconfigure
        // parameters.
        mCamera = Camera.open((mCameraCurrentlyLocked + 1) % mNumberOfCameras);
        mCameraCurrentlyLocked = (mCameraCurrentlyLocked + 1) % mNumberOfCameras;
        mPreview.switchCamera(mCamera);

        // Start the preview
        mCamera.startPreview();
        return true;
    case android.R.id.home:
        Intent intent = new Intent(this.getActivity(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:ca.ualberta.cs.drivr.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    userManager.setConnectivityManager((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE));

    /**//from  w w  w .j a va2 s  .c om
     * This calls the login activity a the beginning if there is no local user stored
     */
    if (userManager.getUser().getUsername().isEmpty()) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    context = getApplicationContext();
    PreferenceManager.setDefaultValues(this, R.xml.pref_driver_mode, false);

    setSupportActionBar(toolbar);

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

    mFragment = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.main_map);
    mFragment.getMapAsync(this);

    autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager()
            .findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            ConcretePlace concretePlace = new ConcretePlace(place);
            Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();
            if (userManager.getUserMode().equals(UserMode.RIDER)) {
                Intent intent = new Intent(MainActivity.this, NewRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(NewRequestActivity.EXTRA_PLACE, concretePlaceJson);
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);

            } else if (userManager.getUserMode().equals(UserMode.DRIVER)) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, concretePlaceJson);
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, "");
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);
            }
        }

        @Override
        public void onError(Status status) {
            // Do nothing
        }
    });

    // Using the floating action button menu system
    final FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.main_fab_menu);
    FloatingActionButton fabSettings = (FloatingActionButton) findViewById(R.id.fabSettings);
    FloatingActionButton fabRequests = (FloatingActionButton) findViewById(R.id.main_fab_requests);
    FloatingActionButton fabProfile = (FloatingActionButton) findViewById(R.id.main_fab_profile);
    FloatingActionButton fabHistory = (FloatingActionButton) findViewById(R.id.main_fah_history);
    FloatingActionButton fabLogin = (FloatingActionButton) findViewById(R.id.main_fab_login);
    final FloatingActionButton fabDriver = (FloatingActionButton) findViewById(R.id.main_driver_mode);
    final FloatingActionButton fabRider = (FloatingActionButton) findViewById(R.id.main_rider_mode);

    // Hide the settings FAB
    fabSettings.setVisibility(View.GONE);

    /*
    Change between user and driver mode. Will probably be replaced with an option in settings.
    For now the visibility of this is set to gone because we should not have too many FABs.
    Having too many FABs may cause confusion and rendering issues on small screens.
    */
    keywordEditText = (EditText) findViewById(R.id.main_keyword_edit_text);
    FloatingActionButton fabMode = (FloatingActionButton) findViewById(R.id.main_fab_mode);
    fabMode.setVisibility(View.GONE);
    if (userManager.getUserMode().equals(UserMode.RIDER)) {
        fabRider.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.GONE);
    } else {
        fabDriver.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.VISIBLE);
    }

    keywordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, "");
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, keywordEditText.getText().toString());
                keywordEditText.setText("");
                keywordEditText.clearFocus();
                startActivity(intent);
            }
            return true;
        }
    });

    fabMode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked mode fab");
            /*
            Will be able to implement code below once elasticSearch is up and running
            UserManager userManager = null; // Once elasticSearch is working will replace with finding a User
            if (userManager.getUserMode() == UserMode.DRIVER) {
            userManager.setUserMode(UserMode.RIDER);
            }
            else if (userManager.getUserMode() == UserMode.RIDER) {
            userManager.setUserMode(UserMode.DRIVER);
            //Will have to implement a method "FindNearbyRequests" to get requests whose source
            // is nearby and display it on the map
            //Intent intent = new Intent((MainActivity.this, FindNearbyRequests.class);)
            //startActivity(intent);
            }*/
        }
    });

    fabDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (userManager.getUser().getVehicleDescription().isEmpty()) {
                /*
                * From: http://stackoverflow.com/a/29048271
                * Author: Syeda Zunairah
                * Accessed: November 29, 2016
                * Creates a dialog box with an edit text to get the vehicle description.
                */
                AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                final EditText edittext = new EditText(v.getContext());
                edittext.setText("Vechicle Make");
                edittext.clearComposingText();
                alert.setTitle("Become a Driver!");
                alert.setMessage(
                        "Drivers are require to enter vehicle information!\n\nPlease enter your vehicle's make");

                alert.setView(edittext);

                alert.setPositiveButton("Save Description", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String vehicleDescription = edittext.getText().toString();
                        if (!vehicleDescription.isEmpty()) {
                            userManager.getUser().setVehicleDescription(vehicleDescription);
                            userManager.notifyObservers();
                            userManager.setUserMode(UserMode.DRIVER);
                            ElasticSearch elasticSearch = new ElasticSearch(
                                    userManager.getConnectivityManager());
                            elasticSearch.updateUser(userManager.getUser());
                            keywordEditText.setVisibility(View.VISIBLE);
                            fabDriver.setVisibility(View.GONE);
                            fabRider.setVisibility(View.VISIBLE);
                            fabMenu.close(true);
                        }
                        dialog.dismiss();
                    }
                });

                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });

                AlertDialog newAlert = alert.create();
                newAlert.show();
            }
            if (!userManager.getUser().getVehicleDescription().isEmpty()) {
                userManager.setUserMode(UserMode.DRIVER);
                keywordEditText.setVisibility(View.VISIBLE);
                fabDriver.setVisibility(View.GONE);
                fabRider.setVisibility(View.VISIBLE);
                fabMenu.close(true);
            }
        }
    });

    fabRider.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            userManager.setUserMode(UserMode.RIDER);
            keywordEditText.setVisibility(View.GONE);
            fabRider.setVisibility(View.GONE);
            fabDriver.setVisibility(View.VISIBLE);
            fabMenu.close(true);
        }
    });

    fabLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked settings fab");
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked profile fab");
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    fabHistory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked history fab");
            Intent intent = new Intent(MainActivity.this, RequestHistoryActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabRequests.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked requests fab");
            Intent intent = new Intent(MainActivity.this, RequestsListActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    setNotificationAlarm(context);
}

From source file:com.zion.music.NotificationHelper.java

/**
 * Open to the corresponding ArtistDetailsFragment
 *///ww w. j a va 2  s. c  om
private PendingIntent getPendingIntent(int artistId) {
    Intent intent = new Intent(this.service, ArtistDetailsActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra(ArtistDetailsActivity.EXTRA_ARTIST_ID, artistId);
    return PendingIntent.getActivity(this.service, 0, intent, 0);
}

From source file:de.grobox.liberario.fragments.PrefsFragment.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(Preferences.THEME)) {
        ListPreference themePref = (ListPreference) findPreference(key);
        themePref.setSummary(themePref.getEntry());

        getActivity().finish();/*from   w  w  w . j  a  v  a2 s .co m*/
        final Intent intent = getActivity().getIntent();
        intent.setAction(MainActivity.ACTION_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        getActivity().startActivity(intent);

        // switch back to this fragment, because it doesn't work the first time where fragment is not yet found
        final Intent intent2 = new Intent(getActivity(), MainActivity.class);
        intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent2.setAction(MainActivity.ACTION_SETTINGS);
        startActivity(intent2);
    }
}

From source file:com.stanleyidesis.quotograph.api.controller.LWQNotificationControllerImpl.java

@Override
public void postNewWallpaperNotification() {
    dismissWallpaperGenerationFailureNotification();
    final LWQWallpaperController wallpaperController = LWQWallpaperControllerHelper.get();
    // Compress background to reasonable Square size
    final Bitmap backgroundImage = wallpaperController.getBackgroundImage();
    if (backgroundImage == null) {
        return;/*  w  w w . jav a 2 s.  c om*/
    }
    final Bitmap notificationBitmap = chopToCenterSquare(backgroundImage);

    Context context = LWQApplication.get();

    // Establish basic options
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setCategory(Notification.CATEGORY_SERVICE);
    notificationBuilder.setColor(LWQApplication.get().getResources().getColor(R.color.palette_A100));
    notificationBuilder.setContentInfo(wallpaperController.getAuthor());
    notificationBuilder.setContentTitle(context.getString(R.string.new_quotograph));
    notificationBuilder.setContentText(String.format("\"%s\"", wallpaperController.getQuote()));
    notificationBuilder.setLights(LWQApplication.get().getResources().getColor(R.color.palette_A100), 500, 500);
    notificationBuilder.setLargeIcon(notificationBitmap);
    notificationBuilder.setOngoing(false);
    notificationBuilder.setShowWhen(false);
    notificationBuilder.setSmallIcon(R.mipmap.ic_stat);
    notificationBuilder.setTicker(String.format("New quote from %s", wallpaperController.getAuthor()));
    notificationBuilder.setWhen(System.currentTimeMillis());

    // Create BigTextStyle
    NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
    bigTextStyle.bigText(wallpaperController.getQuote());
    bigTextStyle.setBigContentTitle(wallpaperController.getAuthor());
    bigTextStyle.setSummaryText(context.getString(R.string.new_quotograph));
    notificationBuilder.setStyle(bigTextStyle);

    // Set Content Intent
    Intent mainIntent = new Intent(context, LWQActivateActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    notificationBuilder
            .setContentIntent(PendingIntent.getActivity(context, uniqueRequestCode++, mainIntent, 0));

    // Add Share Action
    Intent shareIntent = new Intent(context, LWQReceiver.class);
    shareIntent.setAction(context.getString(R.string.action_share));
    shareIntent.setData(Uri.parse(AnalyticsUtils.URI_SHARE_SOURCE_NOTIFICATION));
    final PendingIntent shareBroadcast = PendingIntent.getBroadcast(context, uniqueRequestCode++, shareIntent,
            0);
    final NotificationCompat.Action shareAction = new NotificationCompat.Action.Builder(R.mipmap.ic_share_white,
            context.getString(R.string.share), shareBroadcast).build();
    notificationBuilder.addAction(shareAction);

    // Add save to disk
    Intent saveToDiskIntent = new Intent(context, LWQSaveWallpaperActivity.class);
    saveToDiskIntent.setData(Uri.parse(AnalyticsUtils.URI_SAVE_SOURCE_NOTIFICATION));
    final PendingIntent saveToDiskActivity = PendingIntent.getActivity(context, uniqueRequestCode++,
            saveToDiskIntent, 0);
    final NotificationCompat.Action saveToDiskAction = new NotificationCompat.Action.Builder(
            R.mipmap.ic_save_white, context.getString(R.string.save_to_disk), saveToDiskActivity).build();
    notificationBuilder.addAction(saveToDiskAction);

    // Add Skip Action
    Intent skipIntent = new Intent(context, LWQReceiver.class);
    skipIntent.setAction(context.getString(R.string.action_change_wallpaper));
    // Track where the skip originated
    skipIntent.setData(Uri.parse(AnalyticsUtils.URI_CHANGE_SOURCE_NOTIFICATION));
    final PendingIntent skipBroadcast = PendingIntent.getBroadcast(context, uniqueRequestCode++, skipIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    final NotificationCompat.Action skipAction = new NotificationCompat.Action.Builder(
            R.mipmap.ic_skip_next_white, context.getString(R.string.skip), skipBroadcast).build();
    notificationBuilder.addAction(skipAction);

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIF_ID_PRIMARY, notificationBuilder.build());

    notificationBitmap.recycle();
}