Example usage for android.app NotificationManager cancelAll

List of usage examples for android.app NotificationManager cancelAll

Introduction

In this page you can find the example usage for android.app NotificationManager cancelAll.

Prototype

public void cancelAll() 

Source Link

Document

Cancel all previously shown notifications.

Usage

From source file:com.daiv.android.twitter.ui.drawer_activities.DrawerActivity.java

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

    // cancels the notifications when the app is opened
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancelAll();

    SharedPreferences.Editor e = sharedPrefs.edit();
    e.putInt("new_followers", 0);
    e.putInt("new_favorites", 0);
    e.putInt("new_retweets", 0);
    e.putString("old_interaction_text", "");
    e.commit();//from  www .j a va 2s.  com

    DrawerActivity.settings = AppSettings.getInstance(context);
}

From source file:com.androidquery.simplefeed.activity.PostActivity.java

private void notify(String ticker, String title, String message, Intent intent) {

    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

    int icon = R.drawable.launcher;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, ticker, when);

    Context context = getApplicationContext();
    CharSequence contentText = message;

    int id = getNotifyId();
    PendingIntent contentIntent = PendingIntent.getActivity(this, id, intent, 0);

    notification.setLatestEventInfo(context, title, contentText, contentIntent);

    mNotificationManager.cancelAll();

    AQUtility.debug("notify id", id);
    mNotificationManager.notify(id, notification);

}

From source file:com.google.android.marvin.screenspeak.ScreenSpeakService.java

/**
 * Registers listeners, sets service info, loads preferences. This should be called from
 * {@link #onServiceConnected} and when ScreenSpeak resumes from a suspended state.
 *//*from   w  w w .  j  av  a  2  s  . c  om*/
private void suspendInfrastructure() {
    if (!isServiceActive()) {
        if (LogUtils.LOG_LEVEL <= Log.ERROR) {
            Log.e(LOGTAG, "Attempted to suspend while already suspended");
        }
        return;
    }

    mDimScreenController.makeScreenBright();

    interruptAllFeedback();
    setServiceState(SERVICE_STATE_SUSPENDED);

    // Some apps depend on these being set to false when ScreenSpeak is disabled.
    if (mSupportsTouchScreen) {
        requestTouchExploration(false);
    }

    if (SUPPORTS_WEB_SCRIPT_TOGGLE) {
        requestWebScripts(false);
    }

    mPrefs.unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    unregisterReceiver(mActiveReceiver);

    if (mCallStateMonitor != null) {
        mCallStateMonitor.stopMonitor();
    }

    if (mRingerModeAndScreenMonitor != null) {
        unregisterReceiver(mRingerModeAndScreenMonitor);
    }

    if (mMenuManager != null) {
        mMenuManager.clearCache();
    }

    if (mVolumeMonitor != null) {
        unregisterReceiver(mVolumeMonitor);
        mVolumeMonitor.releaseControl();
    }

    if (mBatteryMonitor != null) {
        unregisterReceiver(mBatteryMonitor);
    }

    if (mPackageReceiver != null) {
        unregisterReceiver(mPackageReceiver);
    }

    if (mShakeDetector != null) {
        mShakeDetector.setEnabled(false);
    }

    // The tap detector is enabled through reloadPreferences
    if (mSideTapManager != null) {
        unregisterReceiver(mSideTapManager);
        mSideTapManager.onSuspendInfrastructure();
    }

    // Disable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);

    // Remove any pending notifications that shouldn't persist.
    final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancelAll();
}

From source file:com.paywith.ibeacon.service.IBeaconService.java

