Example usage for android.os Message setData

List of usage examples for android.os Message setData

Introduction

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

Prototype

public void setData(Bundle data) 

Source Link

Document

Sets a Bundle of arbitrary data values.

Usage

From source file:info.guardianproject.mrapp.server.YouTubeSubmit.java

public void asyncUpload(final File videoFile, final String contentType, final String uploadEndPoint) {
    new Thread(new Runnable() {
        @Override/*w  w w  .  ja v  a2s. c o  m*/
        public void run() {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            msg.setData(bundle);
            msg.what = 888;

            int submitCount = 0;
            try {
                while (submitCount <= MAX_RETRIES && videoId == null) {
                    try {
                        submitCount++;
                        videoId = startUpload(videoFile, contentType, uploadEndPoint);
                        assert videoId != null;
                        break;
                    } catch (Internal500ResumeException e500) { // TODO - this should not really happen
                        if (submitCount < MAX_RETRIES) {
                            Log.w(LOG_TAG, e500.getMessage());
                            Log.d(LOG_TAG, String.format("Upload retry :%d.", submitCount, Locale.US));
                        } else {
                            Log.d(LOG_TAG, "Giving up");
                            Log.e(LOG_TAG, e500.getMessage());
                            throw new IOException(e500.getMessage());
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                msg.what = -1;

                handler.sendMessage(msg);
                return;
            } catch (YouTubeAccountException e) {
                e.printStackTrace();
                msg.what = -1;

                bundle.putString("err", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (SAXException e) {
                e.printStackTrace();
                msg.what = -1;

                bundle.putString("err", e.getMessage());
                handler.sendMessage(msg);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
                msg.what = -1;

                bundle.putString("err", e.getMessage());
                handler.sendMessage(msg);
            }

            bundle.putString("videoId", videoId);
            handler.sendMessage(msg);
        }
    }).start();
}

From source file:ca.spencerelliott.mercury.Changesets.java

private synchronized void startThread() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //Create the thread that will process the incoming feed
    load_thread = new Thread() {
        @Override/* w ww.j  a va2 s. c  o  m*/
        public void run() {
            changesets_list.clear();

            DatabaseHelper db_helper = DatabaseHelper.getInstance(getApplicationContext());
            EncryptionHelper encrypt_helper = EncryptionHelper.getInstance("DEADBEEF".toCharArray(),
                    new byte[] { 'L', 'O', 'L' });

            //Get the repository information from the local database
            Beans.RepositoryBean repo_type = db_helper.getRepository(repo_id, encrypt_helper);
            AtomHandler feed_handler = null;

            //Detect the type of repository and create a parser based on that
            switch (repo_type.getType()) {
            case Mercury.RepositoryTypes.HGSERVE:
                feed_handler = new HGWebAtomHandler();
                break;
            case Mercury.RepositoryTypes.GOOGLECODE:
                feed_handler = new GoogleCodeAtomHandler();
                break;
            case Mercury.RepositoryTypes.BITBUCKET:
                feed_handler = new BitbucketAtomHandler();
                break;
            case Mercury.RepositoryTypes.CODEPLEX:
                feed_handler = new CodePlexAtomHandler();
                break;
            }

            HttpURLConnection conn = null;
            boolean connected = false;

            try {
                // XXX We need to use our own factory to make all ssl certs work
                HttpsURLConnection.setDefaultSSLSocketFactory(NaiveSSLSocketFactory.getSocketFactory());

                String repo_url_string = (repo_type.getUrl().endsWith("/") || repo_type.getUrl().endsWith("\\")
                        ? feed_handler
                                .formatURL(repo_type.getUrl().substring(0, repo_type.getUrl().length() - 1))
                        : feed_handler.formatURL(repo_type.getUrl()));

                switch (repo_type.getType()) {
                case Mercury.RepositoryTypes.BITBUCKET:
                    //Only add the token if the user requested it
                    if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.TOKEN)
                        repo_url_string = repo_url_string + "?token=" + repo_type.getSSHKey();
                    break;
                }

                URL repo_url = new URL(repo_url_string);
                conn = (HttpURLConnection) repo_url.openConnection();

                //Check to see if the user enabled HTTP authentication
                if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.HTTP) {
                    //Get their username and password
                    byte[] decrypted_info = (repo_type.getUsername() + ":" + repo_type.getPassword())
                            .getBytes();

                    //Add the header to the http request
                    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes(decrypted_info));
                }
                conn.connect();
                connected = true;
            } catch (ClientProtocolException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("There was a problem with the HTTP protocol");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (IOException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("Server did not respond with a valid HTTP response");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (NullPointerException e3) {

            } catch (Exception e) {

            }

            BufferedReader reader = null;

            //Create a new reader based on the information retrieved
            if (connected) {
                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Make sure both the feed handler and info loaded from the web are not null
            if (reader != null && feed_handler != null) {
                try {
                    Xml.parse(reader, feed_handler);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Stored beans in the devices database
            ArrayList<Beans.ChangesetBean> stored_beans = null;

            if (prefs.getBoolean("caching", false)) {
                long last_insert = db_helper.getHighestID(DatabaseHelper.DB_TABLE_CHANGESETS, repo_id);

                if (last_insert >= 0) {
                    //Get all of the stored changesets
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                    String rev_id = "";

                    //Try to find the revision id of the bean that has the id of the last inserted value
                    for (Beans.ChangesetBean b : stored_beans) {
                        if (b.getID() == last_insert) {
                            rev_id = b.getRevisionID();
                            break;
                        }
                    }

                    //Trim the list starting from this revision
                    feed_handler.trimStartingFromRevision(rev_id);
                }
            }

            //Create a new bundle for the progress
            Bundle progress_bundle = new Bundle();

            //Retreive all the beans from the handler
            ArrayList<Beans.ChangesetBean> beans = feed_handler.getAllChangesets();
            int bean_count = beans.size();

            //Store the amount of changesets
            progress_bundle.putInt("max", bean_count);

            //Create a new message and store the bundle and what type of message it is
            Message msg = new Message();
            msg.setData(progress_bundle);
            msg.what = SETUP_COUNT;
            list_handler.sendMessage(msg);

            //Add each of the beans to the list
            for (int i = 0; i < bean_count; i++) {
                String commit_text = beans.get(i).getTitle();
                Date commit_date = new Date(beans.get(i).getUpdated());
                changesets_list.add(createChangeset(
                        (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                        beans.get(i).getRevisionID() + " - " + commit_date.toLocaleString()));

                //Store the current progress of the changeset loading
                progress_bundle.putInt("progress", i);

                //Reuse the old message and send an update progress message
                msg = new Message();
                msg.setData(progress_bundle);
                msg.what = UPDATE_PROGRESS;
                list_handler.sendMessage(msg);
            }

            //Get the current count of changesets and the shared preferences
            long changeset_count = db_helper.getChangesetCount(repo_id);

            if (prefs.getBoolean("caching", false)) {
                //Get all of the stored beans from the device if not already done
                if (stored_beans == null)
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                //Add all the changesets from the device
                for (Beans.ChangesetBean b : stored_beans) {
                    changesets_list.add(createChangeset(
                            (b.getTitle().length() > 30 ? (b.getTitle().substring(0, 30)) + "..."
                                    : b.getTitle()),
                            b.getRevisionID() + " - " + new Date(b.getUpdated()).toLocaleString()));
                }

                //Reverse the list so the oldest changesets are stored first
                Collections.reverse(beans);

                //Iterate through each bean and add it to the device's database
                for (Beans.ChangesetBean b : beans) {
                    db_helper.insert(b, repo_id);
                }

                //Get the amount of changesets allowed to be stored on the device
                int max_changes = Integer.parseInt(prefs.getString("max_changesets", "-1"));

                //Delete the oldest changesets if too many have been stored
                if (changeset_count > max_changes) {
                    db_helper.deleteNumChangesets(repo_id, (changeset_count - max_changes));
                }
            } else if (changeset_count > 0) {
                //Since the user does not have caching enabled, delete the changesets
                db_helper.deleteAllChangesets(repo_id);
            }

            //Update the tables to the newest revision
            if (!beans.isEmpty())
                db_helper.updateLastRev(repo_id, beans.get(0).getRevisionID());

            //Add all of the data to the changeset list
            changesets_data.addAll(beans);

            if (prefs.getBoolean("caching", false))
                changesets_data.addAll(stored_beans);

            //Clean up the sql connection
            db_helper.cleanup();
            db_helper = null;

            //Notify the handler that the loading of the list was successful
            list_handler.sendEmptyMessage(SUCCESSFUL);
        }
    };

    //Start the thread
    load_thread.start();
}

From source file:com.google.ytd.SubmitActivity.java

public void asyncUpload(final Uri uri, final Handler handler) {
    new Thread(new Runnable() {
        @Override//from w ww .j  av a 2  s.  co m
        public void run() {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            msg.setData(bundle);

            String videoId = null;
            int submitCount = 0;
            try {
                while (submitCount <= MAX_RETRIES && videoId == null) {
                    try {
                        submitCount++;
                        videoId = startUpload(uri);
                        assert videoId != null;
                    } catch (Internal500ResumeException e500) { // TODO - this should not really happen
                        if (submitCount < MAX_RETRIES) {
                            Log.w(LOG_TAG, e500.getMessage());
                            Log.d(LOG_TAG, String.format("Upload retry :%d.", submitCount));
                        } else {
                            Log.d(LOG_TAG, "Giving up");
                            Log.e(LOG_TAG, e500.getMessage());
                            throw new IOException(e500.getMessage());
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (YouTubeAccountException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
                return;
            } catch (SAXException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
                bundle.putString("error", e.getMessage());
                handler.sendMessage(msg);
            }

            bundle.putString("videoId", videoId);
            handler.sendMessage(msg);
        }
    }).start();
}

From source file:com.vuze.android.remote.service.VuzeService.java

public void sendStuff(int what, String s) {
    for (int i = mClients.size() - 1; i >= 0; i--) {
        try {/*from w w  w. j ava  2  s  . c om*/
            Message obtain = Message.obtain(null, what, 0, 0);
            if (s != null) {
                Bundle bundle = new Bundle();
                bundle.putString("data", s);
                obtain.setData(bundle);
            }
            mClients.get(i).send(obtain);
        } catch (RemoteException e) {
            // The client is dead.  Remove it from the list;
            // we are going through the list from back to front
            // so this is safe to do inside the loop.
            mClients.remove(i);
        }
    }
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/*********************************
 * /*from w w w .  ja v  a  2  s .co m*/
 * Get Artist Events
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getArtistEvents() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Artist Cursor
     */
    artistCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ARTIST_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String artistNameFiltered = null;
    String artistConcertFileName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLArtistEventHandler xmlHandler = new XMLArtistEventHandler();
    xmlHandler.myLocation = this.myLocation;
    xmlReader.setContentHandler(xmlHandler);

    /*
     * Set Distance Limit
     */
    xmlHandler.MAX_DISTANCE = this.concertRadius;

    /*
     * Loop through the artists
     */
    artistCursor.moveToFirst();
    for (int i = 0; i < artistCursor.getCount(); i++) {
        /*
         * Get artist name
         */
        artistName = artistCursor.getString(artistCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST));
        if (artistName.equals("<unknown>")) {
            artistCursor.moveToNext();
            continue;
        }
        artistNameFiltered = filterString(artistName);
        artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName);

        /*
         * UI feedback
         */
        Bundle data = new Bundle();
        data.putString("info", artistName);
        Message msg = new Message();
        msg.setData(data);
        ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);

        /*
         * If we dont have yet or info is too old, update the concert info of this artist
         */
        if (hasConcertInfo(artistName) == false || concertInfoNeedsUpdate(artistName) == true) {
            Log.i("INET", "Getting concert info from LastFM");
            if (hasConcertInfo(artistName) == false)
                Log.i("INET", "Because there is no concert info yet");
            if (concertInfoNeedsUpdate(artistName) == true)
                Log.i("INET", "Because Info is too old");

            File artistConcertFile = new File(artistConcertFileName);
            if (!artistConcertFile.exists()) {
                try {
                    artistConcertFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            URL lastFmApiRequest;
            try {
                lastFmApiRequest = new URL(
                        this.LAST_FM_API_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
                BufferedInputStream bufferedURLStream = new BufferedInputStream(lastFmApiRequest.openStream());
                BufferedOutputStream bufferedFileWriter = new BufferedOutputStream(
                        new FileOutputStream(artistConcertFile));

                byte[] buf = new byte[1024];
                int len;
                while ((len = bufferedURLStream.read(buf)) >= 0)
                    bufferedFileWriter.write(buf, 0, len);
                bufferedURLStream.close();
                bufferedFileWriter.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        /*
         * get event list from cached XML files
         */
        File artistConcertFile = new File(artistConcertFileName);
        if (artistConcertFile.exists() && artistConcertFile.length() > 0) {
            try {
                BufferedReader xmlFileReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(artistConcertFile)));
                xmlHandler.resetList();
                xmlHandler.artist = artistName;
                xmlReader.parse(new InputSource(xmlFileReader));
                insertListInListByDate(xmlHandler.artistEventList);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        artistCursor.moveToNext();
    }

    /*
     * Debug
     */
    ArtistEvent artistEventDebug = null;
    if (!artistEventList.isEmpty()) {
        artistEventList.getFirst();
        ListIterator<ArtistEvent> listIterator = artistEventList.listIterator(0);
        for (artistEventDebug = listIterator.next(); listIterator
                .hasNext() == true; artistEventDebug = listIterator.next()) {
            if (artistEventDebug != null)
                Log.i("DBG", artistEventDebug.date + " " + artistEventDebug.city);
            //   Log.i("DBG", artistEventDebug.date+" "+artistEventDebug.city+" "+artistEventDebug.artist);
            else
                Log.i("DBG", "NULL");
        }
    }
    /*
     * Update Adapter
     */
    eventLinkedListAdapter = new EventLinkedListAdapter(context, R.layout.eventlist_item, artistEventList);
    if (eventLinkedListAdapter == null)
        Log.i("NULL", "NULL");
    ((RockPlayer) context).updateEventListHandler.sendEmptyMessage(0);

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);
}

From source file:com.layer8apps.CalendarHandler.java

/************
 *  PURPOSE: Handles the primary thread in the service
 *  ARGUMENTS: Intent intent//from  ww w .ja  va  2  s.co  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:dk.kk.ibikecphlib.util.HttpUtils.java

public static Message JSONtoMessage(JsonNode result) {
    Message ret = new Message();
    Bundle data = new Bundle();
    if (result != null) {
        if (result.has("success"))
            data.putBoolean("success", result.get("success").asBoolean());
        if (result.has("info"))
            data.putString("info", result.get("info").asText());
        if (result.has("has_password"))
            data.putBoolean("has_password", result.get("has_password").asBoolean());
        if (result.has("invalid_token")) {
            if (result.get("invalid_token").asBoolean()) {
                data.putBoolean("invalid_token", result.get("invalid_token").asBoolean());
                IBikeApplication.logoutWrongToken();
            }/*from  w w  w.j av  a  2  s.com*/
        }
        /*if (result.has("errors"))
        data.putString("errors", result.get("errors").get(0).asText());*/
    }
    if (result != null && result.has("data")) {
        JsonNode dataNode = result.get("data");
        if (dataNode != null) {
            if (dataNode.has("id"))
                data.putInt("id", dataNode.get("id").asInt());
            if (dataNode.has("auth_token"))
                data.putString("auth_token", dataNode.get("auth_token").asText());
            if (dataNode.has("signature"))
                data.putString("signature", dataNode.get("signature").asText());
            if (dataNode.has("provider"))
                data.putString("provider", dataNode.get("provider").asText());
            /*if (dataNode.has("errors"))
                data.putString("errors", dataNode.get("errors").get(0).asText());*/
        }
    }

    ret.setData(data);
    return ret;
}

From source file:com.softminds.matrixcalculator.OperationFragments.InverseFragment.java

public void RunAndGetDeterminantWithAdjoint(final int i, final ProgressDialog progressDialog) {
    Runnable runnable = new Runnable() {
        @Override// w  w  w.  j a v  a2 s  .co m
        public void run() {
            Message message = new Message();
            Bundle bundle = new Bundle();
            float detr = (float) SquareList.get(i).getDeterminant(progressDialog);
            if (detr == 0.0f) {
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), R.string.NoInverse, Toast.LENGTH_SHORT).show();
                    }
                }, 0);
                progressDialog.dismiss();
            } else {
                progressDialog.setProgress(0);
                bundle.putFloat("DETERMINANT", detr);
                MatrixV2 res = SquareList.get(i).getAdjoint(progressDialog);
                bundle.putAll(res.getDataBundled());
                message.setData(bundle);
                myHandler.sendMessage(message);
            }

        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
}

From source file:com.zia.freshdocs.widget.adapter.CMISAdapter.java

/**
 * Download the content for the given NodeRef
 * /* w  w w . j  av a  2s .c o  m*/
 * @param ref
 * @param handler
 */
protected void downloadContent(final NodeRef ref, final Handler handler) {
    startProgressDlg(false);
    mProgressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue());

    mDlThread = new ChildDownloadThread(handler, new Downloadable() {
        public Object execute() {
            File f = null;

            try {
                CMISApplication app = (CMISApplication) getContext().getApplicationContext();
                URL url = new URL(ref.getContent());
                String name = ref.getName();
                long fileSize = ref.getContentLength();
                f = app.getFile(name, fileSize);

                if (f != null && f.length() != fileSize) {
                    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

                    FileOutputStream fos = new FileOutputStream(f);
                    InputStream is = mCmis.get(url.getPath());

                    byte[] buffer = new byte[BUF_SIZE];
                    int len = is.read(buffer);
                    int total = len;
                    Message msg = null;
                    Bundle b = null;

                    while (len != -1) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("progress", total);
                        msg.setData(b);
                        handler.sendMessage(msg);

                        fos.write(buffer, 0, len);
                        len = is.read(buffer);
                        total += len;

                        if (Thread.interrupted()) {
                            fos.close();
                            f = null;
                            throw new InterruptedException();
                        }
                    }

                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                Log.e(CMISAdapter.class.getSimpleName(), "", e);
            }

            return f;
        }
    });
    mDlThread.start();
}

From source file:fr.mixit.android.ui.fragments.MemberDetailsFragment.java

protected void refreshMemberData() {
    if (mIsBound && mServiceReady) {
        setRefreshMode(true);//from  w  w  w  .  j  a  v  a2s.  c o  m

        final Message msg = Message.obtain(null, MixItService.MSG_MEMBER, 0, 0);
        msg.replyTo = mMessenger;
        final Bundle b = new Bundle();
        b.putInt(MixItService.EXTRA_ID, mMemberId);
        msg.setData(b);
        try {
            mService.send(msg);
        } catch (final RemoteException e) {
            e.printStackTrace();
        }

        mIsFirstLoad = false;
    }
}