Example usage for android.os Message obtain

List of usage examples for android.os Message obtain

Introduction

In this page you can find the example usage for android.os Message obtain.

Prototype

public static Message obtain() 

Source Link

Document

Return a new Message instance from the global pool.

Usage

From source file:com.cttapp.bby.mytlc.layer8apps.CalendarHandler.java

/************
 *  PURPOSE: Handles the primary thread in the service
 *  ARGUMENTS: Intent intent/*from   w ww . ja  va 2 s.  c o  m*/
 *  RETURNS: VOID
 *  AUTHOR: Devin Collins <agent14709@gmail.com>
 *************/
@Override
protected void onHandleIntent(Intent intent) {
    // Get our stored data from the intent
    username = intent.getStringExtra("username");
    password = intent.getStringExtra("password");
    messenger = (Messenger) intent.getExtras().get("handler");
    calID = intent.getIntExtra("calendarID", -1);

    String url = getApplicationContext().getResources().getString(R.string.url);

    // Create variables to be used through the application
    List<String[]> workDays = null;
    ConnectionManager conn = ConnectionManager.newConnection();

    /************
     * Once we verify that we have a valid token, we get the actual schedule
     *************/
    updateStatus("Logging in...");
    String tempToken = conn.getData(url + "/etm/login.jsp");
    if (tempToken != null) {
        loginToken = parseToken(tempToken);
    } else {
        showError("Error connecting to MyTLC, make sure you have a valid network connection");
        return;
    }

    String postResults = null;
    // This creates our login information
    List<NameValuePair> parameters = createParams();
    if (loginToken != null) {
        // Here we send the information to the server and login
        postResults = conn.postData(url + "/etm/login.jsp", parameters);
    } else {
        showError("Error retrieving your login token");
        return;
    }

    if (postResults != null && postResults.toLowerCase().contains("etmmenu.jsp")
            && !postResults.toLowerCase().contains("<font size=\"2\">")) {
        updateStatus("Retrieving schedule...");
        postResults = conn.getData(url + "/etm/time/timesheet/etmTnsMonth.jsp");
    } else {
        String error = parseError(postResults);
        if (error != null) {
            showError(error);
        } else {
            showError("Error logging in, please verify your username and password");
        }
        return;
    }

    // If we successfully got the information, then parse out the schedule to read it properly
    String secToken = null;
    if (postResults != null) {
        updateStatus("Parsing schedule...");
        workDays = parseSchedule(postResults);
        secToken = parseSecureToken(postResults);
        wbat = parseWbat(postResults);
    } else {
        showError("Could not obtain user schedule");
        return;
    }

    if (secToken != null) {
        parameters = createSecondParams(secToken);
        postResults = conn.postData(url + "/etm/time/timesheet/etmTnsMonth.jsp", parameters);
    } else {
        String error = parseError(postResults);
        if (error != null) {
            showError(error);
        } else {
            showError("Error retrieving your security token");
        }
        return;
    }

    List<String[]> secondMonth = null;
    if (postResults != null) {
        secondMonth = parseSchedule(postResults);
    } else {
        showError("Could not obtain user schedule");
        return;
    }

    if (secondMonth != null) {
        if (workDays == null) {
            workDays = secondMonth;
        } else {
            workDays.addAll(secondMonth);
        }
        finalDays = workDays;
    } else {
        String error = parseError(postResults);
        if (error != null) {
            showError(error);
        } else {
            showError("There was an error retrieving your schedule");
        }
        return;
    }

    // Add our shifts to the calendar
    updateStatus("Adding shifts to calendar...");
    int numShifts = addDays();

    if (finalDays != null && numShifts > -1) {
        // Report back that we're successful!
        Message msg = Message.obtain();
        Bundle b = new Bundle();
        b.putString("status", "DONE");
        b.putInt("count", numShifts);
        msg.setData(b);
        try {
            messenger.send(msg);
        } catch (Exception e) {
            // Nothing
        }
    } else {
        showError("Couldn't add your shifts to your calendar");
    }

}

From source file:com.cwp.android.baidutest.MyApplication.java

