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:com.wenwen.chatuidemo.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   ww w. j  a v a 2  s .  c  o  m
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);
    toAccountname = getIntent().getStringExtra("accountname");
    type = getIntent().getStringExtra("type");
    if (!type.equals("1")) {
        toChatUsername = MD5.md5(toChatUsername);
    }
    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("username");//acuntName
        DebugLog.i(TAG, "toChatUsername==" + toChatUsername);
        ((TextView) findViewById(R.id.name)).setText(getIntent().getStringExtra("accountname"));
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.container_remove).setVisibility(View.GONE);
        findViewById(R.id.container_voice_call).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.resetUnreadMsgCount();
    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);
            emojiIconContainer.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);

    // ??BroadcastReceiver
    IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
    deliveryAckMessageIntentFilter.setPriority(5);
    registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

    // ????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.xiaoyu.HeartConsultation.chat.chatuidemo.activity.ChatActivity.java

private void setUpView() {
    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  ww w.  ja va2 s  . com
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        //doctor avatar
        String name = getIntent().getStringExtra("name");
        if (!TextUtils.isEmpty(name)) {
            ((TextView) findViewById(R.id.name)).setText(name);
        } else {
            final ChatUserInfoUtil.UserInfo userInfo = ChatUserInfoUtil.getUserInfo(toChatUsername);
            if (userInfo != null) {
                ((TextView) findViewById(R.id.name)).setText(userInfo.name);
            } else {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                pairs.add(new BasicNameValuePair("userid", toChatUsername));
                Request.doRequest(this, pairs, ServerConfig.URL_QUERY_USER_INFO, Request.GET,
                        new Request.RequestListener() {
                            @Override
                            public void onException(Request.RequestException e) {
                                ((TextView) findViewById(R.id.name)).setText(toChatUsername);
                            }

                            @Override
                            public void onComplete(String response) {
                                UserInfoModel model = HCApplicaton.getInstance().getGson()
                                        .fromJsonWithNoException(response, UserInfoModel.class);
                                if (model != null && model.result == 1) {
                                    ChatUserInfoUtil.UserInfo userInfo1 = new ChatUserInfoUtil.UserInfo();
                                    userInfo1.avatar = model.imagepath;
                                    userInfo1.name = model.nickname;
                                    ChatUserInfoUtil.putUserInfo(toChatUsername, userInfo1);
                                    ((TextView) findViewById(R.id.name)).setText(userInfo1.name);
                                } else {
                                    ((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);
        findViewById(R.id.container_voice_call).setVisibility(View.GONE);
        findViewById(R.id.container_video_call).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");

        if (chatType == CHATTYPE_GROUP) {
            onGroupViewCreation();
        } else {
            onChatRoomViewCreation();
        }
    }

    // for chatroom type, we only init conversation and create view adapter on success
    if (chatType != CHATTYPE_CHATROOM) {
        onConversationInit();

        onListViewCreation();

        // 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.kaixin.android.activity.ChatActivity.java

private void setUpView() {
    Intent intent = new Intent(this, MessagePushService.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    stopService(intent);//from w w  w.j av a  2  s.  co  m
    // ??????,???
    mEmail = getIntent().getStringExtra("email");
    mName = getIntent().getStringExtra("name");
    mAvatar = getIntent().getStringExtra("avatar");
    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");
    // ???

    toChatUsername = mEmail;
    ((TextView) findViewById(R.id.chat_title)).setText(mName);
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnsetMsgCount();
    adapter = new MessageAdapter(mKXApplication, this, toChatUsername, chatType, mAvatar);
    // ?
    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);
    }

    // ??options
    EMChatOptions options = EMChatManager.getInstance().getChatOptions();
    options.setNotificationEnable(true);
    // ??
    options.setNotifyText(new OnMessageNotifyListener() {

        @Override
        public String onNewMessageNotify(EMMessage message) {
            // ??message?????
            try {
                return "?" + message.getStringAttribute("mName") + "????";
            } catch (EaseMobException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "";
        }

        @Override
        public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) {
            return fromUsersNum + "???" + messageNum + "??";
        }

    });

    /*options.setOnNotificationClickListener(new OnNotificationClickListener() {
            
       @Override
       public Intent onNotificationClick(EMMessage message) {
    Intent intent = new Intent(C.this,
          ChatActivity1.class);
    intent.putExtra("email", message.getFrom());
    intent.putExtra("isNews", "yes");
          intent.putExtra("isNews", message.getMsgId());
            
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (msgReceiver != null) {
       try {
          unregisterReceiver(msgReceiver);
       } catch (Exception e) {
          e.printStackTrace();
       }
    }
    return intent;
       }
    });*/

    //            timer = new Timer();
    //             timer.schedule(new RemindTask(), 1* 1000, 4 * 1000);
    mFaceGridView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // ???
            int currentPosition = mEditTextContent.getSelectionStart();
            // 
            mEditTextContent.setText(new TextUtil(mKXApplication).replace(mEditTextContent.getText()
                    .insert(currentPosition, mKXApplication.mFacesText.get(position))));
            // ?
            dismissFace();
        }
    });
    //app?
    EMChat.getInstance().setAppInited();

}

From source file:com.hx.hxchat.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  ww  .  ja v  a 2 s . c  o  m
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        toChatUserNick = getIntent().getStringExtra("userName");
        /* userId10000??????????? */
        if (getIntent().getStringExtra("userId").equals("10000")) {
            rl_bottom.setVisibility(View.GONE);
        }

        // conversation =
        // EMChatManager.getInstance().getConversation(toChatUsername,false);
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.rl_setting).setVisibility(View.GONE);
        findViewById(R.id.container_voice_call).setVisibility(View.GONE);
        findViewById(R.id.container_video_call).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(toChatUsername);
        if (group != null)
            ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
        else
            ((TextView) findViewById(R.id.name)).setText(toChatUsername);
        // conversation =
        // EMChatManager.getInstance().getConversation(toChatUsername,true);
    }
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnreadMsgCount();
    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);
            emojiIconContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // ?
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,??chat??????
    intentFilter.setPriority(9);
    registerReceiver(receiver, intentFilter);

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

    // ??BroadcastReceiver
    IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
    deliveryAckMessageIntentFilter.setPriority(5);
    registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

    // ????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.feytuo.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");
    // ???//from  ww  w . j  a  v  a2s.  com
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        String nickName = getIntent().getStringExtra("userNickName");
        TextView nickNameTV = (TextView) findViewById(R.id.name);
        if (!TextUtils.isEmpty(nickName)) {//?
            nickNameTV.setText(nickName);
        } else {
            nickName = new UserDao(this).getUserNickName(toChatUsername);
            if (!TextUtils.isEmpty(nickName)) {//?
                nickNameTV.setText(nickName);
            } else {//??
                setTitleName(toChatUsername, nickNameTV);
            }
        }

        // conversation =
        // EMChatManager.getInstance().getConversation(toChatUsername,false);
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        //         findViewById(R.id.container_remove).setVisibility(View.GONE);
        findViewById(R.id.container_voice_call).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,true);
    }
    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);

    // ??BroadcastReceiver
    IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
    deliveryAckMessageIntentFilter.setPriority(5);
    registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

    // ????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);
    }
    //??
    if (App.getInstance().getContactList().containsKey(toChatUsername)) {
        findViewById(R.id.chat_add_friend_btn).setVisibility(View.INVISIBLE);
    } else {
        findViewById(R.id.chat_add_friend_btn).setVisibility(View.VISIBLE);
    }

}

