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:alaindc.memenguage.RandomIntentService.java

private void sendNotification(long id_word) {
    String title = "Memenguage";
    String description = "Do you remember?";

    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), GuessActivity.class);
    notificationIntent.setAction(Constants.ACTION_GUESS_ACTIVITY);
    notificationIntent.putExtra(Constants.EXTRA_GUESS_IDWORD, id_word);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntentWithParentStack(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.

    builder.setSmallIcon(R.drawable.icon)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo)).setColor(Color.RED)
            .setContentTitle(title).setContentText(description).setDefaults(Notification.DEFAULT_ALL)
            .setContentIntent(notificationPendingIntent);

    try {/*from w w w.j  a  v  a  2s .c o m*/
        String urisound = PreferenceManager.getDefaultSharedPreferences(this).getString("sound_notifications",
                "");
        builder.setSound(Uri.parse(urisound));
    } catch (Exception e) {
        Log.d("RandomIntentService", "Uri sound notification empty or wrong");
    }

    try {
        Boolean vibrate = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("vibrate_notifications", false);
        if (vibrate)
            builder.setVibrate(new long[] { 1000, 1000 });
    } catch (Exception e) {
        Log.d("RandomIntentService", "Vibrate notification wrong");
    }

    builder.setDefaults(0);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(Constants.ID_NOTIFICATION_RANDOM_WORD, builder.build());
}

From source file:com.test.onesignal.GenerateNotificationRunner.java

@Before // Before each test
public void beforeEachTest() throws Exception {
    // Robolectric mocks System.currentTimeMillis() to 0, we need the current real time to match our SQL records.
    ShadowSystemClock.setCurrentTimeMillis(System.currentTimeMillis());

    blankActivityController = Robolectric.buildActivity(BlankActivity.class).create();
    blankActivity = blankActivityController.get();
    blankActivity.getApplicationInfo().name = "UnitTestApp";

    overrideNotificationId = -1;// ww  w .ja  v a2 s .  c o m

    TestHelpers.betweenTestsCleanup();

    NotificationManager notificationManager = (NotificationManager) blankActivity
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

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

@Override
protected void onResume() {
    super.onResume();
    // Lock the Tango configuration and reconnect to the service each time
    // the app/*from www.jav  a2 s  .com*/
    // is brought to the foreground.
    super.onResume();
    if (!mIsTangoServiceConnected) {
        startActivityForResult(Tango.getRequestPermissionIntent(Tango.PERMISSIONTYPE_MOTION_TRACKING),
                Tango.TANGO_INTENT_ACTIVITYCODE);
    }

    // Clear all notification
    NotificationManager mNotifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotifyMgr.cancelAll();
}

From source file:com.google.android.apps.chrometophone.C2DMReceiver.java

private void generateNotification(Context context, String msg, String title, Intent intent) {
    int icon = R.drawable.status_icon;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, title, when);
    notification.setLatestEventInfo(context, title, msg, PendingIntent.getActivity(context, 0, intent, 0));
    notification.defaults = Notification.DEFAULT_SOUND;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    SharedPreferences settings = Prefs.get(context);
    int notificatonID = settings.getInt("notificationID", 0); // allow multiple notifications

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(notificatonID, notification);

    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("notificationID", ++notificatonID % 32);
    editor.commit();//from   w  w  w  .  ja  v a2  s .c  om
}

From source file:com.nanostuffs.yurdriver.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from ww w  .  j  a v a 2  s .  co m
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MapActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(AndyConstants.NOTIFICATION_ID, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();

}

From source file:at.florian_lentsch.expirysync.NotifyChecker.java

private void createExpiryNotification(Context appContext, List<String> expiringProducts) {
    Resources res = appContext.getResources();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(res.getQuantityString(R.plurals.numberOfItemsToBeEaten, expiringProducts.size(),
                    expiringProducts.size()))
            .setContentText(StringUtils.join(expiringProducts, System.getProperty("line.separator")))
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI).setAutoCancel(true);
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(appContext, ProductListActivity.class);

    // set stack (for the back button to work correctly):
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(appContext);
    stackBuilder.addParentStack(ProductListActivity.class);
    stackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager = (NotificationManager) appContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // display the notification:
    notificationManager.notify(WASTE_NOTIFICATION, builder.build());
}

