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:jieehd.villain.updater.checkInBackground.java

public void notifyUser() {
    final NotificationManager nm;
    nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence from = "Villain Updater";
    CharSequence message = "New Updates!";
    PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
    Notification notif = new Notification(R.drawable.updates, "New updates!", System.currentTimeMillis());
    notif.setLatestEventInfo(mContext, from, message, contentIntent);
    nm.notify(1, notif);//w w w.ja  v  a2  s . c  o  m
}

From source file:com.hhunj.hhudata.ForegroundService.java

void handleCommand(Intent intent) {
    if (intent == null) {
        return;//from  ww w  .  ja  va  2s.  c o  m
    }
    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
        Notification notification = new Notification(R.drawable.stat_sample, text, System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this
        // notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainTab.class), 0);//

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);

        startForegroundCompat(R.string.foreground_service_started, notification);

    }
    /*
     * else if (ACTION_BACKGROUND.equals(intent.getAction())) {
     * stopForegroundCompat(R.string.foreground_service_started); }
     */

}

From source file:org.crossconnect.bible.activity.main.ResourceFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    resourceService = ((MainActivity) getActivity()).getResourceService();

    // Prepare the loader.  Either re-connect with an existing one,
    // or start a new one.
    Bundle bundle = new Bundle();
    bundle.putParcelable("BibleText",
            Utils.loadBibleText(getActivity().getSharedPreferences("APP SETTINGS", Context.MODE_PRIVATE)));
    getLoaderManager().initLoader(0, bundle, this);

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new ResourceListAdapter(getActivity());
    setListAdapter(mAdapter);/*from ww  w .ja  v a  2  s. com*/

    dm = ((DownloadManager) getActivity().getSystemService("download"));

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                Query query = new Query();
                query.setFilterById(enqueue);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                        String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    }
                }

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

                int icon = R.drawable.icon_book_rss;
                CharSequence tickerText = "Resource Download Complete";
                long when = System.currentTimeMillis();

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

                CharSequence contentTitle = "Download Complete";
                CharSequence contentText = "Click to view downloaded resources";

                Intent notificationIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //uncomment when better
                //                    Intent notificationIntent = new Intent(getActivity(), MusicActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(getActivity(), 0, notificationIntent,
                        0);

                notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
                notification.flags |= Notification.FLAG_AUTO_CANCEL;

                int HELLO_ID = 1;

                mNotificationManager.notify(HELLO_ID, notification);
            }
        }
    };

    getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

}

From source file:com.gdpi.app.UpdateManager.java

/**
 * ??/* w  w  w . j ava2  s .com*/
 */