From source file:edu.mit.viral.shen.DroidFish.java

/** Called when the activity is first created. */
@Override/*from ww w.  j a  va2s . c  om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    game_number = getIntent().getExtras().getInt("game_id", 0);

    // sendGame();
    Pair<String, String> pair = getPgnOrFenIntent();
    String intentPgnOrFen = pair.first;
    String intentFilename = pair.second;

    createDirectories();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    settings.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            handlePrefsChange();
        }
    });

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    setWakeLock(false);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "droidfish");
    wakeLock.setReferenceCounted(false);

    custom1ButtonActions = new ButtonActions("custom1", CUSTOM1_BUTTON_DIALOG, R.string.select_action);
    custom2ButtonActions = new ButtonActions("custom2", CUSTOM2_BUTTON_DIALOG, R.string.select_action);
    custom3ButtonActions = new ButtonActions("custom3", CUSTOM3_BUTTON_DIALOG, R.string.select_action);

    figNotation = Typeface.createFromAsset(getAssets(), "fonts/DroidFishChessNotationDark.otf");
    setPieceNames(PGNOptions.PT_LOCAL);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    initUI();

    gameTextListener = new PgnScreenText(pgnOptions);
    if (ctrl != null)
        ctrl.shutdownEngine();
    ctrl = new DroidChessController(this, gameTextListener, pgnOptions);
    egtbForceReload = true;
    readPrefs();
    TimeControlData tcData = new TimeControlData();
    mDatabase = new SudokuDatabase(getApplicationContext());
    game_id = Long.valueOf(game_number);
    ctrl = mDatabase.getSudoku(ctrl, game_id);
    startPosition = ctrl.getData();

    tcData.setTimeControl(timeControl, movesPerSession, timeIncrement);
    int version = 1;
    version = settings.getInt("gameStateVersion", version);
    // System.out.println("this is the version" + version);
    ctrl.newGame(gameMode, tcData);

    if (game_number >= 37 && (startPosition.equals("8/8/8/8/8/8/8/8 w - - 0 1")
            | startPosition.equals("8/8/8/8/8/8/8/8 w KQkq - 0 1"))) {
        // System.out.println("greater than 37");
        startEditBoard("8/8/8/8/8/8/8/8 w KQkq - 0 1");
    }

    if (ctrl.getState() == DroidChessController.GAME_STATE_NOT_STARTED) {

        ctrl.start();
        System.out.println("GAME_STATE_NOT_STARTED");
    } else if (ctrl.getState() == DroidChessController.GAME_STATE_PLAYING) {

        System.out.println("GAME_STATE_PLAYING");
        String dataStr = ctrl.getNote();
        // System.out.println(ctrl.getNote());

        byte[] data = strToByteArr(dataStr);
        // ctrl.newGame(gameMode, tcData, "8/8/8/8/8/8/8/8 w KQkq - 0 1");

        ctrl.fromByteArray(data, 3);
    }

    ctrl.setGuiPaused(true);
    ctrl.setGuiPaused(false);
    ctrl.startGame();

    if (intentPgnOrFen != null) {
        try {
            ctrl.setFENOrPGN(intentPgnOrFen);
            setBoardFlip(true);
        } catch (ChessParseError e) {
            // If FEN corresponds to illegal chess position, go into edit board mode.
            try {
                TextIO.readFEN(intentPgnOrFen);
            } catch (ChessParseError e2) {
                if (e2.pos != null)
                    startEditBoard(intentPgnOrFen);
            }
        }
    } else if (intentFilename != null) {
        if (intentFilename.toLowerCase(Locale.US).endsWith(".fen")
                || intentFilename.toLowerCase(Locale.US).endsWith(".epd"))
            loadFENFromFile(intentFilename);
        else
            loadPGNFromFile(intentFilename);
    }
    // commented out 04/12/15
    // sendDataone(startPosition, 1);
    utils = new Utils(getApplicationContext());
    client = new WebSocketClient(URI.create(Const.URL_WEBSOCKET + URLEncoder.encode(name)),
            new WebSocketClient.Listener() {
                @Override
                public void onConnect() {

                }

                /**
                 * On receiving the message from web socket server
                 * */
                @Override
                public void onMessage(String message) {
                    Log.d(TAG, String.format("Got string message! %s", message));
                    parseMessage(message);
                }

                @Override
                public void onMessage(byte[] data) {
                    Log.d(TAG, String.format("Got binary message! %s", bytesToHex(data)));
                    parseMessage(bytesToHex(data));
                    // Message will be in JSON format
                }

                /**
                 * Called when the connection is terminated
                 * */
                @Override
                public void onDisconnect(int code, String reason) {

                    String message = String.format(Locale.US, "Disconnected! Code: %d Reason: %s", code,
                            reason);
                    //                showToast(message);

                    // clear the session id from shared preferences
                    utils.storeSessionId(null);
                }

                @Override
                public void onError(Exception error) {
                    Log.e(TAG, "Error! : " + error);

                }
            }, null);
    client.connect();
}

