Example usage for android.app Notification Notification

List of usage examples for android.app Notification Notification

Introduction

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

Prototype

@Deprecated
public Notification(int icon, CharSequence tickerText, long when) 

Source Link

Document

Constructs a Notification object with the information needed to have a status bar icon without the standard expanded view.

Usage

From source file:com.shafiq.myfeedle.core.MyfeedleService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else//  w  w w  .j  a  v a2  s  .  c  om
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(MyfeedleService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(MyfeedleService.this),
                                        values, Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(MyfeedleService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Myfeedle.default_message_bg_color;
                                int profile_bg_color = Myfeedle.default_message_bg_color;
                                int friend_bg_color = Myfeedle.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Myfeedle.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(MyfeedleService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(MyfeedleService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(MyfeedleService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(MyfeedleService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(MyfeedleService.this, widget,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(MyfeedleService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this),
                                        values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(MyfeedleService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(MyfeedleService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(MyfeedleService.this, 0,
                                            (Myfeedle.getPackageIntent(MyfeedleService.this,
                                                    MyfeedleNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}

From source file:saphion.services.ForegroundService.java

@SuppressWarnings("deprecation")
void handleCommand() {

    mPref = getSharedPreferences(PREF_NAME, MODE_MULTI_PROCESS);

    // if (ACTION_FOREGROUND.equals(intent.getAction())) {
    // In this sample, we'll use the same text for the ticker and the
    // expanded notification
    // CharSequence text = getText(R.string.foreground_service_started);

    // Set the icon, scrolling text and timestamp
    try {//ww w.  j a  va2  s  .  c o  m
        handleTrigger(level);
    } catch (Exception ex) {
        Log.d(ex.toString());
    }

    RemoteViews rvNoti = new RemoteViews(getPackageName(), R.layout.smallnoti);

    NotificationCompat.Builder builder;/*
                                       * = new NotificationCompat.Builder(
                                       * getBaseContext
                                       * ()).setContent(rvNoti);
                                       * builder.build();
                                       */

    Notification notification = new Notification(getId(level), null, 0);

    // The PendingIntent to launch our activity if the user selects this
    // notification
    PendingIntent contentIntent = null;
    Intent localIntent;
    switch (mPref.getInt(PreferenceHelper.NOTI_ONCLICK, 2)) {
    case 0:
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TabNavigation.class), 0);
        break;
    case 1:
        localIntent = new Intent();
        localIntent.setFlags(346030080);
        localIntent.setAction("android.intent.action.POWER_USAGE_SUMMARY");
        contentIntent = PendingIntent.getActivity(this, 0, localIntent, 0);
        break;
    case 2:
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Controller.class), 0);
        break;
    case 3:
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ToggleDialog.class), 0);
        break;
    }
    String prevTime = mPref.getString(PreferenceHelper.PREV_BAT_TIME, TimeFuncs.getCurrentTimeStamp());

    long diff = TimeFuncs.newDiff(TimeFuncs.GetItemDate(prevTime),
            TimeFuncs.GetItemDate(TimeFuncs.getCurrentTimeStamp()));

    Log.d("New diff " + diff);
    // TODO

    Log.d("Previous Date: " + TimeFuncs.GetItemDate(prevTime));
    Log.d("Current Date: " + TimeFuncs.GetItemDate(TimeFuncs.getCurrentTimeStamp()));
    // Log.d( "Previous Timestamp " + level + "");
    // Log.d( "Current Timestamp " + level + "");

    String subtext;

    Log.d("Current Level " + level + "");
    Log.d("Previous Level " + mPref.getInt(PreferenceHelper.PREV_BAT_LEVEL, level) + "");
    if (level < mPref.getInt(PreferenceHelper.PREV_BAT_LEVEL, level)) {

        diff = (long) (mPref.getLong(PreferenceHelper.BAT_DISCHARGE, diff));

        reqTime = diff * level;
        subtext = "Empty in " + TimeFuncs.convtohournminnday(reqTime);

        // mPref
        // .edit().putLong(PreferenceHelper.BAT_DISCHARGE, diff)
        // .commit();
        Log.d("Discharging with " + diff);

    } else {
        if (level > mPref.getInt(PreferenceHelper.PREV_BAT_LEVEL, level)) {
            if (level != 100
                    && TimeFuncs.convtohournminnday(diff * (100 - level)).equalsIgnoreCase("0 Minute(s)")) {
                reqTime = (long) (81 * (100 - level));
                subtext = "Full Charge in " + TimeFuncs.convtohournminnday(reqTime);
            } else {
                reqTime = diff * (100 - level);
                subtext = "Full Charge in " + TimeFuncs.convtohournminnday(reqTime);
                mPref.edit().putLong(PreferenceHelper.BAT_CHARGE, diff).commit();
            }

            Log.d("Charging with " + diff);

        } else {

            if (isconnected) {
                reqTime = (long) (mPref.getLong(PreferenceHelper.BAT_CHARGE, 81) * (100 - level));
                subtext = "Full Charge in " + TimeFuncs.convtohournminnday(reqTime);
                Log.d("Estimating Charging");
                // mPref
                // .edit().putLong("batcharge", diff).commit();
                Log.d("EST Charging with " + diff);

            } else {
                reqTime = (long) (mPref.getLong(PreferenceHelper.BAT_DISCHARGE, 792) * (level));
                subtext = "Empty in " + TimeFuncs.convtohournminnday(reqTime);
                Log.d("Estimating Discharging with: "
                        + (long) (mPref.getLong(PreferenceHelper.BAT_DISCHARGE, 792)));
            }
        }
    }

    if (level == 100 && isconnected) {
        subtext = "Fully Charged";
        reqTime = 0;
    }

    String mainText = mPref.getString(PreferenceHelper.LAST_CHARGED, TimeFuncs.getCurrentTimeStamp());

    if (isconnected) {
        if (mPref.getBoolean("plugged?", true))
            mPref.edit().putString(PreferenceHelper.LAST_CHARGED, TimeFuncs.getCurrentTimeStamp()).commit();
        String time = TimeFuncs.convtohournminnday(TimeFuncs.newDiff(TimeFuncs.GetItemDate(mainText),
                TimeFuncs.GetItemDate(TimeFuncs.getCurrentTimeStamp())));
        if (!time.equals("0 Minute(s)"))
            mainText = "Plugged " + time + " ago";
        else
            mainText = "Plugged " + "right now";
        mPref.edit().putBoolean("plugged?", false).commit();

    } else {
        if (!mPref.getBoolean("plugged?", true)) {
            mPref.edit().putBoolean("plugged?", true).commit();
            mPref.edit().putString(PreferenceHelper.LAST_CHARGED, TimeFuncs.getCurrentTimeStamp()).commit();
        }

        mainText = mPref.getString(PreferenceHelper.LAST_CHARGED, TimeFuncs.getCurrentTimeStamp());

        String time = TimeFuncs.convtohournminnday(TimeFuncs.newDiff(TimeFuncs.GetItemDate(mainText),
                TimeFuncs.GetItemDate(TimeFuncs.getCurrentTimeStamp())));

        if (!time.equals("0 Minute(s)"))
            mainText = "Unplugged " + time + " ago";
        else
            mainText = "Unplugged " + "right now";
    }

    String tempsubtext = subtext;
    subtext = setNotText(subtext, mainText, mPref.getInt(PreferenceHelper.NOTI_SUBTEXT, 3));
    mainText = setNotText(tempsubtext, mainText, mPref.getInt(PreferenceHelper.NOTI_MAINTEXT, 6));

    // Set the info for the views that show in the notification panel
    int srcId = getId(level);
    builder = new NotificationCompat.Builder(this).setSmallIcon(srcId).setAutoCancel(false).setOngoing(true)
            .setContentTitle(mainText).setContentText(subtext).setTicker(null).setWhen(0);
    // modification

    rvNoti.setImageViewResource(R.id.notification_icon, srcId);
    rvNoti.setTextViewText(R.id.tvNotiPrevmainText, mainText);
    rvNoti.setTextViewText(R.id.tvNotiPrevsubText, subtext);

    rvLargeNoti = new RemoteViews(getPackageName(), R.layout.largenoti);

    /*if (Build.VERSION.SDK_INT != 20)*/
    builder.setContent(rvNoti);
    // Intent notificationIntent = new Intent(this,
    // ForegroundService.class);
    // contentIntent = PendingIntent.getActivity(this, 0,
    // notificationIntent,
    // PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    switch (mPref.getInt(PreferenceHelper.NOTI_PRIORITY, 2)) {
    case 0:
        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
        break;
    case 1:
        builder.setPriority(NotificationCompat.PRIORITY_MIN);
        break;
    case 2:
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        break;
    case 3:
        builder.setPriority(NotificationCompat.PRIORITY_LOW);
        break;
    case 4:
        builder.setPriority(NotificationCompat.PRIORITY_MAX);
        break;
    }

    // builder.
    notification = builder.build();
    /*if (Build.VERSION.SDK_INT != 20)*/
    notification.contentView = rvNoti;

    /*if (Build.VERSION.SDK_INT == 20) {
            
               
        * builder = new
        * Notification.Builder(this).setContentTitle(mainText)
        * .setContentText(subtext).setTicker(null).setWhen(0)
        * .setOngoing(true).setSmallIcon(srcId)
        * .setContentIntent(pendingIntent).addAction(call)
        * .addAction(cancel).setAutoCancel(false);
                
            
       setKitkatActions(builder);
            
       notification = builder.build();
            
    } else*/ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        rvLargeNoti.setImageViewResource(R.id.notification_icon_large, srcId);

        if (mPref.getBoolean(PreferenceHelper.SHOW_CHART, true)) {

            vals = new ArrayList<Double>();
            dates = new ArrayList<Double>();

            vals = SerialPreference.retPrefs(getBaseContext(), PreferenceHelper.BAT_VALS);
            dates = SerialPreference.retPrefs(getBaseContext(), PreferenceHelper.BAT_TIME);

            GraphicalView mChartView = ChartFactory.getTimeChartView(getBaseContext(), getDateDataset(),
                    getRenderer(), "EEE, h:mm a");
            Bitmap outBitmap = Bitmap.createScaledBitmap(loadBitmapFromView(mChartView),
                    getResources().getDisplayMetrics().widthPixels,
                    Functions.ReturnHeight(140, getBaseContext()), true);

            rvLargeNoti.setImageViewBitmap(R.id.ivchart_large, outBitmap);
            rvLargeNoti.setViewVisibility(R.id.ivchart_large, View.VISIBLE);
        } else {
            rvLargeNoti.setViewVisibility(R.id.ivchart_large, View.GONE);
        }
        rvLargeNoti.setTextViewText(R.id.tvNotiPrevmainText_large, mainText);
        rvLargeNoti.setTextViewText(R.id.tvNotiPrevsubText_large, subtext);
        setResourceImages(rvLargeNoti);
        setIntents(rvLargeNoti);
        notification.bigContentView = rvLargeNoti;

    }

    if (mPref.getBoolean(PreferenceHelper.NOTIFICATION_ENABLE, true)) {
        /*
         * startForegroundCompat(R.string.foreground_service_started,
         * notification);
         */
        startForeground(notiID, notification);

    } else {
        notification.icon = R.drawable.abc_ab_bottom_transparent_dark_holo;
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
                notification.priority = Notification.PRIORITY_MIN;
        } catch (Exception ex) {
        }
        startForeground(notiID, notification);
        startService(new Intent(ForegroundService.this, FakeService.class));
    }

    /*
     * if(DISPLAY != null){ if(DISPLAY){ startForeground(notiID,
     * notification); Log.Toast(getBaseContext(), "displaying notification",
     * Toast.LENGTH_LONG); }else{ Log.Toast(getBaseContext(),
     * "not gonna display", Toast.LENGTH_LONG);
     * //startForegroundCompat(R.string.foreground_service_started, null);
     * notification.icon = R.drawable.abc_ab_bottom_transparent_dark_holo;
     * notification.priority = Notification.PRIORITY_MIN;
     * startForeground(notiID, notification); startService(new
     * Intent(ForegroundService.this, FakeService.class)); } }
     */

    if (level != mPref.getInt(PreferenceHelper.PREV_BAT_LEVEL, level))
        mPref.edit().putString(PreferenceHelper.PREV_BAT_TIME, TimeFuncs.getCurrentTimeStamp()).commit();
    mPref.edit().putInt(PreferenceHelper.PREV_BAT_LEVEL, level).commit();

}

From source file:com.f8full.casserolesencours.CasserolesEnCoursActivity.java

/**
 * On service click./*w  ww.  j  a v a  2s  .  co  m*/
 *
 * @param view the view
 */
public void onServiceClick(View view) {
    boolean isChecked = ((ToggleButton) view).isChecked();
    if (isChecked) {
        //turn on
        mAlohar.startServices();
        //StatusView.setText("Service is running!");
        ((TextView) findViewById(R.id.geolocationServiceStatus))
                .setText(getString(R.string.geolocationStatusOn));
        ((TextView) findViewById(R.id.geolocationServiceStatus))
                .setTextColor(getResources().getColor(R.color.text_red));
        ((TextView) findViewById(R.id.distanceFilterNA)).setVisibility(View.INVISIBLE);
        findViewById(R.id.FrequencyGroupLayout).setVisibility(View.VISIBLE);
        mDistanceFilterSpinner.setEnabled(true);

        //String freq = ((RadioButton)findViewById( ((RadioGroup)findViewById(R.id.pollFrequencyRadioGroup)).getCheckedRadioButtonId() )).getText().toString();
        String text = getString(R.string.geolocationStatusOnNotification);//String.format(getString(R.string.geolocationOnNotification), freq);
        int icon = R.drawable.ic_launcher;
        CharSequence tickerText = text;

        long when = System.currentTimeMillis();

        mNotification = new Notification(icon, tickerText, when);
        mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        CharSequence contentText = getString(R.string.geolocationOnNotificationNoFreq);
        CharSequence contentTitle = getString(R.string.app_name);
        Intent notificationIntent = new Intent(this, CasserolesEnCoursActivity.class);
        mNotification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mNotification.setLatestEventInfo(this, contentTitle, contentText, mNotification.contentIntent);
        mNotificationManager.notify(R.layout.main, mNotification);

    } else {
        //turn off
        mAlohar.stopServices();
        ((TextView) findViewById(R.id.geolocationServiceStatus))
                .setText(getString(R.string.geolocationStatusOff));
        ((TextView) findViewById(R.id.geolocationServiceStatus))
                .setTextColor(getResources().getColor(R.color.text_green));
        ((TextView) findViewById(R.id.distanceFilterNA)).setVisibility(View.VISIBLE);
        findViewById(R.id.FrequencyGroupLayout).setVisibility(View.INVISIBLE);
        mDistanceFilterSpinner.setSelection(0);
        mDistanceFilterSpinner.setEnabled(false);

        //((RadioGroup) findViewById(R.id.pollFrequencyRadioGroup)).check(-1);
        cancelActiveTasks();
        mLocationPollThreadExecutor.purge();

        //That is a hack, some code path must be missed, I'm tracking a thread leak bug when app is in background for a long time
        mLocationPollThreadExecutor.shutdown();
        mLocationPollThreadExecutor = new ScheduledThreadPoolExecutor(20);

        mIsStationary = true;
        mNotificationManager.cancel(R.layout.main);
    }
}

From source file:github.daneren2005.dsub.util.Util.java

public static void showPlayingNotification(final Context context, final DownloadServiceImpl downloadService,
        Handler handler, MusicDirectory.Entry song) {
    // Set the icon, scrolling text and timestamp
    final Notification notification = new Notification(R.drawable.stat_notify_playing, song.getTitle(),
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    boolean playing = downloadService.getPlayerState() == PlayerState.STARTED;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        RemoteViews expandedContentView = new RemoteViews(context.getPackageName(),
                R.layout.notification_expanded);
        setupViews(expandedContentView, context, song, playing);
        notification.bigContentView = expandedContentView;
    }/*from   w  w w .jav  a2 s .  c  o  m*/

    RemoteViews smallContentView = new RemoteViews(context.getPackageName(), R.layout.notification);
    setupViews(smallContentView, context, song, playing);
    notification.contentView = smallContentView;

    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.putExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD, true);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    handler.post(new Runnable() {
        @Override
        public void run() {
            downloadService.startForeground(Constants.NOTIFICATION_ID_PLAYING, notification);
        }
    });

    // Update widget
    DSubWidgetProvider.notifyInstances(context, downloadService, true);
}

From source file:de.ub0r.android.websms.connector.common.Utils.java

/**
 * Show update notification./*from w w w  .  j a v a2s  .co  m*/
 * 
 * @param context
 *            {@link Context}
 * @param pkg
 *            package
 */
public static void showUpdateNotification(final Context context, final String pkg) {
    Notification n = new Notification(android.R.drawable.stat_sys_warning,
            context.getString(R.string.update_title), 0);
    n.flags = Notification.FLAG_AUTO_CANCEL;
    PendingIntent pi = PendingIntent.getActivity(context, 0,
            new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + pkg)),
            PendingIntent.FLAG_UPDATE_CURRENT);
    n.setLatestEventInfo(context, context.getString(R.string.update_title),
            context.getString(R.string.update_message), pi);

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(0, n);
}

