Example usage for android.content Context POWER_SERVICE

List of usage examples for android.content Context POWER_SERVICE

Introduction

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

Prototype

String POWER_SERVICE

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

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

Usage

From source file:activities.Activity_Main.java

/** Called when the activity is first created. */
@Override/* w  w  w.j av  a  2  s  . co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myself = this;
    setContentView(R.layout.activity_home);

    SP_params = PreferenceManager.getDefaultSharedPreferences(this);
    SP_prefEditor = SP_params.edit();
    Tracer = tracerengine.getInstance(SP_params);

    //Added by Doume
    File storage = new File(Environment.getExternalStorageDirectory() + "/domodroid/.conf/");
    if (!storage.exists())
        storage.mkdirs();
    //Configure Tracer tool initial state
    File logpath = new File(Environment.getExternalStorageDirectory() + "/domodroid/.log/");
    if (!logpath.exists())
        logpath.mkdirs();

    String currlogpath = SP_params.getString("LOGNAME", "");
    if (currlogpath.equals("")) {
        //Not yet existing prefs : Configure debugging by default, to configure Tracer
        currlogpath = Environment.getExternalStorageDirectory() + "/domodroid/.log/";
        SP_prefEditor.putString("LOGPATH", currlogpath);
        SP_prefEditor.putString("LOGNAME", "Domodroid.txt");
        SP_prefEditor.putBoolean("SYSTEMLOG", false);
        SP_prefEditor.putBoolean("TEXTLOG", false);
        SP_prefEditor.putBoolean("SCREENLOG", false);
        SP_prefEditor.putBoolean("LOGCHANGED", true);
        SP_prefEditor.putBoolean("LOGAPPEND", false);
    } else {
        SP_prefEditor.putBoolean("LOGCHANGED", true); //To force Tracer to consider current settings
    }
    //prefEditor.putBoolean("SYSTEMLOG", false);      // For tests : no system logs....
    SP_prefEditor.putBoolean("SYSTEMLOG", true); // For tests : with system logs....

    SP_prefEditor.commit();

    Tracer.set_profile(SP_params);
    // Create .nomedia file, that will prevent Android image gallery from showing domodroid file
    String nomedia = Environment.getExternalStorageDirectory() + "/domodroid/.nomedia";
    try {
        if (!(new File(nomedia).exists())) {
            new FileOutputStream(nomedia).close();
        }
    } catch (Exception e) {
    }

    appname = (ImageView) findViewById(R.id.app_name);

    LoadSelections();

    // Prepare a listener to know when a sync dialog is closed...
    if (sync_listener == null) {
        sync_listener = new DialogInterface.OnDismissListener() {

            public void onDismiss(DialogInterface dialog) {

                Tracer.d(mytag, "sync dialog has been closed !");

                // Is it success or fail ?
                if (((Dialog_Synchronize) dialog).need_refresh) {
                    // Sync has been successful : Force to refresh current main view
                    Tracer.d(mytag, "sync dialog requires a refresh !");
                    reload = true; // Sync being done, consider shared prefs are OK
                    VG_parent.removeAllViews();
                    if (WU_widgetUpdate != null) {
                        WU_widgetUpdate.resync();
                    } else {
                        Tracer.i(mytag + ".onCreate", "WidgetUpdate is null startCacheengine!");
                        startCacheEngine();
                    }
                    Bundle b = new Bundle();
                    //Notify sync complete to parent Dialog
                    b.putInt("id", 0);
                    b.putString("type", "root");
                    Message msg = new Message();
                    msg.setData(b);
                    if (widgetHandler != null)
                        widgetHandler.sendMessage(msg); // That should force to refresh Views
                    /* */
                    if (WU_widgetUpdate != null) {
                        WU_widgetUpdate.Disconnect(0); //That should disconnect all opened widgets from cache engine
                        //widgetUpdate.dump_cache();   //For debug
                        dont_kill = true; // to avoid engines kill when onDestroy()
                    }
                    onResume();
                } else {
                    Tracer.d(mytag, "sync dialog end with no refresh !");

                }
                ((Dialog_Synchronize) dialog).need_refresh = false;
            }
        };
    }

    //update thread
    sbanim = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name2));
            } else if (msg.what == 1) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name3));
            } else if (msg.what == 2) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name1));
            } else if (msg.what == 3) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name4));
            } else if (msg.what == 8000) {
                Tracer.e(mytag, "Request to display message : 8000");
                /*
                if(dialog_message == null) {
                   Create_message_box();
                }
                dialog_message.setMessage("Starting cache engine...");
                dialog_message.show();
                        
                */
            } else if (msg.what == 8999) {
                //Cache engine is ready for use....
                if (Tracer != null)
                    Tracer.e(mytag, "Cache engine has notified it's ready !");
                cache_ready = true;
                if (end_of_init_requested)
                    end_of_init();
                PG_dialog_message.dismiss();
            }
        }
    };

    //power management
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    this.PM_WakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "");
    this.PM_WakeLock.acquire();

    //titlebar
    final FrameLayout titlebar = (FrameLayout) findViewById(R.id.TitleBar);
    titlebar.setBackgroundDrawable(Gradients_Manager.LoadDrawable("title", 40));

    //Parent view
    VG_parent = (ViewGroup) findViewById(R.id.home_container);

    LL_house_map = new LinearLayout(this);
    LL_house_map
            .setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    LL_house_map.setOrientation(LinearLayout.HORIZONTAL);
    LL_house_map.setPadding(5, 5, 5, 5);

    house = new Basic_Graphical_zone(getApplicationContext(), 0, Graphics_Manager.Names_Agent(this, "House"),
            "", "house", 0, "", null);
    house.setPadding(0, 0, 5, 0);
    map = new Basic_Graphical_zone(getApplicationContext(), 0, Graphics_Manager.Names_Agent(this, "Map"), "",
            "map", 0, "", null);
    map.setPadding(5, 0, 0, 0);

    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT, 1.0f);

    house.setLayoutParams(param);
    house.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (SP_params.getBoolean("SYNC", false)) {
                loadWigets(0, "root");
                historyPosition++;
                history.add(historyPosition, new String[] { "0", "root" });
            } else {
                if (AD_notSyncAlert == null)
                    createAlert();
                AD_notSyncAlert.show();
            }
        }
    });

    map.setLayoutParams(param);
    map.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (SP_params.getBoolean("SYNC", false)) {
                //dont_freeze=true;      //To avoid WidgetUpdate engine freeze
                Tracer.w(mytag, "Before call to Map, Disconnect widgets from engine !");
                if (WU_widgetUpdate != null) {
                    WU_widgetUpdate.Disconnect(0); //That should disconnect all opened widgets from cache engine
                    //widgetUpdate.dump_cache();   //For debug
                    dont_kill = true; // to avoid engines kill when onDestroy()
                }
                INTENT_map = new Intent(Activity_Main.this, Activity_Map.class);
                Tracer.d(mytag, "Call to Map, run it now !");
                Tracer.Map_as_main = false;
                startActivity(INTENT_map);
            } else {
                if (AD_notSyncAlert == null)
                    createAlert();
                AD_notSyncAlert.show();
            }
        }
    });

    LL_house_map.addView(house);
    LL_house_map.addView(map);

    init_done = false;
    // Detect if it's the 1st use after installation...
    if (!SP_params.getBoolean("SPLASH", false)) {
        // Yes, 1st use !
        init_done = false;
        reload = false;
        if (backupprefs.exists()) {
            // A backup exists : Ask if reload it
            Tracer.v(mytag, "settings backup found after a fresh install...");

            DialogInterface.OnClickListener reload_listener = new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    Tracer.e(mytag, "Reload dialog returns : " + which);
                    if (which == dialog.BUTTON_POSITIVE) {
                        reload = true;
                    } else if (which == dialog.BUTTON_NEGATIVE) {
                        reload = false;
                    }
                    check_answer();
                    dialog.dismiss();
                }
            };
            dialog_reload = new AlertDialog.Builder(this);
            dialog_reload.setMessage(getText(R.string.home_reload));
            dialog_reload.setTitle(getText(R.string.reload_title));
            dialog_reload.setPositiveButton(getText(R.string.reloadOK), reload_listener);
            dialog_reload.setNegativeButton(getText(R.string.reloadNO), reload_listener);
            dialog_reload.show();
            init_done = false; //A choice is pending : Rest of init has to be completed...
        } else {
            //No settings backup found
            Tracer.v(mytag, "no settings backup found after fresh install...");
            end_of_init_requested = true;
            // open server config view
            Intent helpI = new Intent(Activity_Main.this, Preference.class);
            startActivity(helpI);
        }
    } else {
        // It's not the 1st use after fresh install
        // This method will be followed by 'onResume()'
        end_of_init_requested = true;
    }
    if (SP_params.getBoolean("SYNC", false)) {
        //A config exists and a sync as been done by past.
        if (WU_widgetUpdate == null) {
            Tracer.i(mytag + ".onCreate", "Params splach is false and WidgetUpdate is null startCacheengine!");
            startCacheEngine();
        }

    }

    Tracer.e(mytag, "OnCreate() complete !");
    // End of onCreate (UIThread)
}

