Example usage for android.content Context NOTIFICATION_SERVICE

List of usage examples for android.content Context NOTIFICATION_SERVICE

Introduction

In this page you can find the example usage for android.content Context NOTIFICATION_SERVICE.

Prototype

String NOTIFICATION_SERVICE

To view the source code for android.content Context NOTIFICATION_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.NotificationManager for informing the user of background events.

Usage

From source file:com.orange.oidc.secproxy_service.Service.java

private void hideNotifIcon() {
    Logd(TAG, "hideNotifIcon");

    if (Context.NOTIFICATION_SERVICE != null) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(0);//from  w  w  w. j ava  2  s.  com
    }
}

From source file:biz.wiz.android.wallet.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    final Wallet wallet = application.getWallet();

    peerConnectivityListener = new PeerConnectivityListener();

    broadcastPeerState(0);/*from   www .j  a  v a  2  s.  com*/

    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        wallet.setLastBlockSeenHeight(-1); // magic value
        wallet.setLastBlockSeenHash(null);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        blockStore.getChainHead(); // detect corruptions as early as possible

        final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();

        if (!blockChainFileExists && earliestKeyCreationTime > 0) {
            try {
                final InputStream checkpointsInputStream = getAssets()
                        .open(Constants.Files.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter); // implicitly start PeerGroup

    application.getWallet().addEventListener(walletEventListener, Threading.SAME_THREAD);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:edu.mit.mobile.android.locast.sync.MediaSync.java

/**
 * Checks the local file system and checks to see if the given media resource has been
 * downloaded successfully already. If not, it will download it from the server and store it in
 * the filesystem. This uses the last-modified header and file length to determine if a media
 * resource is up to date.//from ww w .j a  v a  2 s . c  om
 *
 * This method blocks for the course of the download, but shows a progress notification.
 *
 * @param pubUri
 *            the http:// uri of the public resource
 * @param saveFile
 *            the file that the resource will be saved to
 * @param castMediaUri
 *            the content:// uri of the cast
 * @return true if anything has changed. False if this function has determined it doesn't need
 *         to do anything.
 * @throws SyncException
 */
public boolean downloadMediaFile(String pubUri, File saveFile, Uri castMediaUri) throws SyncException {
    final NetworkClient nc = NetworkClient.getInstance(this, Authenticator.getFirstAccount(this));
    try {
        boolean dirty = true;
        // String contentType = null;

        if (saveFile.exists()) {
            final HttpResponse headRes = nc.head(pubUri);
            final long serverLength = Long.valueOf(headRes.getFirstHeader("Content-Length").getValue());
            // XXX should really be checking the e-tag too, but this will be
            // fine for our application.
            final Header remoteLastModifiedHeader = headRes.getFirstHeader("last-modified");

            long remoteLastModified = 0;
            if (remoteLastModifiedHeader != null) {
                remoteLastModified = DateUtils.parseDate(remoteLastModifiedHeader.getValue()).getTime();
            }

            final HttpEntity entity = headRes.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            if (saveFile.length() == serverLength && saveFile.lastModified() >= remoteLastModified) {
                if (DEBUG) {
                    Log.i(TAG, "Local copy of cast " + saveFile
                            + " seems to be the same as the one on the server. Not re-downloading.");
                }

                dirty = false;
            }
            // fall through and re-download, as we have a different size
            // file locally.
        }
        if (dirty) {
            final Uri castUri = CastMedia.getCast(castMediaUri);
            String castTitle = Cast.getTitle(this, castUri);
            if (castTitle == null) {
                castTitle = "untitled";
            }

            final HttpResponse res = nc.get(pubUri);
            final HttpEntity ent = res.getEntity();
            final ProgressNotification notification = new ProgressNotification(this,
                    getString(R.string.sync_downloading_cast, castTitle), ProgressNotification.TYPE_DOWNLOAD,
                    PendingIntent.getActivity(this, 0,
                            new Intent(Intent.ACTION_VIEW, castUri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0),
                    false);

            final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            final NotificationProgressListener npl = new NotificationProgressListener(nm, notification,
                    ent.getContentLength(), 0);
            final InputStreamWatcher is = new InputStreamWatcher(ent.getContent(), npl);

            try {
                if (DEBUG) {
                    Log.d(TAG, "Downloading " + pubUri + " and saving it in " + saveFile.getAbsolutePath());
                }
                final FileOutputStream fos = new FileOutputStream(saveFile);
                StreamUtils.inputStreamToOutputStream(is, fos);
                fos.close();

                // set the file's last modified to match the remote.
                // We can check this later to see if everything is up to
                // date.
                final Header lastModified = res.getFirstHeader("last-modified");
                if (lastModified != null) {
                    saveFile.setLastModified(DateUtils.parseDate(lastModified.getValue()).getTime());
                }

                // contentType = ent.getContentType().getValue();

            } finally {
                npl.done();
                ent.consumeContent();
                is.close();
            }

            // XXX avoid this to prevent adding to local collection
            // final String filePath = saveFile.getAbsolutePath();

            // scanMediaItem(castMediaUri, filePath, contentType);
            return true;
        }
    } catch (final Exception e) {
        final SyncException se = new SyncException("Error downloading content item.");
        se.initCause(e);
        throw se;
    }
    return false;
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * connect to the notification manager and create a notification builder.
 * it also setup the cancellation Intent for get notified when our notification got cancelled.
 *///from   w ww  .j av a  2s  .  co  m
private void setupNotification() {
    // get notification manager
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // get notification builder
    mBuilder = new NotificationCompat.Builder(this);
    // create a broadcast receiver to get actions
    // performed on the notification by the user
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null)
                return;
            // user cancelled our notification
            if (action.equals(NOTIFICATION_CANCELLED)) {
                mRunning = false;
                stopSelf();
            }
        }
    };
    // register our receiver
    registerReceiver(mReceiver, new IntentFilter(NOTIFICATION_CANCELLED));
    // set common notification actions
    mBuilder.setDeleteIntent(
            PendingIntent.getBroadcast(this, CANCEL_CODE, new Intent(NOTIFICATION_CANCELLED), 0));
    mBuilder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

public void notifyWeather() {
    Context context = getContext();
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
    boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
            Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));

    if (displayNotifications) {

        String lastNotificationKey = context.getString(R.string.pref_last_notification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= getNotificationTimeGap()) {
            // Last sync was more than 1 day ago, let's send a notification with the weather.
            String locationQuery = WeatherUtil.getPreferredLocation(context);

            Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery,
                    System.currentTimeMillis());

            // we'll query our contentProvider, as always
            Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null,
                    null, null);//from  w  ww . ja  v  a  2  s  . co m

            if (cursor.moveToFirst()) {
                int weatherId = cursor.getInt(INDEX_WEATHER_ID);
                double high = cursor.getDouble(INDEX_MAX_TEMP);
                double low = cursor.getDouble(INDEX_MIN_TEMP);
                String desc = cursor.getString(INDEX_SHORT_DESC);

                int iconId = WeatherUtil.getIconResourceForWeatherCondition(weatherId);
                Resources resources = context.getResources();
                Bitmap largeIcon = BitmapFactory.decodeResource(resources,
                        WeatherUtil.getArtResourceForWeatherCondition(weatherId));
                String title = getTitle();

                // Define the text of the forecast.
                String contentText = String.format(context.getString(R.string.format_notification), desc,
                        WeatherUtil.formatTemperature(context, high),
                        WeatherUtil.formatTemperature(context, low));

                // NotificationCompatBuilder is a very convenient way to build backward-compatible
                // notifications.  Just throw in some data.
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext())
                        .setColor(resources.getColor(R.color.weather4u_light_blue)).setSmallIcon(iconId)
                        .setLargeIcon(largeIcon).setContentTitle(title).setContentText(contentText);
                mBuilder.setAutoCancel(true);

                // Make something interesting happen when the user clicks on the notification.
                // In this case, opening the app is sufficient.
                Intent resultIntent = new Intent(context, MainActivity.class);

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);

                NotificationManager mNotificationManager = (NotificationManager) getContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                // WEATHER_NOTIFICATION_ID allows you to update the notification later on.
                mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build());

                //refreshing last sync
                SharedPreferences.Editor editor = prefs.edit();
                editor.putLong(lastNotificationKey, System.currentTimeMillis());
                editor.commit();
            }
            cursor.close();
        }
    }
}