private void processRangeData() {
    // Don Kelley August 2014 (based loosely on original method from Radius)
    // This is the method that does most of the custom paywith magical logic.

    // always check if user logged in before continuing
    if (!getUserLoggedIn()) {
        Log.e("processRangeData() ", "user logged out");
        disableScanning();/*from   w  w  w.  j a v  a2 s .c  om*/
        return;
    }
    Iterator<Region> regionIterator = rangedRegionState.keySet().iterator();
    while (regionIterator.hasNext()) {
        Region region = regionIterator.next();
        RangeState rangeState = rangedRegionState.get(region);
        if (IBeaconManager.debug)
            Log.d(TAG, "Calling ranging callback");
        //rangeState.getCallback().call(IBeaconService.this, "rangingData", new RangingData(rangeState.finalizeIBeacons(), region));

        //Log.e("iterator",trackedBeacons);
        IBeacon nearest_beacon = findNearest(trackedBeacons);
        Boolean beacon_changed = false;

        if (nearest_beacon == null) {
            //Log.e("nearest_beacon() result","no beacon found");
            // if no paywith beacon nearby, remove any of our notifications.
            // Need this to only happen after several iterations of no beacon found.... 
            noPaywithBeaconCount = noPaywithBeaconCount + 1; // inc the counter and remove notification if higher than 10 cycles

            if (noPaywithBeaconCount > 3) {
                // clear all paywith notifications and launch url... nothing has been found for 10 cycles
                setNextLaunchUrl(null);
                NotificationManager notificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notificationManager.cancelAll();
                old_locid = 0;
                old_locid2 = 0;
                lastBeaconFound = null;
                lastBeaconFound2 = null;
                lastaction = "cancelAll";
            }
            return;
        }
        noPaywithBeaconCount = 0; // always reset the sequential nobeaconsfound counter once a nearby paywith beacon is found

        Integer m1 = nearest_beacon.getMinor();
        Integer M1 = nearest_beacon.getMajor();
        Integer m2 = 0; // just some safe default settings
        Integer M2 = 0;
        Integer m3 = 0;
        Integer M3 = 0;
        if (lastBeaconFound != null) {
            m2 = lastBeaconFound.getMinor();
            M2 = lastBeaconFound.getMajor();
        }

        if (lastBeaconFound2 != null) {
            m3 = lastBeaconFound2.getMinor();
            M3 = lastBeaconFound2.getMajor();
        }

        //Log.e("service",m1.toString() + " = " + m2.toString() + " = " + m3.toString() + ", " + M1.toString() + " = " + M2.toString() + " = " + M3.toString());
        lastBeaconFound2 = lastBeaconFound;
        lastBeaconFound = nearest_beacon;

        //Log.e("matching?",m1.toString() + " = " + m2.toString() + ", " + M1.toString() + " = " + M2.toString());
        if (!m1.equals(m2) || !M1.equals(M2) || !m2.equals(m3) || !M2.equals(M3)) {
            // simple debouncer queue:
            // We only get past this point if beacon found is same as last beacon found and also the one before that.
            //return;
            // skip this... now that we're reducing the frequency of beacon checks, this will take way too long to happen.
        }

        Integer thisminor = nearest_beacon.getMinor();
        String muuid = nearest_beacon.getProximityUuid();
        Integer mmajor = nearest_beacon.getMajor();
        Integer mminor = nearest_beacon.getMinor();
        Double distance = nearest_beacon.getAccuracy();

        String last_updated_at = null; // need to do the date formatting below.
        String current_datetime = null;
        String beaconurl;
        String beaconname;
        Integer location_id;
        // also need to store results of this api beacon call in sharedprefs and check
        // if data for a found beacon exists there and use that data before making a
        // possibly unneccessary api callback about it.

        // note: I need to do something like this still (from iOS app):

        String format = "yyyy-MM-dd HH:mm:ss Z";
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
        //System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
        //sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        current_datetime = sdf.format(new Date(0)); // this will be used for beacon database getUpdatedAt/setUpdatedAt string dates        

        // Set a Beacon Shell object into UserHelper with last updated at of right now
        // so that we do not query for this Beacon again until +24hours since we do not want to overwhelm device
        /*NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:DATE_FORMAT];
        NSString *last_updated_at = [dateFormatter stringFromDate:[NSDate date]];*/
        // the call should include last_updated_at, @"last_updated_at

        // experimenting with storing in my new sqlite db and looking for existing records there before hitting api

        DatabaseHandler db = new DatabaseHandler(this);

        /**
         * CRUD Operations
         * */

        //Log.e("Select:", "Looking for beacon in db..");
        BeaconStore foundBeacon = db.getBeacon(muuid, mmajor, mminor);

        // Read all beacons (just a database demo example - not sure we'll ever need it in our app)
        /*Log.e("Reading: ", "Reading all beacons.."); 
        List<BeaconStore> beacons = db.getAllBeacons();       
                 
        for (BeaconStore cn : beacons) {
        String log = "Id: "+cn.getID()+" ,uuid: " + cn.getUuid() + " ,major: " + cn.getMajor() + " ,minor: " + cn.getMinor();
            // Writing Contacts to log
        Log.e("Beacon: ", log);
        }*/

        // beacon isn't in our phone database so poll api about it
        if (foundBeacon == null) {
            Log.e("Service", "Making API Call");
            //if (distance < 1) {
            // distance handling is done in nearest_beacon() now...
            //Log.e("IBeaconService","*** mminor=" + mminor.toString() + ", distance =" + distance.toString());
            Map<String, String> beaconApiData = runAppAPI("beaconInfoRequest", muuid, mmajor.toString(),
                    mminor.toString());

            //Log.e("Insert: ", "Inserting beacon from api results.."); 
            //String mername = beaconApiData.get("name");
            //Integer locid = Integer.parseInt(beaconApiData.get("location_id"));
            //String url = beaconApiData.get("url");  

            beaconurl = beaconApiData.get("url");
            beaconname = beaconApiData.get("name");
            location_id = Integer.parseInt(beaconApiData.get("location_id"));

            // Insert Beacon
            db.addBeacon(new BeaconStore(muuid, mmajor, mminor, current_datetime, beaconname, location_id,
                    beaconurl));

        } else {

            //Log.e("Service","!*!*! NOT Making API Call - beacon already in our sql db!");

            beaconurl = foundBeacon.getUrl();
            beaconname = foundBeacon.getMerchantName();
            location_id = foundBeacon.getLocationId();
        }

        // Check if database current_datetime for this beacon is older than 1 hour and older than 24 hours.
        // different logic may result based on those values.
        // for example, if greater than 24 hours old, we should still poll the api for updated info about this beacon.
        // 

        //Log.e("ibeaconservice","about to send data to app");
        //Log.e("beaconurl"," " + beaconurl);
        if (beaconurl != null && beaconurl != "signinfailure") {
            // force open app at payment page:
            //Log.e("service","beaconurl = " + beaconurl);
            String previousNotificationUrl = apiInstance.getCurrentLaunchUrl();
            // only generate notification if it's different from the last one
            String notetext = "Pay with your phone";
            notetext = notetext + " at " + beaconname;

            //Log.e("service","lastaction=" + lastaction + ", lastlocationid=" + lastlocationid.toString() + ", location_id=" + location_id.toString());
            //Log.e("locid before N/1/2",location_id+"/"+old_locid+"/"+old_locid2);

            // if location_id has changed from last two sent by a notification in this background service:
            beacon_changed = (location_id.equals(old_locid) && old_locid.equals(old_locid2));
            //Log.e("beacon_changed",beacon_changed.toString());
            //old_locid = location_id;
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            boolean isScreenOn = powerManager.isScreenOn();
            boolean keyboardLocked = km.inKeyguardRestrictedInputMode();

            if (isForeground("com.paywith.paywith") && isScreenOn && !keyboardLocked) {
                // only if the app is running main on your phone AND phone is currently unlocked

                // only do this if:
                // the last thing this service did was NOT send a location id
                // OR the last thing this service did was NOT send this same location change

                // also add the 3 level debouncer when in foreground to locations list 
                //Log.e("matching?",m1.toString() + " = " + m2.toString() + ", " + M1.toString() + " = " + M2.toString());
                if (!m1.equals(m2) || !M1.equals(M2) || !m2.equals(m3) || !M2.equals(M3)) {
                    // simple debouncer queue:
                    // We only get past this point if beacon found is same as last beacon found and also the one before that.
                    return;
                    // skip this... now that we're reducing the frequency of beacon checks, this will take way too long to happen.
                }
                //if (!lastaction.equals("moveLocationToTop") || 
                //      lastaction.equals("moveLocationToTop") && !lastlocationid.equals(location_id)) {

                //Log.e("service","sending new location to locationlist:" + location_id.toString());
                // tell app to move this location to top of location list if possible
                moveLocationToTop(location_id.toString());
                //}
                //generateNotification("TEST",notetext, beaconurl, location_id.toString());// this generates system notification

                lastaction = "moveLocationToTop";
                scanPeriod = IBeaconManager.DEFAULT_FOREGROUND_SCAN_PERIOD;
                betweenScanPeriod = IBeaconManager.DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD;
                //setScanPeriods(scanPeriod,betweenScanPeriod);
                //Log.e("sending intent","locations list order");
            } else if (!lastaction.equals("generateNotification")
                    || lastaction.equals("generateNotification") && !lastlocationid.equals(location_id)) { // add hour timer here also                       
                // && beacon_changed
                // only if app is running in background or not running at all.

                // only do this if:
                // the last thing this service did was NOT send a location id
                // OR the last thing this service did was NOT send this same location change
                // ALSO only notify if this location hasn't been notified within last hour.  (still necessary?  not sure...)
                // (trying without the hour thing for now).

                // simple debouncer targetted at notifications:
                if (!m1.equals(m2) || !M1.equals(M2) || !m2.equals(m3) || !M2.equals(M3)) {
                    //if (m1.equals(m2) && M1.equals(M2) || m1.equals(m3) && M1.equals(M3)) {
                    // logic:  if this beacon was notified within the past 3 cycles, don't notify again.
                    return;
                }

                // generate notification.
                generateNotification("Pay Here", notetext, beaconurl, location_id.toString());// this generates system notification
                setNextLaunchUrl(beaconurl);
                setNextLaunchName(beaconname);
                lastaction = "generateNotification";
                //Log.e("sending intent","*** notification of new location");
                scanPeriod = IBeaconManager.DEFAULT_BACKGROUND_SCAN_PERIOD;
                betweenScanPeriod = IBeaconManager.DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD;
                //setScanPeriods(scanPeriod,betweenScanPeriod);
            }
            lastlocationid = location_id;
            //}
            // update location_id queue history
            old_locid2 = old_locid;
            old_locid = location_id;
        }
    }

}

