Example usage for android.os PowerManager FULL_WAKE_LOCK

List of usage examples for android.os PowerManager FULL_WAKE_LOCK

Introduction

In this page you can find the example usage for android.os PowerManager FULL_WAKE_LOCK.

Prototype

int FULL_WAKE_LOCK

To view the source code for android.os PowerManager FULL_WAKE_LOCK.

Click Source Link

Document

Wake lock level: Ensures that the screen and keyboard backlight are on at full brightness.

Usage

From source file:com.detroitteatime.autocarfinder.Main.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int itemId = item.getItemId();
    if (itemId == R.id.sleep) {
        Intent intent = new Intent(Main.this, SleepTimeDialog.class);
        startActivity(intent);// w  ww.  jav a  2  s . co  m
        return true;
    } else if (itemId == R.id.no_sleep) {
        editor1.putInt(Main.SLEEP_MODE_KEY, Main.SLEEP_MODE_FALSE);
        editor1.commit();
    } else if (itemId == R.id.set_wakelock) {
        int setting = data1.getInt(WAKE_LOCK_SETTING, PowerManager.PARTIAL_WAKE_LOCK);
        if (setting == PowerManager.PARTIAL_WAKE_LOCK) {

            editor1.putInt(WAKE_LOCK_SETTING, PowerManager.FULL_WAKE_LOCK);
            editor1.commit();

            myMenu.findItem(R.id.set_wakelock).setTitle("Change to PARTIAL_WAKE_LOCK");

        } else {

            editor1.putInt(WAKE_LOCK_SETTING, PowerManager.PARTIAL_WAKE_LOCK);
            editor1.commit();

            myMenu.findItem(R.id.set_wakelock).setTitle("Change to FULL_WAKE_LOCK");

        }
    } else if (itemId == R.id.legal) {
        String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getApplicationContext());
        Builder LicenseDialog = new Builder(Main.this);
        LicenseDialog.setTitle("Legal Notices");
        LicenseDialog.setMessage(LicenseInfo);
        LicenseDialog.show();
        return true;
    } else if (itemId == R.id.info) {
        String info = getString(R.string.how_to);
        Builder InfoDialog = new Builder(Main.this);
        InfoDialog.setTitle("Legal Notices");
        InfoDialog.setMessage(info);
        InfoDialog.show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

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

/** Called when the activity is first created. */
@Override// w ww .java2 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:com.android.development.Connectivity.java

private void onStartScreenCycle() {
    try {//from ww  w.j a v a  2 s  .  co m
        mSCOnDuration = Long.parseLong(mSCOnDurationEdit.getText().toString());
        mSCOffDuration = Long.parseLong(mSCOffDurationEdit.getText().toString());
    } catch (Exception e) {
    }
    ;
    mSCCycleCount = 0;

    mScreenonWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ConnectivityTest");
    mScreenonWakeLock.acquire();

    scheduleAlarm(10, SCREEN_OFF);
}

From source file:com.ternup.caddisfly.fragment.DetailsFragment.java

public void postResult(String folderName) {

    RequestParams params = new RequestParams();
    TimeZone tz = TimeZone.getTimeZone("UTC");
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
    df.setTimeZone(tz);/*  ww  w . j  av  a 2s .co  m*/

    final ArrayList<String> filePaths = FileUtils.getFilePaths(getActivity(), folderName, "/small/",
            mLocationId);
    File myFile = new File(filePaths.get(0));
    String date = df.format(DateUtils.getDateFromFilename(myFile.getName()));

    params.put("date", date);
    String deviceId = Build.MANUFACTURER + " " + Build.MODEL;
    if (deviceId.length() > 32) {
        deviceId = deviceId.substring(1, 32);
    }
    params.put("deviceId", deviceId);
    params.put("type", String.valueOf(mTestTypeId + 1));

    if (wakeLock == null || !wakeLock.isHeld()) {
        PowerManager pm = (PowerManager) getActivity().getApplicationContext()
                .getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
        wakeLock.acquire();
    }

    WebClient.post("tests", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String response = responseBody == null ? null : new String(responseBody);
            try {
                JSONObject json = new JSONObject(response);
                final int newId = json.getInt("id");
                if (filePaths.size() > 0) {
                    count = 0;
                    totalCount = filePaths.size();
                    postItem(newId, filePaths);
                }

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

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, final Throwable error) {
            Log.d(Globals.DEBUG_TAG, "fail: " + error.getMessage());

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }

                    if (wakeLock != null && wakeLock.isHeld()) {
                        wakeLock.release();
                    }
                    AlertUtils.showAlert(getActivity(), R.string.error, error.getMessage(), R.string.ok, null,
                            null);
                }
            });
        }
    });
}

From source file:net.czlee.debatekeeper.AlertManager.java

/**
 * Wakes up the screen to attract user attention
 *///  w  ww  .  java 2  s.  co  m
private void wakeUpScreenForBell(long wakeTime) {
    if (mActivityActive) {
        int flags = PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK;
        PowerManager.WakeLock temporaryWakeLock = mPowerManager.newWakeLock(flags, "Debatekeeper-bell");
        temporaryWakeLock.acquire(wakeTime);
    }
}