From source file:org.deviceconnect.android.manager.core.util.DConnectUtil.java

/**
 * ??Context??Doze?????????.//from   w  w  w .ja v a 2  s .  c om
 * <p>
 * Android M ?? OS ????true????
 * </p>
 *
 * @param context 
 * @return Doze????true????false
 */
public static boolean isDozeMode(final Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    } else {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
    }
}

From source file:com.naman14.timber.musicplayer.MusicService.java

@Override
public void onCreate() {
    if (D)/*from   www  .ja va 2s  .  c  om*/
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = NotificationManagerCompat.from(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);
    mSongPlayCount = SongPlayCount.getInstance(this);
    mRecentStore = RecentStore.getInstance(this);

    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setUpMediaSession();
    }

    mPreferences = getSharedPreferences("Service", 0);
    //        mCardId = getCardId();

    //        registerExternalStorageListener();

    mPlayer = new MultiPlayer2(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);

    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    //        mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    //        getContentResolver().registerContentObserver(
    //                MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mMediaStoreObserver);
    //        getContentResolver().registerContentObserver(
    //                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mMediaStoreObserver);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.setReferenceCounted(false);

    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    scheduleDelayedShutdown();

    //        reloadQueueAfterPermissionCheck();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:github.popeen.dsub.service.DownloadService.java

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

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*from w ww.  j ava2 s.  c  om*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            /*try {
               Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
               i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
               i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
               sendBroadcast(i);
            } catch(Throwable e) {
               // Froyo or lower
            }*/

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}

From source file:name.setup.dance.StepService.java

private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    int wakeFlags;
    if (mDanceStepAppSettings.wakeAggressively()) {
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
    } else if (mDanceStepAppSettings.keepScreenOn()) {
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK;
    } else {/*from  w  w  w .  j a  va  2s. c o  m*/
        wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
    }
    wakeLock = pm.newWakeLock(wakeFlags, TAG);
    wakeLock.acquire();
}