From source file:com.google.android.marvin.mytalkback.TalkBackService.java

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when TalkBack resumes from a
 * suspended state.//from   w  w w  .j a v a 2 s  .com
 */
private void suspendInfrastructure() {
    if (!isServiceActive()) {
        LogUtils.log(this, Log.ERROR, "Attempted to suspend while already suspended");
        return;
    }

    interruptAllFeedback();
    setServiceState(ServiceState.SUSPENDED);

    setServiceInfo(new AccessibilityServiceInfo());

    mPrefs.unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    unregisterReceiver(mActiveReceiver);

    if (mCallStateMonitor != null) {
        unregisterReceiver(mCallStateMonitor);
    }

    if (mRingerModeAndScreenMonitor != null) {
        unregisterReceiver(mRingerModeAndScreenMonitor);
    }

    if (mRadialMenuManager != null) {
        unregisterReceiver(mRadialMenuManager);
        mRadialMenuManager.clearCache();
    }

    if (mVolumeMonitor != null) {
        unregisterReceiver(mVolumeMonitor);
        mVolumeMonitor.releaseControl();
    }

    if (mShakeDetector != null) {
        mShakeDetector.setEnabled(false);
    }

    if (SUPPORTS_TOUCH_PREF) {
        final ContentResolver resolver = getContentResolver();
        resolver.unregisterContentObserver(mTouchExploreObserver);
    }

    // Disable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);

    // Remove any pending notifications that shouldn't persist.
    final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancelAll();

    if (mTtsOverlay != null) {
        mTtsOverlay.hide();
    }
}