From source file:keyboard.ecloga.com.eclogakeyboard.EclogaKeyboard.java

@Override
public void onKey(int primaryCode, int[] keyCodes) {
    final InputConnection ic = getCurrentInputConnection();

    playClick();//from  w  ww.  jav  a  2 s .c  o  m
    printChar = true;

    if (primaryCode != 126 && primaryCode != -5 && primaryCode != -1
            && primaryCode != EmojiKeyboardView.KEYCODE_EMOJI_1
            && primaryCode != EmojiKeyboardView.KEYCODE_EMOJI_2
            && primaryCode != EmojiKeyboardView.KEYCODE_EMOJI_3
            && primaryCode != EmojiKeyboardView.KEYCODE_EMOJI_4
            && primaryCode != EmojiKeyboardView.KEYCODE_EMOJI_5) {

        keyPressCounter++;

        if (keyPressCounter > 100 && keyPressCounter <= 1000 && keypresscounter1.equals("false")) {
            NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notify = new Notification(R.drawable.notify, "Ecloga Keyboard",
                    System.currentTimeMillis());
            PendingIntent pending = PendingIntent.getActivity(this, 0, new Intent(this, Home.class), 0);

            notify.setLatestEventInfo(getApplicationContext(), "Warming up!", "Type more than 100 characters",
                    pending);
            notif.notify(0, notify);

            Preferences.setDefaults("keypresscounter1", "true", getApplicationContext());
        } else if (keyPressCounter > 10000 && keyPressCounter <= 10000 && keypresscounter2.equals("false")) {
            NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notify = new Notification(R.drawable.notify, "Ecloga Keyboard",
                    System.currentTimeMillis());
            PendingIntent pending = PendingIntent.getActivity(this, 0, new Intent(this, Home.class), 0);

            notify.setLatestEventInfo(getApplicationContext(), "Keep it up!", "Type more than 1000 characters",
                    pending);
            notif.notify(0, notify);

            Preferences.setDefaults("keypresscounter2", "true", getApplicationContext());
        } else if (keyPressCounter > 10000 && keypresscounter3.equals("false")) {
            NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notify = new Notification(R.drawable.notify, "Ecloga Keyboard",
                    System.currentTimeMillis());
            PendingIntent pending = PendingIntent.getActivity(this, 0, new Intent(this, Home.class), 0);

            notify.setLatestEventInfo(getApplicationContext(), "Typing master!",
                    "Type more than 10000 characters", pending);
            notif.notify(0, notify);

            Preferences.setDefaults("keypresscounter3", "true", getApplicationContext());
        }

        Preferences.setDefaults("keypresses", String.valueOf(keyPressCounter), getApplicationContext());
    }

    switch (primaryCode) {
    case 58:
        ic.commitText(":", 1);

        if (autoSpacing) {
            ic.commitText(" ", 1);
        }
        break;
    case 59:
        ic.commitText(";", 1);

        if (autoSpacing) {
            ic.commitText(" ", 1);
        }
        break;
    case 33:
        ic.commitText("!", 1);

        if (autoSpacing) {
            ic.commitText(" ", 1);
        }

        if (autoCapitalize) {
            caps = true;
            keyboard.setShifted(caps);
            kv.invalidateAllKeys();
            printChar = false;
        }
        break;
    case 63:
        ic.commitText("?", 1);

        if (autoSpacing) {
            ic.commitText(" ", 1);
        }

        if (autoCapitalize) {
            caps = true;
            keyboard.setShifted(caps);
            kv.invalidateAllKeys();
            printChar = false;
        }
        break;
    case -5:
        if (lang.equals("seclang")) {
            if (orient.equals("portrait")) {
                keyboard = prilang;
            } else if (orient.equals("landscape")) {
                keyboard = prilang_landscape;
            }
            kv.setKeyboard(keyboard);
            kv.invalidateAllKeys();
            lang = "prilang";
        } else if (lang.equals("prilang")) {
            if (orient.equals("portrait")) {
                keyboard = seclang;
            } else if (orient.equals("landscape")) {
                keyboard = seclang_landscape;
            }
            kv.setKeyboard(keyboard);
            kv.invalidateAllKeys();
            lang = "seclang";
        }
        break;
    case 32:
        ic.commitText(" ", 1);

        if (autoCapitalize) {
            if (String.valueOf(ic.getTextBeforeCursor(2, 0)).equals(". ")) {
                caps = true;
                keyboard.setShifted(caps);
                kv.invalidateAllKeys();
                printChar = false;
            }
        }
        break;
    case 126:
        ic.deleteSurroundingText(1, 0);

        if (autoCapitalize) {
            if (String.valueOf(ic.getTextBeforeCursor(1, 0)).equals(".")
                    || String.valueOf(ic.getTextBeforeCursor(2, 0)).equals(". ")
                    || String.valueOf(ic.getTextBeforeCursor(2, 0)).equals("")) {
                caps = true;
                keyboard.setShifted(caps);
                kv.invalidateAllKeys();
                printChar = false;
            }
        }
        break;
    case 44:
        ic.commitText(",", 1);

        if (autoSpacing) {
            ic.commitText(" ", 1);
        }
        break;
    case 46:
        ic.commitText(".", 1);

        if (autoSpacing) {
            ic.commitText(" ", 1);
        }

        if (autoCapitalize) {
            caps = true;
            keyboard.setShifted(caps);
            kv.invalidateAllKeys();
            printChar = false;
        }
        break;
    case -1:
        ic.performEditorAction(EditorInfo.IME_ACTION_GO);
        break;
    case EmojiKeyboardView.KEYCODE_EMOJI_1:
        keyboard = new Keyboard(this, R.xml.emoji_a1);
        kv.setKeyboard(keyboard);
        kv.invalidateAllKeys();
        emoji = 1;
        eScreen = 1;
        break;
    case EmojiKeyboardView.KEYCODE_EMOJI_2:
        keyboard = new Keyboard(this, R.xml.emoji_b1);
        kv.setKeyboard(keyboard);
        kv.invalidateAllKeys();
        emoji = 2;
        eScreen = 1;
        break;
    case EmojiKeyboardView.KEYCODE_EMOJI_3:
        keyboard = new Keyboard(this, R.xml.emoji_c1);
        kv.setKeyboard(keyboard);
        kv.invalidateAllKeys();
        emoji = 3;
        eScreen = 1;
        break;
    case EmojiKeyboardView.KEYCODE_EMOJI_4:
        keyboard = new Keyboard(this, R.xml.emoji_d1);
        kv.setKeyboard(keyboard);
        kv.invalidateAllKeys();
        emoji = 4;
        eScreen = 1;
        break;
    case EmojiKeyboardView.KEYCODE_EMOJI_5:
        keyboard = new Keyboard(this, R.xml.emoji_e1);
        kv.setKeyboard(keyboard);
        kv.invalidateAllKeys();
        emoji = 5;
        eScreen = 1;
        break;
    default:
        char code = (char) primaryCode;

        if (allCaps) {
            if (Character.isLetter(code) && capsLock) {
                code = Character.toLowerCase(code);
            } else if (Character.isLetter(code) && !capsLock) {
                code = Character.toUpperCase(code);
            }
        } else {
            if (Character.isLetter(code) && caps) {
                code = Character.toUpperCase(code);
            }
        }

        String character = String.valueOf(code);
        ic.commitText(character, 1);
    }

    if (printedDifferent) {
        ic.deleteSurroundingText(1, 0);
    }

    if (printedDot) {
        ic.deleteSurroundingText(1, 0);

        if (autoCapitalize) {
            caps = true;
            keyboard.setShifted(caps);
            kv.invalidateAllKeys();
            printChar = false;
        }
    }

    if (doubleUp == 2) {
        capsChange();
    } else {
        changeCaps();
    }
}