From source file:com.brayanarias.alarmproject.activity.AlarmScreenActivity.java

@Override
protected void onResume() {
    super.onResume();
    Log.e(TAG, "on Resume Method");
    // Set the window to keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Acquire wakelock
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    if (wakeLock == null) {
        wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), tag);
    }/*  w w  w  .j av a 2  s  .co m*/

    if (!wakeLock.isHeld()) {
        wakeLock.acquire();
    }
}

From source file:com.ternup.caddisfly.activity.SurveyActivity.java

@Override
protected void onStart() {
    super.onStart();

    if (wakeLock == null || !wakeLock.isHeld()) {
        PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
        wakeLock.acquire();//from w  w  w .java  2  s.c  o m
    }
}

From source file:io.vit.vitio.Fragments.Today.TodayFragment.java

private void animateView() {
    PowerManager powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && powerManager.isPowerSaveMode()) {
        return;//from   w ww  .j  a  v  a 2s  .c  om
    }
    //float dimension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
    ObjectAnimator objectAnimatorX = ObjectAnimator.ofFloat(ocassionImage, "scaleX", 1f, 0.8f);
    ObjectAnimator objectAnimatorY = ObjectAnimator.ofFloat(ocassionImage, "scaleY", 1f, 0.8f);
    objectAnimatorX.setDuration(6000);
    objectAnimatorY.setDuration(6000);
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(objectAnimatorX, objectAnimatorY);
    animatorSet.setInterpolator(new LinearInterpolator());
    objectAnimatorX.setRepeatCount(ObjectAnimator.INFINITE);
    objectAnimatorX.setRepeatMode(ObjectAnimator.REVERSE);
    objectAnimatorY.setRepeatCount(ObjectAnimator.INFINITE);
    objectAnimatorY.setRepeatMode(ObjectAnimator.REVERSE);
    animatorSet.start();
    objectAnimatorX.start();
}