From source file:com.money.manager.ex.home.MainActivity.java

@Override
protected void onDestroy() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    if (notificationManager != null)
        notificationManager.cancelAll();
    super.onDestroy();

}

From source file:com.google.android.marvin.talkback.TalkBackService.java

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when TalkBack resumes from a
 * suspended state./*w  w  w. j  av a  2s . c  o  m*/
 */
private void suspendInfrastructure() {
    if (!isServiceActive()) {
        LogUtils.log(this, Log.ERROR, "Attempted to suspend while already suspended");
        return;
    }

    interruptAllFeedback();
    setServiceState(ServiceState.SUSPENDED);

    setServiceInfo(new AccessibilityServiceInfo());

    mPrefs.unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    unregisterReceiver(mActiveReceiver);

    if (mCallStateMonitor != null) {
        unregisterReceiver(mCallStateMonitor);
    }

    if (mRingerModeAndScreenMonitor != null) {
        unregisterReceiver(mRingerModeAndScreenMonitor);
    }

    if (mRadialMenuManager != null) {
        unregisterReceiver(mRadialMenuManager);
        mRadialMenuManager.clearCache();
    }

    if (mVolumeMonitor != null) {
        unregisterReceiver(mVolumeMonitor);
        mVolumeMonitor.releaseControl();
    }

    if (mPackageReceiver != null) {
        unregisterReceiver(mPackageReceiver);
    }

    if (mShakeDetector != null) {
        mShakeDetector.setEnabled(false);
    }

    if (SUPPORTS_TOUCH_PREF) {
        final ContentResolver resolver = getContentResolver();
        resolver.unregisterContentObserver(mTouchExploreObserver);
    }

    // Disable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);

    // Remove any pending notifications that shouldn't persist.
    final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancelAll();

    if (mTtsOverlay != null) {
        mTtsOverlay.hide();
    }
}