From source file:de.tudresden.inf.rn.mobilis.mxa.XMPPRemoteService.java

/**
 * @author Tobias Rho// w  w  w.j a  v  a  2  s  .  com
 */
private void showConnectionNotification() {
    if (RUN_IN_FOREGROUND) {
        Notification note = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.sb_txt_title))
                .setContentText(getString(R.string.sb_txt_text)).setSmallIcon(R.drawable.stat_notify_chat)
                .build();

        Intent i = new Intent(this, MainActivity.class);

        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

        note.setLatestEventInfo(this, getString(R.string.sb_txt_title), getString(R.string.sb_txt_text), pi);
        note.flags |= Notification.FLAG_NO_CLEAR;

        startForeground(NOTIFICATION_ID, note);
    } else {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Notification status = new Notification(R.drawable.stat_notify_chat, getString(R.string.sb_txt_text),
                System.currentTimeMillis());
        status.setLatestEventInfo(XMPPRemoteService.this, getString(R.string.sb_txt_title),
                getString(R.string.sb_txt_text), PendingIntent.getActivity(XMPPRemoteService.this, 0,
                        new Intent(ConstMXA.INTENT_SERVICEMONITOR), 0));
        status.flags |= Notification.FLAG_ONGOING_EVENT;
        status.icon = R.drawable.stat_notify_chat;
        nm.notify(XMPPSERVICE_STATUS, status);
    }
}