From source file:im.afterclass.android.activity.ChatActivity.java

private void setUpView() {
    activityInstance = this;
    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???//from   w  w  w  .  j  a v  a2  s. c om
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        ((TextView) findViewById(R.id.name)).setText(toChatUsername);
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.container_remove).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(toChatUsername);
        ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
    }
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnsetMsgCount();
    adapter = new MessageAdapter(this, toChatUsername, chatType);
    // ?
    listView.setAdapter(adapter);
    listView.setOnScrollListener(new ListScrollListener());
    int count = listView.getCount();
    if (count > 0) {
        listView.setSelection(count - 1);
    }

    listView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideKeyboard();
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // ?
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,??chat??????
    intentFilter.setPriority(5);
    registerReceiver(receiver, intentFilter);

    // ack?BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(5);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // show forward message if the message is not null
    String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
    if (forward_msg_id != null) {
        // ?????
        forwardMessage(forward_msg_id);
    }

}

From source file:com.oo58.game.texaspoker.AppActivity.java

@Override
public void onResume() {
    super.onResume();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    //mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
    //      "<span><span class='string'>MyLock</span></span>");
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "ATAAW");
    mWakeLock.acquire();/*  w  w w.ja  va  2s.  c  o  m*/

    MobclickAgent.onResume(this);

    XGPushClickedResult click = XGPushManager.onActivityStarted(this);
    Log.d("TPush", "onResumeXGPushClickedResult:" + click);
    if (click != null) { // 
        //         Toast.makeText(this, ":" + click.toString(),
        //               Toast.LENGTH_SHORT).show();
    }
}

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