From source file:com.projecttango.experiments.basictango_button.MainActivity.java

public void togglestate(View view) {

    isOn = ((ToggleButton) view).isChecked();

    // Gets an instance of the NotificationManager service
    NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    //Intent for Stop button on Notification
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("isOn", "false");
    PendingIntent aIntent = PendingIntent.getActivity(this, 0, intent, 0);

    //Intent for Restart button on Notification
    Intent intent2 = new Intent(this, RestartActivity.class);
    intent.putExtra("isOn", "true");
    PendingIntent bIntent = PendingIntent.getActivity(this, 0, intent2, 0);

    //NOTIFICATION SETUP
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.appicon)
            .setContentTitle("UTC Tango").setContentText("Collecting Data!").setOngoing(true).setPriority(2)
            .setAutoCancel(true).setDeleteIntent(aIntent).addAction(R.drawable.none, "Stop Session", aIntent)
            .addAction(R.drawable.none, "Restart", bIntent);
    int mNotificationId = 8001; //Notification ID

    if (isOn) {//w  w  w  . j a  va2s . c  om

        //create UUID for session;
        uuid = UUID.randomUUID();

        //Starting Toast
        Toast.makeText(getApplicationContext(), "Collecting Data...", Toast.LENGTH_SHORT).show();

        // Builds the notification and issues it.
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
    } else { //action if button is false
        isOn = false;
        mNotifyMgr.cancelAll(); //kill notification

        //Stopping Toast
        Toast.makeText(getApplicationContext(), "Stopped collecting data", Toast.LENGTH_SHORT).show();
    }
}

From source file:amigoinn.example.v4sales.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");
    if (update_file.length() > 0) {
        setChanged();//from   ww w.j a  v a 2s  .  c om
        notifyObservers(AUTOUPDATE_HAVE_UPDATE);

        // raise the notification
        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Select to install";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(appIcon);
        builder.setTicker(appName + " update");
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setContentIntent(contentIntent);
        builder.setWhen(System.currentTimeMillis());
        builder.setAutoCancel(true);
        builder.setOngoing(true);

        nm.notify(NOTIFICATION_ID, builder.build());
    } else {
        //nm.cancel( NOTIFICATION_ID );   // tried this, but it just doesn't do the trick =(
        nm.cancelAll();
    }
}