From source file:com.xorcode.andtweet.AndTweetService.java

/**
 * Notify user of the commands Queue size
 * /*from w w w  .j  a  va  2 s . c  o  m*/
 * @return total size of Queues
 */
private int notifyOfQueue(boolean clearNotification) {
    int count = mRetryQueue.size() + mCommands.size();
    NotificationManager nM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (count == 0 || clearNotification) {
        // Clear notification
        nM.cancel(CommandEnum.NOTIFY_QUEUE.ordinal());
    } else if (mNotificationsEnabled) {
        if (mRetryQueue.size() > 0) {
            MyLog.d(TAG, mRetryQueue.size() + " commands in Retry Queue.");
        }
        if (mCommands.size() > 0) {
            MyLog.d(TAG, mCommands.size() + " commands in Main Queue.");
        }

        // Set up the notification to display to the user
        Notification notification = new Notification(R.drawable.notification_icon,
                (String) getText(R.string.notification_title), System.currentTimeMillis());

        int messageTitle;
        String aMessage = "";

        aMessage = I18n.formatQuantityMessage(getApplicationContext(), R.string.notification_queue_format,
                count, R.array.notification_queue_patterns, R.array.notification_queue_formats);
        messageTitle = R.string.notification_title_queue;

        // Set up the scrolling message of the notification
        notification.tickerText = aMessage;

        /**
         * Set the latest event information and send the notification
         * Actually don't start any intent
         * 
         * @see http
         *      ://stackoverflow.com/questions/4232006/android-notification
         *      -pendingintent-problem
         */
        // PendingIntent pi = PendingIntent.getActivity(this, 0, null, 0);

        /**
         * Kick the commands queue by sending empty command
         */
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, new CommandData(CommandEnum.EMPTY).toIntent(),
                0);

        notification.setLatestEventInfo(this, getText(messageTitle), aMessage, pi);
        nM.notify(CommandEnum.NOTIFY_QUEUE.ordinal(), notification);
    }
    return count;
}

From source file:com.safecell.HomeScreenActivity.java

public void showNotification(String msg) {
    if (!new ConfigurePreferences(contextHomeScreenActivity).getTripStrated()) {
        Notification notification = new Notification(R.drawable.launch_icon, "Notify",
                System.currentTimeMillis());
        notification.setLatestEventInfo(HomeScreenActivity.this, "SafeCell", msg, PendingIntent.getActivity(
                HomeScreenActivity.this.getBaseContext(), 0, null, PendingIntent.FLAG_CANCEL_CURRENT));
        mManager.notify(APP_ID, notification);
    }/*w  ww  .jav a2s.c om*/

}