public static void startMaInfoMonitoring() {

    //?MaInfo?/*from   w  ww. jav a  2s.  c  om*/
    BmobRealTimeData rtd = new BmobRealTimeData();

    //start?
    //??
    rtd.start(mContext, new ValueEventListener() {
        @Override
        public void onConnectCompleted() {
            //?
            Log.d("->MyApplication", "BmobRealTimeData->currentThread=" + Thread.currentThread());
            Log.d("->MyApplication", "BmobRealTimeData->?:" + rtd.isConnected());

            //?
            if (rtd.isConnected()) {
                rtd.subTableUpdate("MaInfo");
            }
        }

        @Override
        public void onDataChange(JSONObject jsonObject) {
            //

            new Thread(() -> {
                Log.d("->MyApplication", "onDataChange->currentThread=" + Thread.currentThread());
                Log.d("->MyApplication",
                        "onDataChange->(" + jsonObject.optString("action") + ")\n?" + jsonObject);

                if (BmobRealTimeData.ACTION_UPDATETABLE.equals(jsonObject.optString("action"))) {
                    JSONObject data = jsonObject.optJSONObject("data");

                    Log.d("->MyApplication", "onDataChange->?");
                    String username = data.optString("username");
                    String vin = data.optString("vin");

                    try {
                        mSyncSemaphore.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //?????????????
                    List<AutoInfo> list = AutoInfoLocalDBOperation
                            .queryBy(mContext,
                                    AutoInfoConstants.COLUMN_USERNAME + " = ? and "
                                            + AutoInfoConstants.COLUMN_VIN + " = ?",
                                    new String[] { username, vin });
                    if (list.size() != 0) {
                        Log.d("->MyApplication", "onDataChange->?");
                        //?
                        AutoInfo autoInfo = list.get(0);
                        String brand = autoInfo.getBrand();
                        String model = autoInfo.getModel();
                        String plateNum = autoInfo.getLicensePlateNum();
                        Message message = Message.obtain();
                        message.what = -1;
                        message.obj = brand + " " + model + " " + plateNum;
                        //???????
                        if (data.optInt("gasolineVolume") < 20) {//?<20%
                            //
                            mHandler.sendEmptyMessage(1);
                        }

                        //?15000?
                        //?1500?(??)?????

                        //???

                        //??5.E.a-c,????
                        //????
                        Semaphore semaphore = new Semaphore(1);
                        double mileage = data.optDouble("mileage");
                        //mileage?15000??
                        if (mileage >= 15000) {
                            try {
                                semaphore.acquire();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            String scanTime = data.optString("scanTime");
                            BmobQuery<MaInfo> query = new BmobQuery<MaInfo>();
                            query.addWhereEqualTo("username", username);
                            query.addWhereEqualTo("vin", vin);
                            query.addWhereLessThan("scanTime", scanTime);
                            query.addQueryKeys("scanTime");
                            query.order("-scanTime");
                            final Semaphore finalSemaphore = semaphore;
                            query.findObjects(mContext, new FindListener<MaInfo>() {
                                @Override
                                public void onSuccess(List<MaInfo> list) {
                                    int current = (int) mileage / 15000;
                                    Log.d("", "current=" + current + ",mileage=" + mileage);
                                    if (list.size() == 0) {
                                        message.obj = current;
                                        message.what = 2;
                                        mHandler.sendMessage(message);
                                    } else {
                                        double lastMileage = list.get(0).getMileage();
                                        int last = (int) lastMileage / 15000;
                                        if (current > last) {
                                            Message message = Message.obtain();
                                            message.obj = current;
                                            message.what = 2;
                                            mHandler.sendMessage(message);
                                        }
                                    }
                                    finalSemaphore.release();
                                }

                                @Override
                                public void onError(int i, String s) {
                                    finalSemaphore.release();
                                }
                            });
                        }

                        try {
                            semaphore.acquire();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //???????????
                        if (data.optString("enginePerfor").equals("")) {//?
                            mHandler.sendEmptyMessage(3);
                        }
                        if (data.optString("lamp").equals("")) {//?
                            mHandler.sendEmptyMessage(4);
                        }
                        if (data.optString("transmissionPerfor").equals("")) {//?
                            mHandler.sendEmptyMessage(5);
                        }
                        semaphore.release();

                        //????
                        mHandler.sendEmptyMessage(0);
                        mSyncSemaphore.release();
                        Log.d("++++++++++++++++++++", "++++++++++++++++");
                    } else {
                        mSyncSemaphore.release();
                    }
                }
            }).start();
        }
    });
}

From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java

/**
 * Try to connect to Clementine// ww w  .ja va2  s .c  o m
 *
 * @param message The Request Object. Stores the ip to connect to.
 */
@Override
public boolean createConnection(ClementineMessage message) {
    // Reset the connected flag
    mLastKeepAlive = 0;

    // Now try to connect and set the input and output streams
    boolean connected = super.createConnection(message);

    // Check if Clementine dropped the connection.
    // Is possible when we connect from a public ip and clementine rejects it
    if (connected && !mSocket.isClosed()) {
        // Now we are connected
        mLastSong = null;
        mLastState = App.mClementine.getState();

        // Setup the MediaButtonReceiver and the RemoteControlClient
        registerRemoteControlClient();

        // Register MediaButtonReceiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        App.mApp.registerReceiver(mMediaButtonBroadcastReceiver, filter);

        updateNotification();

        // The device shall be awake
        mWakeLock.acquire();

        // We can now reconnect MAX_RECONNECTS times when
        // we get a keep alive timeout
        mLeftReconnects = MAX_RECONNECTS;

        // Set the current time to last keep alive
        setLastKeepAlive(System.currentTimeMillis());

        // Until we get a new connection request from ui,
        // don't request the first data a second time
        mRequestConnect = ClementineMessageFactory.buildConnectMessage(message.getIp(), message.getPort(),
                message.getMessage().getRequestConnect().getAuthCode(), false,
                message.getMessage().getRequestConnect().getDownloader());

        // Save started transmitted bytes
        int uid = App.mApp.getApplicationInfo().uid;
        mStartTx = TrafficStats.getUidTxBytes(uid);
        mStartRx = TrafficStats.getUidRxBytes(uid);

        mStartTime = new Date().getTime();

        // Create a new thread for reading data from Clementine.
        // This is done blocking, so we receive the data directly instead of
        // waiting for the handler and still be able to send commands directly.
        mIncomingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isConnected() && !mIncomingThread.isInterrupted()) {
                    checkKeepAlive();

                    ClementineMessage m = getProtoc();
                    if (!m.isErrorMessage() || m.getErrorMessage() != ErrorMessage.TIMEOUT) {
                        Message msg = Message.obtain();
                        msg.obj = m;
                        msg.arg1 = PROCESS_PROTOC;
                        mHandler.sendMessage(msg);
                    }
                }
                Log.d(TAG, "reading thread exit");
            }
        });
        mIncomingThread.start();

    } else {
        sendUiMessage(new ClementineMessage(ErrorMessage.NO_CONNECTION));
    }

    return connected;
}

