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(Handler h, int what, Object obj) 

Source Link

Document

Same as #obtain() , but sets the values of the target, what, and obj members.

Usage

From source file:com.google.samples.apps.iosched.ui.SessionsFragment.java

void requestQueryUpdate(String query) {
    mHandler.removeMessages(MESSAGE_QUERY_UPDATE);
    mHandler.sendMessageDelayed(Message.obtain(mHandler, MESSAGE_QUERY_UPDATE, query),
            QUERY_UPDATE_DELAY_MILLIS);
}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

private void updateUILocation(Location location) {
    // We're sending the update to a handler which then updates the UI with the new
    // location.//from  ww  w.j ava  2  s.  com
    Message.obtain(mHandler, UPDATE_LATLNG, location.getLatitude() + ", " + location.getLongitude())
            .sendToTarget();

    // Bypass reverse-geocoding only if the Geocoder service is available on the device.
    if (mGeocoderAvailable)
        doReverseGeocoding(location);
}

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

/**
 * Finish response by freeing resource and sending message to the client <br>
 * This method can(must) be called after overriding {@link #onResponse(LLHttpClientBaseResponse)}.
 * /*from  w  ww  . j a va2  s  .c  o  m*/
 * @param _msg
 *            the message that will be sent through {@link #mHandler}
 * @param _r
 *            the {@link LLAbstractResponse} or a decorated subclass of it that contains information after requesting.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected void finishResponse(int _msg, LLAbstractResponse _r) throws IOException {
    LL.i(":) " + getClass().getSimpleName() + " is successfully:" + _r.toString());
    if (mHandler != null) {
        Message msg = Message.obtain(mHandler, _msg, _r);
        msg.sendToTarget();
    }
    // Free http's thing i.e stream and client.
    // If error at releasing, the request seems failed as well.
    _r.release();
}

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

@Override
protected void onPostExecute(Exception _result) {
    if (_result != null) {
        LL.e(":( Faild response.");
        if (mHandler != null) {
            Message.obtain(mHandler, REQUEST_FAILED, _result).sendToTarget();
        }//from w w w.  j a  v  a2s  .com
    }
}

From source file:com.google.android.gcm.demo.app.BluetoothHDPActivity.java

private void sendMessageWithDevice(int what) {
    if (mHealthService == null) {
        Log.d(TAG, "Health Service not connected.");
        return;//from  ww  w  . j ava2  s  .c om
    }

    try {
        mHealthService.send(Message.obtain(null, what, mDevice));
    } catch (RemoteException e) {
        Log.w(TAG, "Unable to reach service.");
        e.printStackTrace();
    }
}

From source file:com.example.android.location.BaselineActivity.java

private void updateUILocation(Location location) {
    // We're sending the update to a handler which then updates the UI with the new
    // location.//from  w w w .jav a2s  .com
    cal = Calendar.getInstance();

    double instantSpeed = location.getSpeed();

    speedBuffer.add(instantSpeed);
    speedBuffer.remove(0);

    if (gotInfinity) {
        if (instantSpeed > 0.01 && speedBuffer.get(0) > 0.01)
            speedBuffer.set(1, (speedBuffer.get(0) + speedBuffer.get(2)) / 2);

        gotInfinity = false;
    }

    if (instantSpeed < 0.01 && speedBuffer.get(1) > 0.01) {
        if (gotInfinity == false)
            gotInfinity = true;
    }
    currPace = 1 / (instantSpeed * 0.0372);

    int s = (int) (cal.getTimeInMillis() / 1000);
    int timePassed = 0;
    if (s > seconds)
        timePassed = s - seconds;
    else
        timePassed = s - seconds + 60;

    seconds = s;
    if (fileOpen) {
        totalSpeeds += instantSpeed * timePassed;
        measureCount += timePassed;
        if (measureCount > 0)
            averageSpeed = totalSpeeds / measureCount;
        //currPace = location.getLatitude();

        Message.obtain(mHandler, UPDATE_AVG_SPEED, averageSpeed + "").sendToTarget();
    }
    //minPace = Double.parseDouble(mMinPace.getText().toString());
    // maxPace = Double.parseDouble(mMaxPace.getText().toString());

    Message.obtain(mHandler, UPDATE_LATLNG, location.getLatitude() + ", " + location.getLongitude())
            .sendToTarget();
    Message.obtain(mHandler, UPDATE_SPEED, currPace + "").sendToTarget();

    if (currPace > maxPace) {
        maxPace = currPace;
        mMaxPace.setText(maxPace + "");
    }

    if (currPace < minPace) {
        minPace = currPace;
        mMinPace.setText(minPace + "");
    }
    writeToFile();

    // Bypass reverse-geocoding only if the Geocoder service is available on the device.
    if (mGeocoderAvailable)
        doReverseGeocoding(location);
}

From source file:cn.com.loopj.android.http.AsyncHttpResponseHandler.java

/**
 * Helper method to create Message instance from handler
 *
 * @param responseMessageId   constant to identify Handler message
 * @param responseMessageData object to be passed to message receiver
 * @return Message instance, should not be null
 *///from  www .  j  a v a 2s  . co m
protected Message obtainMessage(int responseMessageId, Object responseMessageData) {
    return Message.obtain(handler, responseMessageId, responseMessageData);
}

From source file:com.cleverzone.zhizhi.capture.CaptureActivity.java

private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
    // Bitmap isn't used yet -- will be used soon
    if (handler == null) {
        savedResultToShow = result;/*from   w  ww  .  j a v a2 s  .  co  m*/
    } else {
        if (result != null) {
            savedResultToShow = result;
        }
        if (savedResultToShow != null) {
            Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
            handler.sendMessage(message);
        }
        savedResultToShow = null;
    }
}