From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java

private TaggedWakeLock newWakeLock() {
    TaggedWakeLock wl = TaggedWakeLock.newTaggedWakeLock(mService, PowerManager.FULL_WAKE_LOCK,
            "ACTIONSCREEN WakeLock");
    return wl;
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) {
    String shortText;//from   w  w  w .j  a v a 2 s  . c om
    String longText;
    String title;
    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, null, 0);

    NotificationCompat.InboxStyle inbox = null;

    if (tweets.size() == 1) {
        title = tweets.get(0)[0];
        shortText = tweets.get(0)[1];
        longText = shortText;

        largeIcon = getImage(context, tweets.get(0)[2]);
    } else {
        inbox = new NotificationCompat.InboxStyle();

        title = context.getResources().getString(R.string.favorite_users);
        shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets);
        longText = "";

        try {
            inbox.setBigContentTitle(shortText);
        } catch (Exception e) {

        }

        if (tweets.size() <= 5) {
            for (String[] s : tweets) {
                inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1]));
            }
        } else {
            for (int i = 0; i < 5; i++) {
                inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1]));
            }

            inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets));
        }

        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
    }

    NotificationCompat.Builder mBuilder;

    AppSettings settings = AppSettings.getInstance(context);

    if (shortText.contains("@" + settings.myScreenName)) {
        // return because there is a mention notification for this already
        return;
    }

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
    } else {
        mBuilder.setStyle(inbox);
    }
    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(2, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (context
                .getSharedPreferences("com.daiv.android.twitter_world_preferences",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)
                .getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, shortText);
        }

        // Light Flow notification
        sendToLightFlow(context, title, shortText);
    }
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) {
    String shortText;//from   ww  w .j a  va  2s  .co  m
    String longText;
    String title;
    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;

    Intent resultIntent;

    if (toDrawer) {
        resultIntent = new Intent(context, RedirectToDrawer.class);
    } else {
        resultIntent = new Intent(context, NotiTweetPager.class);
    }

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    NotificationCompat.InboxStyle inbox = null;

    if (tweets.size() == 1) {
        title = tweets.get(0)[0];
        shortText = tweets.get(0)[1];
        longText = shortText;

        largeIcon = getImage(context, tweets.get(0)[2]);
    } else {
        inbox = new NotificationCompat.InboxStyle();

        title = context.getResources().getString(R.string.favorite_users);
        shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets);
        longText = "";

        try {
            inbox.setBigContentTitle(shortText);
        } catch (Exception e) {

        }

        if (tweets.size() <= 5) {
            for (String[] s : tweets) {
                inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1]));
            }
        } else {
            for (int i = 0; i < 5; i++) {
                inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1]));
            }

            inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets));
        }

        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
    }

    NotificationCompat.Builder mBuilder;

    AppSettings settings = AppSettings.getInstance(context);

    if (shortText.contains("@" + settings.myScreenName)) {
        // return because there is a mention notification for this already
        return;
    }

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
    } else {
        mBuilder.setStyle(inbox);
    }
    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(2, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (context
                .getSharedPreferences("com.klinker.android.twitter_world_preferences",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)
                .getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, shortText);
        }

        // Light Flow notification
        sendToLightFlow(context, title, shortText);
    }
}

From source file:net.ustyugov.jtalk.service.JTalkService.java

@Override
public void onCreate() {
    configure();/*  w w  w  .  ja va2s. co m*/
    js = this;
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    iconPicker = new IconPicker(this);

    //        updateReceiver = new BroadcastReceiver() {
    //         @Override
    //         public void onReceive(Context arg0, Intent arg1) {
    //            updateWidget();
    //         }
    //        };
    //        registerReceiver(updateReceiver, new IntentFilter(Constants.UPDATE));

    connectionReceiver = new ChangeConnectionReceiver();
    registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    screenStateReceiver = new ScreenStateReceiver();
    registerReceiver(new ScreenStateReceiver(), new IntentFilter(Intent.ACTION_SCREEN_ON));
    registerReceiver(new ScreenStateReceiver(), new IntentFilter(Intent.ACTION_SCREEN_OFF));

    Intent i = new Intent(this, RosterActivity.class);
    i.setAction(Intent.ACTION_MAIN);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setSmallIcon(R.drawable.stat_offline);
    mBuilder.setContentTitle(getString(R.string.app_name));
    mBuilder.setContentIntent(contentIntent);

    startForeground(Notify.NOTIFICATION, mBuilder.build());

    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "jTalk");
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "jTalk");

    started = true;

    Cursor cursor = getContentResolver().query(JTalkProvider.ACCOUNT_URI, null,
            AccountDbHelper.ENABLED + " = '" + 1 + "'", null, null);
    if (cursor != null && cursor.getCount() > 0) {
        connect();
        cursor.close();
    }
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;/*w  w w .  ja va 2  s  .  co  m*/

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

    Intent markRead = new Intent(context, MarkReadSecondAccService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    AppSettings settings = AppSettings.getInstance(context);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverTwo.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setAutoCancel(true).setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(9, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, messageLong);
        }

        // Light Flow notification
        sendToLightFlow(context, title, messageLong);
    }
}