From source file:org.thialfihar.android.apg.ui.dialog.DeleteKeyDialogFragment.java

/**
 * Send message back to handler which is initialized in a activity
 *
 * @param what Message integer you want to send
 *//*from   w ww.  j  a v a 2  s  .co m*/
private void sendMessageToHandler(Integer what, Bundle data) {
    Message msg = Message.obtain();
    msg.what = what;
    if (data != null) {
        msg.setData(data);
    }
    try {
        mMessenger.send(msg);
    } catch (RemoteException e) {
        Log.w(Constants.TAG, "Exception sending message, Is handler present?", e);
    } catch (NullPointerException e) {
        Log.w(Constants.TAG, "Messenger is null!", e);
    }
}

From source file:org.ymkm.lib.controller.support.ControlledDialogFragment.java

@Override
public void onResume() {
    super.onResume();
    Activity activity = getActivity();/*  ww w .  j a  va2  s. co m*/
    if (activity instanceof ControllableActivity) {
        FragmentController controller = ((ControllableActivity) activity).getController();
        mControllerMessenger = controller.getMessenger();
    }

    if (null != mControllerMessenger) {
        Message m = Message.obtain();
        m.what = FragmentController.MSG_ATTACH_MESSAGE;
        m.arg1 = getControlId();
        m.obj = this;
        Bundle b = new Bundle();
        b.putString("controllableName", mControllableName);
        m.setData(b);
        try {
            mControllerMessenger.send(m);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.darshancomputing.BatteryIndicator.CurrentInfoFragment.java

private void toggleShowNotification() {
    SharedPreferences.Editor editor = activity.sp_store.edit();
    editor.putBoolean(BatteryInfoService.KEY_SHOW_NOTIFICATION,
            !activity.sp_store.getBoolean(BatteryInfoService.KEY_SHOW_NOTIFICATION, true));
    editor.commit();//from  w w  w.  j  a v  a 2 s.c o  m

    Message outgoing = Message.obtain();
    outgoing.what = BatteryInfoService.RemoteConnection.SERVICE_CANCEL_NOTIFICATION_AND_RELOAD_SETTINGS;
    try {
        serviceMessenger.send(outgoing);
    } catch (android.os.RemoteException e) {
    }
}

From source file:de.qspool.clementineremote.backend.ClementineService.java

private void sendConnectMessageIfPossible(Intent intent) {
    if (intent.hasExtra(EXTRA_STRING_IP)) {
        final String ip = intent.getStringExtra(EXTRA_STRING_IP);
        final int port = intent.getIntExtra(EXTRA_INT_PORT, 0);
        final int auth = intent.getIntExtra(EXTRA_INT_AUTH, 0);

        Message msg = Message.obtain();
        msg.obj = ClementineMessageFactory.buildConnectMessage(ip, port, auth, true, false);
        App.mClementineConnection.mHandler.sendMessage(msg);
    }/*from w ww  .j  a  va2  s  . c om*/
}

From source file:org.ntpsync.service.NtpSyncService.java

private void sendMessageToHandler(Integer arg1, Integer arg2, Bundle messageData) {
    Message msg = Message.obtain();
    msg.arg1 = arg1;//w  ww. ja  v a 2s . c  o  m
    if (arg2 != null) {
        msg.arg2 = arg2;
    }
    if (messageData != null) {
        msg.setData(messageData);
    }

    try {
        mMessenger.send(msg);
    } catch (RemoteException e) {
        Log.w(Constants.TAG, "Exception sending message, Is handler present?", e);
    } catch (NullPointerException e) {
        Log.w(Constants.TAG, "Messenger is null!", e);
    }
}

From source file:my.home.lehome.service.SendMsgIntentService.java

private void saveAndNotify(Intent intent, String result) {
    Context context = getApplicationContext();
    int rep_code = -1;
    String desc;//from   w  w  w .j a  v  a 2s.co m
    try {
        JSONObject jsonObject = new JSONObject(result);
        rep_code = jsonObject.getInt("code");
        desc = jsonObject.getString("desc");
    } catch (JSONException e) {
        e.printStackTrace();
        desc = context.getString(R.string.chat_error_json);
    }

    Messenger messenger;
    if (intent.hasExtra("messenger"))
        messenger = (Messenger) intent.getExtras().get("messenger");
    else
        messenger = null;

    Message repMsg = Message.obtain();
    repMsg.what = MSG_END_SENDING;

    ChatItem item = intent.getParcelableExtra("pass_item");
    ChatItem newItem = null;
    if (item != null) {
        if (rep_code == 200) {
            item.setState(Constants.CHATITEM_STATE_SUCCESS);
            DBStaticManager.updateChatItem(context, item);
        } else {
            if (rep_code == 415) {
                item.setState(Constants.CHATITEM_STATE_SUCCESS);
            } else {
                item.setState(Constants.CHATITEM_STATE_ERROR);
            }
            DBStaticManager.updateChatItem(context, item);

            newItem = new ChatItem();
            newItem.setContent(desc);
            newItem.setType(ChatItemConstants.TYPE_SERVER);
            newItem.setState(Constants.CHATITEM_STATE_ERROR); // always set true
            newItem.setDate(new Date());
            DBStaticManager.addChatItem(context, newItem);
        }
    } else {
        if (rep_code != 200) {
            Log.d(TAG, result);
            newItem = new ChatItem();
            newItem.setContent(getString(R.string.loc_send_error) + ":" + desc); // TODO - not only loc report
            newItem.setType(ChatItemConstants.TYPE_SERVER);
            newItem.setState(Constants.CHATITEM_STATE_SUCCESS); // always set true
            newItem.setDate(new Date());
            DBStaticManager.addChatItem(context, newItem);
        }
    }

    Log.d(TAG, "dequeue item: " + item);
    if (item == null)
        return;

    Bundle bundle = new Bundle();
    bundle.putParcelable("item", item);
    if (newItem != null)
        bundle.putParcelable("new_item", newItem);
    bundle.putInt("rep_code", rep_code);
    if (messenger != null) {
        repMsg.setData(bundle);
        try {
            messenger.send(repMsg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else {
        Log.d(TAG, "messager is null, send broadcast instead:" + ACTION_SEND_MSG_END);
        Intent newIntent = new Intent(ACTION_SEND_MSG_END);
        newIntent.putExtras(bundle);
        sendBroadcast(newIntent);
    }
}

From source file:com.yangtsaosoftware.pebblemessenger.services.MessageProcessingService.java

@Override
public void onCreate() {
    super.onCreate();
    phone_is_ontalking = false;/*from   w w w. ja  v a  2 s  .  c  o m*/
    loadPrefs();
    Thread proceedthread = new ProcessThread();
    proceedthread.start();
    messageHandler = new MessageHandler(Looper.getMainLooper());
    mMessenger = new Messenger(messageHandler);
    MessageProcessingService._context = getApplicationContext();
    fdb = new FontDbHandler(_context);
    fdb.open();
    mdb = new MessageDbHandler(_context);
    mdb.open();
    bindService(new Intent(this, PebbleCenter.class), connToPebbleCenter, Context.BIND_AUTO_CREATE);
    BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int command = intent.getIntExtra(Constants.BROADCAST_COMMAND, Constants.BROADCAST_PREFER_CHANGED);
            switch (command) {
            case Constants.BROADCAST_PREFER_CHANGED:
                loadPrefs();
                break;
            case Constants.BROADCAST_CALL_INCOMING:
                String number = intent.getStringExtra(Constants.BROADCAST_PHONE_NUM);
                String name = intent.getStringExtra(Constants.BROADCAST_NAME);

                if (callQuietEnable) {
                    Calendar c = Calendar.getInstance();
                    Calendar now = new GregorianCalendar(0, 0, 0, c.get(Calendar.HOUR_OF_DAY),
                            c.get(Calendar.MINUTE));
                    Constants.log(TAG_NAME, "Checking quiet hours. Now: " + now.toString() + " vs "
                            + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
                    if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
                        Constants.log(TAG_NAME, "Time is before or after the quiet hours time. Returning.");
                        addNewCall(number, name, MessageDbHandler.NEW_ICON);
                    } else {
                        Bundle b = new Bundle();
                        b.putLong(MessageDbHandler.COL_CALL_ID,
                                addNewCall(number, name, MessageDbHandler.OLD_ICON));
                        b.putString(MessageDbHandler.COL_CALL_NUMBER, number);
                        b.putString(MessageDbHandler.COL_CALL_NAME, name);
                        Message innerMsg = processHandler.obtainMessage(INNER_CALL_PROCEED);
                        innerMsg.setData(b);
                        processHandler.sendMessage(innerMsg);
                    }
                } else {
                    Bundle b = new Bundle();
                    if (phone_is_ontalking) {
                        b.putString(MessageDbHandler.COL_MESSAGE_APP, "Call");
                        b.putString(MessageDbHandler.COL_MESSAGE_CONTENT, name + "\n" + number);
                        addNewCall(number, name, MessageDbHandler.NEW_ICON);
                        b.putLong(MessageDbHandler.COL_MESSAGE_ID, addNewMessage(b, MessageDbHandler.OLD_ICON));
                        Message innerMsg = processHandler.obtainMessage(INNER_MESSAGE_PROCEED);
                        innerMsg.setData(b);
                        processHandler.sendMessage(innerMsg);
                    } else {
                        b.putLong(MessageDbHandler.COL_CALL_ID,
                                addNewCall(number, name, MessageDbHandler.OLD_ICON));
                        b.putString(MessageDbHandler.COL_CALL_NUMBER, number);
                        b.putString(MessageDbHandler.COL_CALL_NAME, name);
                        Message innerMsg = processHandler.obtainMessage(INNER_CALL_PROCEED);
                        innerMsg.setData(b);
                        processHandler.sendMessage(innerMsg);
                    }
                }
                break;
            case Constants.BROADCAST_CALL_HOOK:
                phone_is_ontalking = true;
                break;
            case Constants.BROADCAST_CALL_IDLE:
                phone_is_ontalking = false;
                break;
            case Constants.BROADCAST_SMS_INCOMING: {
                Message msg = Message.obtain();
                msg.what = MSG_NEW_MESSAGE;
                Bundle b = new Bundle();
                b.putString(MessageDbHandler.COL_MESSAGE_APP, "SMS");
                b.putString(MessageDbHandler.COL_MESSAGE_CONTENT,
                        intent.getStringExtra(Constants.BROADCAST_SMS_BODY));
                msg.setData(b);
                messageHandler.sendMessage(msg);
            }
            }
        }
    };
    IntentFilter intentFilter = new IntentFilter(MessageProcessingService.class.getName());
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(br, intentFilter);

}