From source file:im.vector.activity.RoomActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (CommonActivityUtils.shouldRestartApp()) {
        Log.e(LOG_TAG, "Restart the application.");
        CommonActivityUtils.restartApp(this);
    }//from  w  ww.ja va  2  s.c o m

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_room);

    Intent intent = getIntent();
    if (!intent.hasExtra(EXTRA_ROOM_ID)) {
        Log.e(LOG_TAG, "No room ID extra.");
        finish();
        return;
    }

    // the user has tapped on the "View" notification button
    if ((null != intent.getAction()) && (intent.getAction().startsWith(NotificationUtils.TAP_TO_VIEW_ACTION))) {
        // remove any pending notifications
        NotificationManager notificationsManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationsManager.cancelAll();
    }

    mPendingThumbnailUrl = null;
    mPendingMediaUrl = null;
    mPendingMimeType = null;
    mPendingFilename = null;

    if (null != savedInstanceState) {
        if (savedInstanceState.containsKey(PENDING_THUMBNAIL_URL)) {
            mPendingThumbnailUrl = savedInstanceState.getString(PENDING_THUMBNAIL_URL);
        }

        if (savedInstanceState.containsKey(PENDING_MEDIA_URL)) {
            mPendingMediaUrl = savedInstanceState.getString(PENDING_MEDIA_URL);
        }

        if (savedInstanceState.containsKey(PENDING_MIMETYPE)) {
            mPendingMimeType = savedInstanceState.getString(PENDING_MIMETYPE);
        }

        if (savedInstanceState.containsKey(PENDING_FILENAME)) {
            mPendingFilename = savedInstanceState.getString(PENDING_FILENAME);
        }
    }

    String roomId = intent.getStringExtra(EXTRA_ROOM_ID);
    Log.i(LOG_TAG, "Displaying " + roomId);

    mEditText = (EditText) findViewById(R.id.editText_messageBox);

    mSendButton = (ImageButton) findViewById(R.id.button_send);
    mSendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // send the previewed image ?
            if (null != mPendingThumbnailUrl) {
                boolean sendMedia = true;

                // check if the media could be resized
                if ("image/jpeg".equals(mPendingMimeType)) {

                    System.gc();
                    FileInputStream imageStream = null;

                    try {
                        Uri uri = Uri.parse(mPendingMediaUrl);
                        final String filename = uri.getPath();

                        final int rotationAngle = ImageUtils.getRotationAngleForBitmap(RoomActivity.this, uri);

                        imageStream = new FileInputStream(new File(filename));

                        int fileSize = imageStream.available();

                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                        options.outWidth = -1;
                        options.outHeight = -1;

                        // get the full size bitmap
                        Bitmap fullSizeBitmap = null;
                        try {
                            fullSizeBitmap = BitmapFactory.decodeStream(imageStream, null, options);
                        } catch (OutOfMemoryError e) {
                            Log.e(LOG_TAG, "Onclick BitmapFactory.decodeStream : " + e.getMessage());
                        }

                        final ImageSize fullImageSize = new ImageSize(options.outWidth, options.outHeight);

                        imageStream.close();

                        int maxSide = (fullImageSize.mHeight > fullImageSize.mWidth) ? fullImageSize.mHeight
                                : fullImageSize.mWidth;

                        // can be rescaled ?
                        if (maxSide > SMALL_IMAGE_SIZE) {
                            ImageSize largeImageSize = null;

                            int divider = 2;

                            if (maxSide > LARGE_IMAGE_SIZE) {
                                largeImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                                divider *= 2;
                            }

                            ImageSize mediumImageSize = null;

                            if (maxSide > MEDIUM_IMAGE_SIZE) {
                                mediumImageSize = new ImageSize(
                                        (fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                                divider *= 2;
                            }

                            ImageSize smallImageSize = null;

                            if (maxSide > SMALL_IMAGE_SIZE) {
                                smallImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                            }

                            FragmentManager fm = getSupportFragmentManager();
                            ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                                    .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                            if (fragment != null) {
                                fragment.dismissAllowingStateLoss();
                            }

                            final ArrayList<ImageCompressionDescription> textsList = new ArrayList<ImageCompressionDescription>();
                            final ArrayList<ImageSize> sizesList = new ArrayList<ImageSize>();

                            ImageCompressionDescription description = new ImageCompressionDescription();
                            description.mCompressionText = getString(R.string.compression_opt_list_original);
                            description.mCompressionInfoText = fullImageSize.mWidth + "x"
                                    + fullImageSize.mHeight + " ("
                                    + android.text.format.Formatter.formatFileSize(RoomActivity.this, fileSize)
                                    + ")";

                            textsList.add(description);
                            sizesList.add(fullImageSize);

                            if (null != largeImageSize) {
                                int estFileSize = largeImageSize.mWidth * largeImageSize.mHeight * 2 / 10 / 1024
                                        * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_large);
                                description.mCompressionInfoText = largeImageSize.mWidth + "x"
                                        + largeImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(largeImageSize);
                            }

                            if (null != mediumImageSize) {
                                int estFileSize = mediumImageSize.mWidth * mediumImageSize.mHeight * 2 / 10
                                        / 1024 * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_medium);
                                description.mCompressionInfoText = mediumImageSize.mWidth + "x"
                                        + mediumImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(mediumImageSize);
                            }

                            if (null != smallImageSize) {
                                int estFileSize = smallImageSize.mWidth * smallImageSize.mHeight * 2 / 10 / 1024
                                        * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_small);
                                description.mCompressionInfoText = smallImageSize.mWidth + "x"
                                        + smallImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(smallImageSize);
                            }

                            fragment = ImageSizeSelectionDialogFragment.newInstance(textsList);
                            fragment.setListener(new ImageSizeSelectionDialogFragment.ImageSizeListener() {
                                @Override
                                public void onSelected(int pos) {
                                    final int fPos = pos;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                // pos == 0 -> original
                                                if (0 != fPos) {
                                                    FileInputStream imageStream = new FileInputStream(
                                                            new File(filename));

                                                    ImageSize imageSize = sizesList.get(fPos);
                                                    InputStream resizeBitmapStream = null;

                                                    try {
                                                        resizeBitmapStream = ImageUtils.resizeImage(imageStream,
                                                                -1,
                                                                (fullImageSize.mWidth + imageSize.mWidth - 1)
                                                                        / imageSize.mWidth,
                                                                75);
                                                    } catch (OutOfMemoryError ex) {
                                                        Log.e(LOG_TAG,
                                                                "Onclick BitmapFactory.createScaledBitmap : "
                                                                        + ex.getMessage());
                                                    } catch (Exception e) {
                                                        Log.e(LOG_TAG,
                                                                "Onclick BitmapFactory.createScaledBitmap failed : "
                                                                        + e.getMessage());
                                                    }

                                                    if (null != resizeBitmapStream) {
                                                        String bitmapURL = mMediasCache.saveMedia(
                                                                resizeBitmapStream, null, "image/jpeg");

                                                        if (null != bitmapURL) {
                                                            mPendingMediaUrl = bitmapURL;
                                                        }

                                                        resizeBitmapStream.close();

                                                        // try to apply exif rotation
                                                        if (0 != rotationAngle) {
                                                            // rotate the image content
                                                            ImageUtils.rotateImage(RoomActivity.this,
                                                                    mPendingMediaUrl, rotationAngle,
                                                                    mMediasCache);
                                                        }
                                                    }
                                                }
                                            } catch (Exception e) {
                                                Log.e(LOG_TAG, "Onclick " + e.getMessage());
                                            }

                                            //
                                            mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl,
                                                    mPendingMediaUrl, mPendingFilename, mPendingMimeType);
                                            mPendingThumbnailUrl = null;
                                            mPendingMediaUrl = null;
                                            mPendingMimeType = null;
                                            mPendingFilename = null;
                                            manageSendMoreButtons();
                                        }
                                    });
                                }
                            });

                            fragment.show(fm, TAG_FRAGMENT_IMAGE_SIZE_DIALOG);
                            sendMedia = false;
                        }

                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Onclick " + e.getMessage());
                    }
                }

                if (sendMedia) {
                    mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl,
                            mPendingFilename, mPendingMimeType);
                    mPendingThumbnailUrl = null;
                    mPendingMediaUrl = null;
                    mPendingMimeType = null;
                    mPendingFilename = null;
                    manageSendMoreButtons();
                }
            } else {
                String body = mEditText.getText().toString();
                sendMessage(body);
                mEditText.setText("");
            }
        }
    });

    mAttachmentButton = (ImageButton) findViewById(R.id.button_more);
    mAttachmentButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            FragmentManager fm = getSupportFragmentManager();
            IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm
                    .findFragmentByTag(TAG_FRAGMENT_ATTACHMENTS_DIALOG);

            if (fragment != null) {
                fragment.dismissAllowingStateLoss();
            }

            final Integer[] messages = new Integer[] { R.string.option_send_files,
                    R.string.option_take_photo, };

            final Integer[] icons = new Integer[] { R.drawable.ic_material_file, // R.string.option_send_files
                    R.drawable.ic_material_camera, // R.string.action_members
            };

            fragment = IconAndTextDialogFragment.newInstance(icons, messages, null,
                    RoomActivity.this.getResources().getColor(R.color.vector_title_color));
            fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() {
                @Override
                public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) {
                    Integer selectedVal = messages[position];

                    if (selectedVal == R.string.option_send_files) {
                        RoomActivity.this.launchFileSelectionIntent();
                    } else if (selectedVal == R.string.option_take_photo) {
                        RoomActivity.this.launchCamera();
                    }
                }
            });

            fragment.show(fm, TAG_FRAGMENT_INVITATION_MEMBERS_DIALOG);
        }
    });

    mEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(android.text.Editable s) {
            MXLatestChatMessageCache latestChatMessageCache = RoomActivity.this.mLatestChatMessageCache;

            String textInPlace = latestChatMessageCache.getLatestText(RoomActivity.this, mRoom.getRoomId());

            // check if there is really an update
            // avoid useless updates (initializations..)
            if (!mIgnoreTextUpdate && !textInPlace.equals(mEditText.getText().toString())) {
                latestChatMessageCache.updateLatestMessage(RoomActivity.this, mRoom.getRoomId(),
                        mEditText.getText().toString());
                handleTypingNotification(mEditText.getText().length() != 0);
            }

            manageSendMoreButtons();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    mSession = getSession(intent);

    if (mSession == null) {
        Log.e(LOG_TAG, "No MXSession.");
        finish();
        return;
    }

    mMyUserId = mSession.getCredentials().userId;

    CommonActivityUtils.resumeEventStream(this);

    mRoom = mSession.getDataHandler().getRoom(roomId);

    FragmentManager fm = getSupportFragmentManager();
    mConsoleMessageListFragment = (ConsoleMessageListFragment) fm
            .findFragmentByTag(TAG_FRAGMENT_MATRIX_MESSAGE_LIST);

    if (mConsoleMessageListFragment == null) {
        // this fragment displays messages and handles all message logic
        mConsoleMessageListFragment = ConsoleMessageListFragment.newInstance(mMyUserId, mRoom.getRoomId(),
                org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment);
        fm.beginTransaction().add(R.id.anchor_fragment_messages, mConsoleMessageListFragment,
                TAG_FRAGMENT_MATRIX_MESSAGE_LIST).commit();
    }

    // set general room information
    setTitle(mRoom.getName(mMyUserId));
    setTopic(mRoom.getTopic());

    // listen for room name or topic changes
    mRoom.addEventListener(mEventListener);

    // The error listener needs the current activity
    mSession.setFailureCallback(new ErrorListener(this));

    mImagePreviewLayout = findViewById(R.id.room_image_preview_layout);
    mImagePreviewView = (ImageView) findViewById(R.id.room_image_preview);
    mImagePreviewButton = (ImageButton) findViewById(R.id.room_image_preview_cancel_button);

    // the user cancels the image selection
    mImagePreviewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPendingThumbnailUrl = null;
            mPendingMediaUrl = null;
            mPendingMimeType = null;
            mPendingFilename = null;
            manageSendMoreButtons();
        }
    });

    mLatestChatMessageCache = Matrix.getInstance(this).getDefaultLatestChatMessageCache();
    mMediasCache = Matrix.getInstance(this).getMediasCache();

    // some medias must be sent while opening the chat
    if (intent.hasExtra(HomeActivity.EXTRA_ROOM_INTENT)) {
        final Intent mediaIntent = intent.getParcelableExtra(HomeActivity.EXTRA_ROOM_INTENT);

        // sanity check
        if (null != mediaIntent) {
            mEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendMediasIntent(mediaIntent);
                }
            }, 1000);
        }
    }
}