From source file:org.csploit.android.core.UpdateService.java

/**
 * connect to the notification manager and create a notification builder.
 * it also setup the cancellation Intent for get notified when our notification got cancelled.
 */// w  ww .  j a v a 2  s.  com
private void setupNotification() {
    // get notification manager
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // get notification builder
    mBuilder = new NotificationCompat.Builder(this);
    // create a broadcast receiver to get actions
    // performed on the notification by the user
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null)
                return;
            // user cancelled our notification
            if (action.equals(NOTIFICATION_CANCELLED)) {
                mRunning = false;
            }
        }
    };
    // register our receiver
    registerReceiver(mReceiver, new IntentFilter(NOTIFICATION_CANCELLED));
    // set common notification actions
    mBuilder.setDeleteIntent(
            PendingIntent.getBroadcast(this, CANCEL_CODE, new Intent(NOTIFICATION_CANCELLED), 0));
    mBuilder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
}

From source file:com.farmerbb.secondscreen.util.U.java

public static void runCommands(Context context, String[] commands) {
    if (getPrefMain(context).getBoolean("debug_mode", false)) {
        String dump = "";

        for (String command : commands) {
            if (!command.equals(""))
                dump = dump + context.getResources().getString(R.string.bullet) + " " + command + "\n";
        }/* ww  w . java  2s. c o  m*/

        Notification notification = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentTitle(context.getResources().getString(R.string.debug_mode_enabled))
                .setContentText(dump).setStyle(new NotificationCompat.BigTextStyle().bigText(dump)).build();

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(new Random().nextInt(), notification);

        // Some devices (Android TV) don't show notifications, so let's also print the commands
        // to the log just in case.
        System.out.println(dump);
    } else
        Shell.SU.run(commands);
}