@SuppressWarnings({ "deprecation", "unused" })
private void showNotify() {
    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    int icon = R.drawable.icon;
    CharSequence tickerText = "";
    long when = System.currentTimeMillis();
    nitify = new Notification(icon, tickerText, when);

    // "?"?
    nitify.flags = Notification.FLAG_ONGOING_EVENT;
    RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.view_custom_progress);
    contentView.setTextViewText(R.id.tv_custom_progress_title, name);
    // 
    nitify.contentView = contentView;
    Intent intent = new Intent(mContext, MainFragment.class);
    PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
    // ?
    nitify.contentIntent = contentIntent;
    mNotificationManager.notify(notifyId, nitify);
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private void startUpdate(int flags) {
    setLastAttemptDate();//from  w w  w .jav a2  s  . c  o  m

    NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
    if (netInfo == null || !netInfo.isConnected()) {
        Log.i(LOGTAG, "not connected to the network");
        registerForUpdates(true);
        sendCheckUpdateResult(CheckUpdateResult.NOT_AVAILABLE);
        return;
    }

    registerForUpdates(false);

    UpdateInfo info = findUpdate(hasFlag(flags, UpdateServiceHelper.FLAG_REINSTALL));
    boolean haveUpdate = (info != null);

    if (!haveUpdate) {
        Log.i(LOGTAG, "no update available");
        sendCheckUpdateResult(CheckUpdateResult.NOT_AVAILABLE);
        return;
    }

    Log.i(LOGTAG, "update available, buildID = " + info.buildID);

    AutoDownloadPolicy policy = getAutoDownloadPolicy();

    // We only start a download automatically if one of following criteria are met:
    //
    // - We have a FORCE_DOWNLOAD flag passed in
    // - The preference is set to 'always'
    // - The preference is set to 'wifi' and we are using a non-metered network (i.e. the user
    //   is OK with large data transfers occurring)
    //
    boolean shouldStartDownload = hasFlag(flags, UpdateServiceHelper.FLAG_FORCE_DOWNLOAD)
            || policy == AutoDownloadPolicy.ENABLED || (policy == AutoDownloadPolicy.WIFI
                    && !ConnectivityManagerCompat.isActiveNetworkMetered(mConnectivityManager));

    if (!shouldStartDownload) {
        Log.i(LOGTAG, "not initiating automatic update download due to policy " + policy.toString());
        sendCheckUpdateResult(CheckUpdateResult.AVAILABLE);

        // We aren't autodownloading here, so prompt to start the update
        Notification notification = new Notification(R.drawable.ic_status_logo, null,
                System.currentTimeMillis());

        Intent notificationIntent = new Intent(UpdateServiceHelper.ACTION_DOWNLOAD_UPDATE);
        notificationIntent.setClass(this, UpdateService.class);

        PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        notification.setLatestEventInfo(this, getResources().getString(R.string.updater_start_title),
                getResources().getString(R.string.updater_start_select), contentIntent);

        mNotificationManager.notify(NOTIFICATION_ID, notification);

        return;
    }

    File pkg = downloadUpdatePackage(info, hasFlag(flags, UpdateServiceHelper.FLAG_OVERWRITE_EXISTING));
    if (pkg == null) {
        sendCheckUpdateResult(CheckUpdateResult.NOT_AVAILABLE);
        return;
    }

    Log.i(LOGTAG, "have update package at " + pkg);

    saveUpdateInfo(info, pkg);
    sendCheckUpdateResult(CheckUpdateResult.DOWNLOADED);

    if (mApplyImmediately) {
        applyUpdate(pkg);
    } else {
        // Prompt to apply the update
        Notification notification = new Notification(R.drawable.ic_status_logo, null,
                System.currentTimeMillis());

        Intent notificationIntent = new Intent(UpdateServiceHelper.ACTION_APPLY_UPDATE);
        notificationIntent.setClass(this, UpdateService.class);
        notificationIntent.putExtra(UpdateServiceHelper.EXTRA_PACKAGE_PATH_NAME, pkg.getAbsolutePath());

        PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        notification.setLatestEventInfo(this, getResources().getString(R.string.updater_apply_title),
                getResources().getString(R.string.updater_apply_select), contentIntent);

        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }
}

From source file:com.mobiperf.MeasurementScheduler.java

/**
 * Create notification that indicates the service is running.
 *///  w  w  w  . j  a v  a 2s .c  o m
private Notification createServiceRunningNotification() {
    // The intent to launch when the user clicks the expanded notification
    Intent intent = new Intent(this, SpeedometerApp.class);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // This constructor is deprecated in 3.x. But most phones still run 2.x systems
    Notification notice = new Notification(R.drawable.icon_statusbar,
            getString(R.string.notificationSchedulerStarted), System.currentTimeMillis());
    notice.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    // This is deprecated in 3.x. But most phones still run 2.x systems
    notice.setLatestEventInfo(this, getString(R.string.app_name),
            getString(R.string.notificationServiceRunning), pendIntent);
    return notice;
}

From source file:com.inloc.dr.StepService.java

/**
 * Show a notification while this service is running.
 *///from w  ww .  j  av a2s .c  o  m
private void showNotification() {
    CharSequence text = getText(R.string.app_name);
    Notification notification = new Notification(R.drawable.ic_notification, null, System.currentTimeMillis());
    notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    Intent pedometerIntent = new Intent();
    pedometerIntent.setComponent(new ComponentName(this, DeadReckoning.class));
    pedometerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, pedometerIntent, 0);
    notification.setLatestEventInfo(this, text, getText(R.string.notification_subtitle), contentIntent);

    mNM.notify(R.string.app_name, notification);
}

From source file:io.clh.lrt.androidservice.TraceListenerService.java