From source file:ca.spencerelliott.mercury.Changesets.java

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

    this.requestWindowFeature(Window.FEATURE_PROGRESS);
    this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.changesets);

    //Cancel any notifications previously setup
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(1);/*from w ww  .  ja va 2 s.  c  o  m*/

    //Create a new array list for the changesets
    changesets_list = new ArrayList<Map<String, ?>>();
    changesets_data = new ArrayList<Beans.ChangesetBean>();

    //Get the list view to store the changesets
    changesets_listview = (ListView) findViewById(R.id.changesets_list);

    TextView empty_text = (TextView) findViewById(R.id.changesets_empty_text);

    //Set the empty view
    changesets_listview.setEmptyView(empty_text);

    //Use a simple adapter to display the changesets based on the array list made earlier
    changesets_listview.setAdapter(new SimpleAdapter(this, changesets_list, R.layout.changeset_item,
            new String[] { COMMIT, FORMATTED_INFO },
            new int[] { R.id.changesets_commit, R.id.changesets_info }));

    //Set the on click listener
    changesets_listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
            Intent intent = new Intent(Changesets.this, ChangesetViewer.class);

            //Pass the changeset information to the changeset viewer
            Bundle params = new Bundle();
            params.putString("changeset_commit_text", changesets_data.get(position).getTitle());
            params.putString("changeset_changes", changesets_data.get(position).getContent());
            params.putLong("changeset_updated", changesets_data.get(position).getUpdated());
            params.putString("changeset_authors", changesets_data.get(position).getAuthor());
            params.putString("changeset_link", changesets_data.get(position).getLink());
            //params.putBoolean("is_https", is_https);

            intent.putExtras(params);

            startActivity(intent);
        }

    });

    //Register the list view for opening the context menu
    registerForContextMenu(changesets_listview);

    //Get the intent passed by the program
    if (getIntent() != null) {
        //Check to see if this is a search window
        if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
            //Change the title of the activity and the empty text of the list so it looks like a search window
            this.setTitle(R.string.search_results_label);
            empty_text.setText(R.string.search_results_empty);

            //Retrieve the query the user entered
            String query = getIntent().getStringExtra(SearchManager.QUERY);

            //Convert the query to lower case
            query = query.toLowerCase();

            //Retrieve the bundle data
            Bundle retrieved_data = getIntent().getBundleExtra(SearchManager.APP_DATA);

            //If the bundle was passed, grab the changeset data
            if (retrieved_data != null) {
                changesets_data = retrieved_data
                        .getParcelableArrayList("ca.spencerelliott.mercury.SEARCH_DATA");
            }

            //If we're missing changeset data, stop here
            if (changesets_data == null)
                return;

            //Create a new array list to store the changesets that were a match
            ArrayList<Beans.ChangesetBean> search_beans = new ArrayList<Beans.ChangesetBean>();

            //Loop through each changeset
            for (Beans.ChangesetBean b : changesets_data) {
                //Check to see if any changesets match
                if (b.getTitle().toLowerCase().contains(query)) {
                    //Get the title and date of the commit
                    String commit_text = b.getTitle();
                    Date commit_date = new Date(b.getUpdated());

                    //Add a new changeset to display in the list view
                    changesets_list.add(createChangeset(
                            (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                            b.getRevisionID() + " - " + commit_date.toLocaleString()));

                    //Add this bean to the list of found search beans
                    search_beans.add(b);
                }
            }

            //Switch the changeset data over to the changeset data that was a match
            changesets_data = search_beans;

            //Update the list in the activity
            list_handler.sendEmptyMessage(SUCCESSFUL);

            //Notify the activity that it is a search window
            is_search_window = true;

            //Stop loading here
            return;
        }

        //Get the data from the intent
        Uri data = getIntent().getData();

        if (data != null) {
            //Extract the path in the intent
            String path_string = data.getEncodedPath();

            //Split it by the forward slashes
            String[] split_path = path_string.split("/");

            //Make sure a valid path was passed
            if (split_path.length == 3) {
                //Get the repository id from the intent
                repo_id = Long.parseLong(split_path[2].toString());
            } else {
                //Notify the user if there was a problem
                Toast.makeText(this, R.string.invalid_intent, 1000).show();
            }
        }
    }

    //Retrieve the changesets
    refreshChangesets();
}