From source file:net.ben.subsonic.androidapp.util.Util.java

public static void showPlayingNotification(final Context context, Handler handler, MusicDirectory.Entry song) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();

    // Set the icon, scrolling text and timestamp
    final Notification notification = new Notification(R.drawable.stat_notify_playing, title,
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, FragActivity.class),
            0);/*from  w  w  w  .ja  v a2 s.  co  m*/

    String text = song.getArtist();
    notification.setLatestEventInfo(context, title, text, contentIntent);

    // Send the notification.
    handler.post(new Runnable() {
        @Override
        public void run() {
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING, notification);
        }
    });

    // Update widget
    DownloadService service = DownloadServiceImpl.getInstance();
    if (service != null) {
        SubsonicAppWidgetProvider.getInstance().notifyChange(context, service, true);
    }
}

From source file:com.aware.Aware.java

/**
 * Starts a plugin. Expects the package name of the plugin.<br/>
 * It checks if the plugin does exist on the phone. If it doesn't, it will request the user to install it automatically.
 * @param context//from   ww w. java  2s  .c  o m
 * @param package_name
 */
public static void startPlugin(Context context, String package_name) {
    //Check if plugin is installed. If not, ask user to download it.
    Cursor is_installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null,
            Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null, null);
    if (is_installed != null && is_installed.moveToFirst()) {
        //We might just have it cached, but not installed
        if (isClassAvailable(context, package_name, "Plugin")) {
            //it's installed, start it!
            Intent plugin = new Intent();
            plugin.setClassName(package_name, package_name + ".Plugin");
            context.startService(plugin);
            if (Aware.DEBUG)
                Log.d(TAG, package_name + " started...");

            ContentValues rowData = new ContentValues();
            rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON);
            context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData,
                    Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null);
            is_installed.close();
            return;
        }
        is_installed.close();
    }

    HttpResponse response = new Https(awareContext)
            .dataGET("https://api.awareframework.com/index.php/plugins/get_plugin/" + package_name);
    if (response != null && response.getStatusLine().getStatusCode() == 200) {
        try {
            String data = EntityUtils.toString(response.getEntity());
            if (data.equals("[]"))
                return;

            JSONObject json_package = new JSONObject(data);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setSmallIcon(R.drawable.ic_stat_aware_plugin_dependency);
            mBuilder.setContentTitle("AWARE");
            mBuilder.setContentText("Plugin missing: " + json_package.getString("title") + ". Tap to install.");
            mBuilder.setDefaults(Notification.DEFAULT_ALL);
            mBuilder.setAutoCancel(true);

            Intent pluginIntent = new Intent(context, DownloadPluginService.class);
            pluginIntent.putExtra("package_name", package_name);
            pluginIntent.putExtra("is_update", false);

            PendingIntent clickIntent = PendingIntent.getService(context, 0, pluginIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(clickIntent);
            NotificationManager notManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notManager.notify(json_package.getInt("id"), mBuilder.build());

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushIntentService.java

protected void dismissNotification(String nid) {
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(MFPPush.PREFS_NAME,
            Context.MODE_PRIVATE);
    int countOfStoredMessages = sharedPreferences.getInt(MFPPush.PREFS_NOTIFICATION_COUNT, 0);

    if (countOfStoredMessages > 0) {
        for (int index = 1; index <= countOfStoredMessages; index++) {

            String key = MFPPush.PREFS_NOTIFICATION_MSG + index;
            try {
                String msg = sharedPreferences.getString(key, null);
                if (msg != null) {
                    JSONObject messageObject = new JSONObject(msg);
                    if (messageObject != null && !messageObject.isNull(NID)) {
                        String id = messageObject.getString(NID);
                        if (id != null && id.equals(nid)) {
                            MFPPushUtils.removeContentFromSharedPreferences(sharedPreferences, key);
                            MFPPushUtils.storeContentInSharedPreferences(sharedPreferences,
                                    MFPPush.PREFS_NOTIFICATION_COUNT, countOfStoredMessages - 1);
                            NotificationManager mNotificationManager = (NotificationManager) this
                                    .getSystemService(Context.NOTIFICATION_SERVICE);
                            mNotificationManager.cancel(messageObject.getInt(NOTIFICATIONID));
                        }/*from   w  ww.  ja v  a 2s .c  o m*/
                    }
                }
            } catch (JSONException e) {
                logger.error("MFPPushIntentService: dismissNotification() - Failed to dismiss notification.");
            }
        }
    }
}