private void setNotification(String msg, boolean ongoing) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    int icon = R.drawable.ic_launcher;
    CharSequence notiText = msg;/*w  w w. ja va2  s. c  om*/
    long meow = System.currentTimeMillis();

    Notification notification = new Notification(icon, notiText, meow);

    Context context = getApplicationContext();
    CharSequence contentTitle = "LRT notification";
    CharSequence contentText = msg;
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

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

    int SERVER_DATA_RECEIVED = 1;
    if (ongoing) {
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        startForeground(1337, notification);
    } else {
        notificationManager.notify(SERVER_DATA_RECEIVED, notification);
    }
}

From source file:org.navitproject.navit.Navit.java

/** Called when the activity is first created. */
@Override/*  w w w  . ja va 2  s .  c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    else
        this.getActionBar().hide();

    dialogs = new NavitDialogs(this);

    NavitResources = getResources();

    // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
    Navit.startup_intent = this.getIntent();
    // hack! Remember time stamps, and only allow 4 secs. later in onResume to set target!
    Navit.startup_intent_timestamp = System.currentTimeMillis();
    Log.e("Navit", "**1**A " + startup_intent.getAction());
    Log.e("Navit", "**1**D " + startup_intent.getDataString());

    // init translated text
    NavitTextTranslations.init();

    // NOTIFICATION
    // Setup the status bar notification      
    // This notification is removed in the exit() function
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Grab a handle to the NotificationManager
    Notification NavitNotification = new Notification(R.drawable.ic_notify,
            getString(R.string.notification_ticker), System.currentTimeMillis()); // Create a new notification, with the text string to show when the notification first appears
    PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0);
    //      FIXME : needs a fix for sdk 23
    //      NavitNotification.setLatestEventInfo(getApplicationContext(), "Navit", getString(R.string.notification_event_default), appIntent);   // Set the text in the notification
    //      NavitNotification.flags|=Notification.FLAG_ONGOING_EVENT;   // Ensure that the notification appears in Ongoing
    //      nm.notify(R.string.app_name, NavitNotification);   // Set the notification

    // Status and navigation bar sizes
    // These are platform defaults and do not change with rotation, but we have to figure out which ones apply
    // (is the navigation bar visible? on the side or at the bottom?)
    Resources resources = getResources();
    int shid = resources.getIdentifier("status_bar_height", "dimen", "android");
    int adhid = resources.getIdentifier("action_bar_default_height", "dimen", "android");
    int nhid = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    int nhlid = resources.getIdentifier("navigation_bar_height_landscape", "dimen", "android");
    int nwid = resources.getIdentifier("navigation_bar_width", "dimen", "android");
    status_bar_height = (shid > 0) ? resources.getDimensionPixelSize(shid) : 0;
    action_bar_default_height = (adhid > 0) ? resources.getDimensionPixelSize(adhid) : 0;
    navigation_bar_height = (nhid > 0) ? resources.getDimensionPixelSize(nhid) : 0;
    navigation_bar_height_landscape = (nhlid > 0) ? resources.getDimensionPixelSize(nhlid) : 0;
    navigation_bar_width = (nwid > 0) ? resources.getDimensionPixelSize(nwid) : 0;
    Log.d(TAG, String.format(
            "status_bar_height=%d, action_bar_default_height=%d, navigation_bar_height=%d, navigation_bar_height_landscape=%d, navigation_bar_width=%d",
            status_bar_height, action_bar_default_height, navigation_bar_height,
            navigation_bar_height_landscape, navigation_bar_width));
    if ((ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            || (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
        Log.d(TAG, "ask for permission(s)");
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSIONS_REQUEST_ALL);
    }
    // get the local language -------------
    Locale locale = java.util.Locale.getDefault();
    String lang = locale.getLanguage();
    String langu = lang;
    String langc = lang;
    Log.e("Navit", "lang=" + lang);
    int pos = langu.indexOf('_');
    if (pos != -1) {
        langc = langu.substring(0, pos);
        NavitLanguage = langc + langu.substring(pos).toUpperCase(locale);
        Log.e("Navit", "substring lang " + NavitLanguage.substring(pos).toUpperCase(locale));
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = NavitLanguage.substring(pos).toUpperCase(locale);
    } else {
        String country = locale.getCountry();
        Log.e("Navit", "Country1 " + country);
        Log.e("Navit", "Country2 " + country.toUpperCase(locale));
        NavitLanguage = langc + "_" + country.toUpperCase(locale);
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = country.toUpperCase(locale);
    }
    Log.e("Navit", "Language " + lang);

    SharedPreferences prefs = getSharedPreferences(NAVIT_PREFS, MODE_PRIVATE);
    map_filename_path = prefs.getString("filenamePath",
            Environment.getExternalStorageDirectory().getPath() + "/navit/");

    // make sure the new path for the navitmap.bin file(s) exist!!
    File navit_maps_dir = new File(map_filename_path);
    navit_maps_dir.mkdirs();

    // make sure the share dir exists
    File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
    navit_data_share_dir.mkdirs();

    Display display_ = getWindowManager().getDefaultDisplay();
    int width_ = display_.getWidth();
    int height_ = display_.getHeight();
    metrics = new DisplayMetrics();
    display_.getMetrics(Navit.metrics);
    int densityDpi = (int) ((Navit.metrics.density * 160) - .5f);
    Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
    Log.e("Navit", "Navit -> dpi=" + densityDpi);
    Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
    Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);

    ActivityResults = new NavitActivityResult[16];
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen");

    if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo")) {
        Log.e("Navit", "Failed to extract language resource " + langc);
    }

    if (densityDpi <= 120) {
        my_display_density = "ldpi";
    } else if (densityDpi <= 160) {
        my_display_density = "mdpi";
    } else if (densityDpi < 240) {
        my_display_density = "hdpi";
    } else if (densityDpi < 320) {
        my_display_density = "xhdpi";
    } else if (densityDpi < 480) {
        my_display_density = "xxhdpi";
    } else if (densityDpi < 640) {
        my_display_density = "xxxhdpi";
    } else {
        Log.e("Navit", "found device of very high density (" + densityDpi + ")");
        Log.e("Navit", "using xxxhdpi values");
        my_display_density = "xxxhdpi";
    }

    if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml")) {
        Log.e("Navit", "Failed to extract navit.xml for " + my_display_density);
    }

    // --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4
    Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));
    NavitMain(this, NavitLanguage, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density,
            NAVIT_DATA_DIR + "/bin/navit", map_filename_path);

    showInfos();

    Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
}

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private void oldPushNotification(Context context, Intent intent) {
    PushReportUtility.log("oldPushNotification->isForground = " + EBrowserActivity.isForground);
    if (EBrowserActivity.isForground) {
        if (mContext != null) {
            intent.putExtra("ntype", F_TYPE_PUSH);
            ((EBrowserActivity) mContext).handleIntent(intent);
        }/*  w  w w.j  a v  a2s. co m*/
    } else {
        CharSequence tickerText = intent.getStringExtra("title"); // ????
        Resources res = context.getResources();
        int icon = res.getIdentifier("icon", "drawable", intent.getPackage());
        long when = System.currentTimeMillis(); // ?
        // ??Nofification

        String notifyTitle = null;
        String pushMessage = intent.getStringExtra("message");
        String value = intent.getStringExtra("data"); // ??json
        try {
            JSONObject bodyJson = new JSONObject(value);
            notifyTitle = bodyJson.getString("msgName");// ?
        } catch (Exception e) {
            PushReportUtility.oe("onReceive", e);
        }
        if (TextUtils.isEmpty(notifyTitle)) {
            notifyTitle = intent.getStringExtra("widgetName");// msgNamewidgetName?
        }
        if (TextUtils.isEmpty(notifyTitle)) {
            notifyTitle = "APPCAN";// widgetNameAPPCAN?
        }
        CharSequence contentTitle = notifyTitle; // ?
        Intent notificationIntent = new Intent(context, EBrowserActivity.class); // ??Activity
        notificationIntent.putExtra("data", value);
        notificationIntent.putExtra("message", pushMessage);
        notificationIntent.putExtra("ntype", F_TYPE_PUSH);
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
        Notification notification = new Notification(icon, tickerText, when);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        if (Build.VERSION.SDK_INT >= 16) {
            try {
                Field priorityField = Notification.class.getField("priority");
                priorityField.setAccessible(true);
                priorityField.set(notification, 1);
            } catch (Exception e) {
                PushReportUtility.oe("onReceive", e);
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(context, notificationNB, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(context, contentTitle, tickerText, contentIntent);
        // NotificationNotificationManager
        mNotificationManager.notify(notificationNB, notification);
        notificationNB++;
    }
}