From source file:ru.orangesoftware.financisto.activity.FlowzrSyncActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FlowzrSyncActivity.me = this;

    mNotifyBuilder = new NotificationCompat.Builder(getApplicationContext());
    nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    setContentView(R.layout.flowzr_sync);
    restoreUIFromPref();//from   w  w w. ja  v a  2 s. c o m

    AccountManager accountManager = AccountManager.get(getApplicationContext());
    final Account[] accounts = accountManager.getAccountsByType("com.google");
    if (accounts.length < 1) {
        new AlertDialog.Builder(this).setTitle(getString(R.string.flowzr_sync_error))
                .setMessage(R.string.account_required)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).show();
    }
    //checkbox
    CheckBox chk = (CheckBox) findViewById(R.id.chk_sync_from_zero);
    OnClickListener chk_listener = new OnClickListener() {
        public void onClick(View v) {
            lastSyncLocalTimestamp = 0;
            renderLastTime(0);
            flowzrSyncEngine.resetLastTime(getApplicationContext());
        }
    };
    chk.setOnClickListener(chk_listener);
    //radio crendentials
    RadioGroup radioGroupCredentials = (RadioGroup) findViewById(R.id.radioCredentials);
    OnClickListener radio_listener = new OnClickListener() {
        public void onClick(View v) {
            RadioButton radioButtonSelected = (RadioButton) findViewById(v.getId());
            for (Account account : accounts) {
                if (account.name == radioButtonSelected.getText()) {
                    lastSyncLocalTimestamp = 0;
                    renderLastTime(0);
                    flowzrSyncEngine.resetLastTime(getApplicationContext());
                    useCredential = account;
                }
            }
        }
    };
    radioGroupCredentials.setOnClickListener(radio_listener);
    //initialize value
    for (int i = 0; i < accounts.length; i++) {
        RadioButton rb = new RadioButton(this);
        radioGroupCredentials.addView(rb); //, 0, lp); 
        rb.setOnClickListener(radio_listener);
        rb.setText(((Account) accounts[i]).name);
        String prefAccount = MyPreferences.getFlowzrAccount(this);
        if (prefAccount != null) {
            if (accounts[i].name.equals(prefAccount)) {
                useCredential = accounts[i];
                rb.toggle(); //.setChecked(true);
            }
        }
    }

    bOk = (Button) findViewById(R.id.bOK);
    bOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            startSync();

        }
    });

    Button bCancel = (Button) findViewById(R.id.bCancel);
    bCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (flowzrSyncEngine != null) {
                flowzrSyncEngine.isCanceled = true;
            }
            isRunning = false;
            setResult(RESULT_CANCELED);
            setReady();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            //finish();
        }
    });

    Button textViewAbout = (Button) findViewById(R.id.buySubscription);
    textViewAbout.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (isOnline(FlowzrSyncActivity.this)) {
                visitFlowzr(useCredential);
            } else {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
            }
        }
    });

    Button textViewAboutAnon = (Button) findViewById(R.id.visitFlowzr);
    textViewAboutAnon.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (isOnline(FlowzrSyncActivity.this)) {
                visitFlowzr(null);
            } else {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
            }
        }
    });

    TextView textViewNotes = (TextView) findViewById(R.id.flowzrPleaseNote);
    textViewNotes.setMovementMethod(LinkMovementMethod.getInstance());
    textViewNotes.setText(Html.fromHtml(getString(R.string.flowzr_terms_of_use)));
    if (MyPreferences.isAutoSync(this)) {
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(getApplicationContext());

            if (regid.equals("")) {
                registerInBackground();
            }
            Log.i(TAG, "Google Cloud Messaging registered as :" + regid);
        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }
}

From source file:com.matze5800.paupdater.Functions.java

public static void Clear(Context context) {
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancelAll();/*www .j a  v a 2  s  .c  o m*/
}

From source file:br.com.bioscada.apps.biotracks.io.sendtogoogle.SendToGoogleUtils.java

/**
 * Cancels any notification to request a permission.
 * /*from ww  w .  jav  a 2 s . c  om*/
 * @param context the context
 * @param notificationId the notification id
 */
public static void cancelNotification(Context context, int notificationId) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(notificationId);
}