From source file:com.willhauck.linconnectclient.SettingsActivity.java

@SuppressLint("SimpleDateFormat")
private void setupSimplePreferencesScreen() {
    // Load preferences
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);

    // Add preferences from XML
    addPreferencesFromResource(R.xml.pref_general);
    bindPreferenceSummaryToValue(findPreference("pref_ip"));

    // Preference Categories
    serverCategory = ((PreferenceCategory) findPreference("cat_servers"));

    // Preferences
    refreshPreference = ((Preference) findPreference("pref_refresh"));
    serverCategory.removePreference(refreshPreference);

    loadingPreference = ((Preference) findPreference("pref_loading"));
    serverCategory.removePreference(loadingPreference);

    Preference prefEnable = findPreference("pref_enable");
    prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override/*  ww w .  j a v a2s  . c o m*/
        public boolean onPreferenceClick(Preference arg0) {
            // If Android 4.3+, open Notification Listener settings,
            // otherwise open accessibility settings
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0);
            } else {
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
            }
            return true;
        }
    });

    ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference arg0, Object arg1) {
            // Update Custom IP address summary
            arg0.setSummary((String) arg1);

            refreshServerList();

            // Create and send test notification
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            Object[] notif = new Object[3];
            notif[0] = "Hello from Android!";
            notif[1] = "Test succesful @ " + sf.format(new Date());
            notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
            new TestTask().execute(notif);

            return true;
        }
    });

    Preference prefDownload = findPreference("pref_download");
    prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Create share dialog with server download URL
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,
                    "Download LinConnect server @ https://github.com/hauckwill/linconnect-server");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
            return true;
        }
    });

    Preference prefApplication = findPreference("pref_application");
    prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open application settings screen
            Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class);

            startActivity(intent);
            return true;
        }
    });

    Preference prefDonateBitcoin = findPreference("pref_donate_btc");
    prefDonateBitcoin.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            try {
                // Open installed Bitcoin wallet if possible
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(
                        "bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect"));
                startActivity(intent);
            } catch (Exception e) {
                // Otherwise, show dialog with Bitcoin address
                EditText input = new EditText(SettingsActivity.this);
                input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                input.setEnabled(false);

                new AlertDialog.Builder(SettingsActivity.this).setTitle("Bitcoin Address")
                        .setMessage(
                                "Please donate to the following Bitcoin address. Thank you for the support.")
                        .setView(input)
                        .setPositiveButton("Copy Address", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                        Context.CLIPBOARD_SERVICE);
                                clipboard.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                            }
                        }).setNegativeButton("Okay", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
            }
            return true;
        }
    });

    Preference prefGooglePlus = findPreference("pref_google_plus");
    prefGooglePlus.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Google Plus page
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://plus.google.com/114633032648182423928/posts"));
            startActivity(intent);
            return true;
        }
    });

    Preference prefDonatePlay = findPreference("pref_donate_play");
    prefDonatePlay.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Donation Key app on Play Store
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.willhauck.donation"));
            startActivity(intent);
            return true;
        }
    });

    // Create handler to process a detected server
    serverFoundHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {

                javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj);

                // Get info about server
                String name = serviceInfo.getName();
                String port = String.valueOf(serviceInfo.getPort());
                String ip = serviceInfo.getHostAddresses()[0];

                // Create a preference representing the server
                Preference p = new Preference(SettingsActivity.this);
                p.setTitle(name);
                p.setSummary(ip + ":" + port);

                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference arg0) {
                        refreshServerList();

                        // Save IP address in preferences
                        Editor e = sharedPreferences.edit();
                        e.putString("pref_ip", arg0.getSummary().toString());
                        e.apply();

                        // Create and send test notification
                        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");

                        Object[] notif = new Object[3];
                        notif[0] = "Hello from Android!";
                        notif[1] = "Test succesful @ " + sf.format(new Date());
                        notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

                        new TestTask().execute(notif);

                        return true;
                    }

                });

                // Add preference to server list if it doesn't already exist
                boolean found = false;
                for (int i = 0; i < serverCategory.getPreferenceCount(); i++) {
                    if (serverCategory.getPreference(i) != null
                            && serverCategory.getPreference(i).getTitle() != null
                            && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) {
                        found = true;
                    }
                }
                if (!found) {
                    serverCategory.addPreference(p);
                }

                refreshServerList();

                // Remove loading indicator, add refresh indicator if it
                // isn't already there
                if (findPreference("pref_loading") != null)
                    serverCategory.removePreference(findPreference("pref_loading"));
                if (findPreference("pref_refresh") == null)
                    serverCategory.addPreference(refreshPreference);

            }
            return true;
        }
    });

    // Create task to scan for servers
    class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> {

        @Override
        protected void onPreExecute() {
            // Remove refresh preference, add loading preference
            if (findPreference("pref_refresh") != null)
                serverCategory.removePreference(refreshPreference);
            serverCategory.addPreference(loadingPreference);

            try {
                mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener);
            } catch (Exception e) {
            }

            refreshServerList();

        }

        @Override
        protected Boolean doInBackground(String... notif) {
            WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
            int intaddr = wifiinfo.getIpAddress();

            // Ensure there is an active Wifi connection
            if (intaddr != 0) {
                byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
                        (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByAddress(byteaddr);
                } catch (UnknownHostException e1) {
                }

                // Create Multicast lock (required for JmDNS)
                mMulticastLock = mWifiManager.createMulticastLock("LinConnect");
                mMulticastLock.setReferenceCounted(true);
                mMulticastLock.acquire();

                try {
                    mJmDNS = JmDNS.create(addr, "LinConnect");
                } catch (IOException e) {
                }

                // Create listener for detected servers
                ServerListener = new ServiceListener() {

                    @Override
                    public void serviceAdded(ServiceEvent arg0) {
                        final String name = arg0.getName();
                        // Send the server data to the handler, delayed by
                        // 500ms to ensure all information is read
                        serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name),
                                500);
                    }

                    @Override
                    public void serviceRemoved(ServiceEvent arg0) {
                    }

                    @Override
                    public void serviceResolved(ServiceEvent arg0) {
                        mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1);
                    }
                };
                mJmDNS.addServiceListener(jmDnsServiceType, ServerListener);

                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                // Notify user if there is no connection
                if (findPreference("pref_loading") != null) {
                    serverCategory.removePreference(findPreference("pref_loading"));
                    serverCategory.addPreference(refreshPreference);

                }
                Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show();
            }
        }
    }

    refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {
            new ServerScanTask().execute();
            return true;
        }

    });

    // Start scanning for servers
    new ServerScanTask().execute();
}

From source file:org.altusmetrum.AltosDroid.AltosDroid.java

private void connectDevice(Intent data) {
    // Get the device MAC address
    String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
    // Get the BLuetoothDevice object
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    // Attempt to connect to the device
    try {//from   w  w  w .  j  av a 2  s . c o  m
        if (D)
            Log.d(TAG, "Connecting to " + device.getName());
        mService.send(Message.obtain(null, TelemetryService.MSG_CONNECT, device));
    } catch (RemoteException e) {
    }
}