public static void refreshNotification(Context context, boolean noTimeline) {
    AppSettings settings = AppSettings.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences(
            "com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
    int currentAccount = sharedPrefs.getInt("current_account", 1);

    //int[] unreadCounts = new int[] {4, 1, 2}; // for testing
    int[] unreadCounts = getUnreads(context);

    int timeline = unreadCounts[0];
    int realTimelineCount = timeline;

    // if they don't want that type of notification, simply set it to zero
    if (!settings.timelineNot || (settings.pushNotifications && settings.liveStreaming) || noTimeline) {
        unreadCounts[0] = 0;/* w  w w .  j a va 2  s  .c  o m*/
    }
    if (!settings.mentionsNot) {
        unreadCounts[1] = 0;
    }
    if (!settings.dmsNot) {
        unreadCounts[2] = 0;
    }

    if (unreadCounts[0] == 0 && unreadCounts[1] == 0 && unreadCounts[2] == 0) {

    } else {
        Intent markRead = new Intent(context, MarkReadService.class);
        PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

        String shortText = getShortText(unreadCounts, context, currentAccount);
        String longText = getLongText(unreadCounts, context, currentAccount);
        // [0] is the full title and [1] is the screenname
        String[] title = getTitle(unreadCounts, context, currentAccount);
        boolean useExpanded = useExp(context);
        boolean addButton = addBtn(unreadCounts);

        if (title == null) {
            return;
        }

        Intent resultIntent;

        if (unreadCounts[1] != 0 && unreadCounts[0] == 0) {
            // it is a mention notification (could also have a direct message)
            resultIntent = new Intent(context, RedirectToMentions.class);
        } else if (unreadCounts[2] != 0 && unreadCounts[0] == 0 && unreadCounts[1] == 0) {
            // it is a direct message
            resultIntent = new Intent(context, RedirectToDMs.class);
        } else {
            resultIntent = new Intent(context, MainActivity.class);
        }

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

        NotificationCompat.Builder mBuilder;

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

        mBuilder = new NotificationCompat.Builder(context).setContentTitle(title[0])
                .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings))
                .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(getIcon(context, unreadCounts, title[1]))
                .setContentIntent(resultPendingIntent).setAutoCancel(true)
                .setTicker(TweetLinkUtils.removeColorHtml(shortText, settings))
                .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        if (unreadCounts[1] > 1 && unreadCounts[0] == 0 && unreadCounts[2] == 0) {
            // inbox style notification for mentions
            mBuilder.setStyle(getMentionsInboxStyle(unreadCounts[1], currentAccount, context,
                    TweetLinkUtils.removeColorHtml(shortText, settings)));
        } else if (unreadCounts[2] > 1 && unreadCounts[0] == 0 && unreadCounts[1] == 0) {
            // inbox style notification for direct messages
            mBuilder.setStyle(getDMInboxStyle(unreadCounts[1], currentAccount, context,
                    TweetLinkUtils.removeColorHtml(shortText, settings)));
        } else {
            // big text style for an unread count on timeline, mentions, and direct messages
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                    settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title[0], shortText);
        }

        // Light Flow notification
        sendToLightFlow(context, title[0], shortText);

        int homeTweets = unreadCounts[0];
        int mentionsTweets = unreadCounts[1];
        int dmTweets = unreadCounts[2];

        int newC = 0;

        if (homeTweets > 0) {
            newC++;
        }
        if (mentionsTweets > 0) {
            newC++;
        }
        if (dmTweets > 0) {
            newC++;
        }

        if (settings.notifications && newC > 0) {

            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);

            // Get an instance of the NotificationManager service
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

            if (addButton) { // the reply and read button should be shown
                Intent reply;
                if (unreadCounts[1] == 1) {
                    reply = new Intent(context, NotificationCompose.class);
                } else {
                    reply = new Intent(context, NotificationDMCompose.class);
                }

                Log.v("username_for_noti", title[1]);
                sharedPrefs.edit().putString("from_notification", "@" + title[1] + " " + title[2]).commit();
                MentionsDataSource data = MentionsDataSource.getInstance(context);
                long id = data.getLastIds(currentAccount)[0];
                PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0);
                sharedPrefs.edit().putLong("from_notification_long", id).commit();
                sharedPrefs.edit()
                        .putString("from_notification_text",
                                "@" + title[1] + ": " + TweetLinkUtils.removeColorHtml(shortText, settings))
                        .commit();

                // Create the remote input
                RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                        .setLabel("@" + title[1] + " ").build();

                // Create the notification action
                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
                        R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply),
                        replyPending).addRemoteInput(remoteInput).build();

                NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
                        R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read),
                        readPending);

                mBuilder.addAction(replyAction);
                mBuilder.addAction(action.build());
            } else { // otherwise, if they can use the expanded notifications, the popup button will be shown
                Intent popup = new Intent(context, RedirectToPopup.class);
                popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                popup.putExtra("from_notification", true);

                PendingIntent popupPending = PendingIntent.getActivity(context, 0, popup, 0);

                NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
                        R.drawable.ic_popup, context.getResources().getString(R.string.popup), popupPending);

                mBuilder.addAction(action.build());
            }

            // Build the notification and issues it with notification manager.
            notificationManager.notify(1, 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);
            }
        }

        // if there are unread tweets on the timeline, check them for favorite users
        if (settings.favoriteUserNotifications && realTimelineCount > 0) {
            favUsersNotification(currentAccount, context);
        }
    }

    try {

        ContentValues cv = new ContentValues();

        cv.put("tag", "com.klinker.android.twitter/com.klinker.android.twitter.ui.MainActivity");

        // add the direct messages and mentions
        cv.put("count", unreadCounts[1] + unreadCounts[2]);

        context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);

    } catch (IllegalArgumentException ex) {

        /* Fine, TeslaUnread is not installed. */

    } catch (Exception ex) {

        /* Some other error, possibly because the format
           of the ContentValues are incorrect.
                
        Log but do not crash over this. */

        ex.printStackTrace();

    }
}

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

public void postResult(final String url) {

    RequestParams params = new RequestParams();
    TimeZone tz = TimeZone.getTimeZone("UTC");
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
    df.setTimeZone(tz);/*from  w  w w  .j  a  v  a 2s. c o  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, 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();
                    }
                }
            });

        }
    });
}

From source file:com.runye.express.chat.activity.ChatActivity.java

private void setUpView() {
    activityInstance = this;
    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???//w  ww. j av  a 2s. co  m
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        ((TextView) findViewById(R.id.name)).setText(getIntent().getStringExtra("nick"));
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.container_remove).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(toChatUsername);
        ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
    }
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnsetMsgCount();
    adapter = new MessageAdapter(this, toChatUsername, chatType);
    // ?
    listView.setAdapter(adapter);
    listView.setOnScrollListener(new ListScrollListener());
    int count = listView.getCount();
    if (count > 0) {
        listView.setSelection(count - 1);
    }

    listView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideKeyboard();
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // ?
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,??chat??????
    intentFilter.setPriority(5);
    registerReceiver(receiver, intentFilter);

    // ack?BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(5);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // ????T
    groupListener = new GroupListener();
    EMGroupManager.getInstance().addGroupChangeListener(groupListener);

    // show forward message if the message is not null
    String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
    if (forward_msg_id != null) {
        // ?????
        forwardMessage(forward_msg_id);
    }

}

From source file:com.googlecode.eyesfree.brailleback.DisplayManager.java

/**
 * Creates an instance of this class and starts the internal thread to
 * connect to the braille display service.  {@code context} is used to
 * connect to the display service.  {@code translator} is used for braille
 * translation.  The various listeners will be called as appropriate and
 * on the same thread that was used to create this object.  The current
 * thread must have a prepared looper./*from   w w  w. j a  va  2s.  c o  m*/
 */
public DisplayManager(TranslatorManager translatorManager, Context context,
        OnPanOverflowListener panOverflowListener,
        Display.OnConnectionStateChangeListener connectionStateChangeListener,
        OnMappedInputEventListener mappedInputEventListener) {
    mTranslatorManager = translatorManager;
    mTranslatorManager.addOnTablesChangedListener(this);
    mContext = context;
    mPanOverflowListener = panOverflowListener;
    mConnectionStateChangeListener = connectionStateChangeListener;
    mMappedInputEventListener = mappedInputEventListener;
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "BrailleBack");
    mHandlerThread = new HandlerThread("DisplayManager") {
        @Override
        public void onLooperPrepared() {
            mDisplay = new OverlayDisplay(mContext, new DisplayClient(mContext));
            mDisplay.setOnConnectionStateChangeListener(DisplayManager.this);
            mDisplay.setOnInputEventListener(DisplayManager.this);
        }
    };
    mHandlerThread.start();
    mDisplayHandler = new DisplayHandler(mHandlerThread.getLooper());
    mCallbackHandler = new CallbackHandler();
}