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, int arg1, int arg2, Object obj) 

Source Link

Document

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

Usage

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

private Boolean httpDownload(String downloadUrl, String dateiname) {
    URL url;/*from   w  ww .  j  a v  a2s . co m*/
    URLConnection conn;
    String fileName;
    Message msg;
    try {
        url = new URL(downloadUrl);
        conn = url.openConnection();
        conn.setUseCaches(false);
        int fileSize = conn.getContentLength();

        fileName = KleFuEntry.DOWNLOAD_LOCAL_DIRECTORY;
        File file = new File(fileName);
        file.mkdirs();
        fileName = fileName + dateiname;

        // notify download start
        int fileSizeInKB = (int) (fileSize / 1024);
        msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_DOWNLOAD_STARTED, fileSizeInKB, 0, fileName);
        activityHandler.sendMessage(msg);

        BufferedInputStream inStream = new BufferedInputStream(conn.getInputStream());
        File outFile = new File(fileName);
        FileOutputStream fileStream = new FileOutputStream(outFile);
        BufferedOutputStream outStream = new BufferedOutputStream(fileStream, KleFuEntry.DOWNLOAD_BUFFER_SIZE);
        byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE];
        int bytesRead = 0, totalRead = 0;

        while (!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
            outStream.write(data, 0, bytesRead);

            // update progress bar
            totalRead += bytesRead;
            int totalReadInKB = totalRead / 1024;
            msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0);
            activityHandler.sendMessage(msg);
        }

        outStream.close();
        fileStream.close();
        inStream.close();

        if (isInterrupted()) {
            // the download was canceled, so let's delete the partially downloaded file
            outFile.delete();
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        String errMsg = parentActivity.getString(R.string.error_message_general);
        msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR, 0, 0, errMsg);
        activityHandler.sendMessage(msg);
        return false;
    }
}

From source file:io.n7.calendar.caldav.CalDAVService.java

private void setupAcc(Message msg) {
    Log.d(TAG, "setupAcc");
    // validate args
    Bundle bndl = (Bundle) msg.obj;/* w ww.j a v  a 2  s .  c  om*/
    String calname = null;
    String username = null;
    String password = null;
    String host = null;
    String protocol = null;
    String home = null;
    String coll = null;
    int port = -1;
    int err = 0;
    int suberr = 0;
    String errstr = null;

    if (bndl != null) {
        calname = bndl.getString(CAL_NAME);
        username = bndl.getString(CAL_USER);
        password = bndl.getString(CAL_PSWD);
        host = bndl.getString(CAL_HOST);
        protocol = bndl.getString(CAL_PROT);
        port = bndl.getInt(CAL_PORT);
        home = bndl.getString(CAL_HOME);
        coll = bndl.getString(CAL_COLL);
    }
    if (calname == null || username == null || password == null || host == null || protocol == null || port <= 0
            || home == null || coll == null) {
        err = ERR_SETUP_INVALID_ARGS;
    }
    Log.d(TAG, "Setting up CalDAV acc name " + calname + " user " + username + " password " + password
            + " host " + host + " protocol " + protocol + " port " + port + " home " + home + " coll " + coll);

    Account acc = new Account(this, calname, username, password, host, protocol, home, coll, port);
    if (acc == null || Preferences.getPreferences(this).accountExists(acc)) {
        err = ERR_SETUP_ACC_EXISTS;
    }
    //TODO add a system account

    // test connection
    CalDAV4jIf caldavif = null;
    if (err == 0) {
        caldavif = new CalDAV4jIf(getAssets());
        try {
            caldavif.setCredentials(new CaldavCredential(protocol, host, port, home, coll, username, password));
            suberr = caldavif.testConnection();
            if (suberr != HttpStatus.SC_OK) {
                err = ERR_SETUP_CONN;
            } else
                suberr = 0;
        } catch (Exception e) {
            e.printStackTrace();
            err = ERR_SETUP_CONN;
            errstr = e.toString();
        }
    }

    long calid = -1;
    if (err == 0) {
        // store the details persistently.
        acc.save(Preferences.getPreferences(this));

        // add calendar to provider DB
        calid = createCalendar(acc);
        if (calid < 0)
            err = ERR_SETUP_PROVIDER;
    }

    if (err == 0)
        try {
            doSyncCalendar(acc, calid);
        } catch (Exception e) {
            e.printStackTrace();
            err = ERR_SYNC_SERVER;
            errstr = e.toString();
        }

    try {
        if (err != 0 && errstr == null)
            errstr = errString(err);
        msg.replyTo.send(Message.obtain(null, MSG_SETUP_ACC, err, suberr, errstr));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.n7.calendar.caldav.CalDAVService.java

private void sync(Message msg) {
    Log.d(TAG, "sync");
    // retrieve caldav accounts

    int err = 0;/* w w w .jav a2 s  . c  o  m*/
    String errstr = null;
    Account[] accs = Preferences.getPreferences(this).getAccounts();

    try {
        for (Account a : accs) {
            Log.d(TAG, "now syncing " + a.getUrl());
            msg.replyTo.send(Message.obtain(null, MSG_SYNC, 0, a.getAccountNumber() + 1, null));
            err = doSyncCalendar(a);
        }
    } catch (Exception e) {
        e.printStackTrace();
        errstr = e.toString();
        err = ERR_SYNC_SERVER;
    }
    if (accs.length == 0) {
        err = ERR_SYNC_NO_CALENDARS;
        errstr = errString(err);
    }

    try {
        msg.replyTo.send(Message.obtain(null, MSG_SYNC, err, 0, errstr));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.n7.calendar.caldav.CalDAVService.java

private void remove(Message msg) {
    Log.d(TAG, "remove");
    // retrieve caldav accounts

    int err = 0;/*from  www.j a v  a 2 s  . c om*/
    String errstr = null;
    Preferences prefs = Preferences.getPreferences(this);
    Account[] accs = prefs.getAccounts();

    try {
        for (Account a : accs) {
            Log.d(TAG, "now removing " + a.getUrl());
            msg.replyTo.send(Message.obtain(null, MSG_REMOVE, 0, a.getAccountNumber() + 1, null));
            err = doRemoveCalendar(a);
            a.delete(prefs);

        }
    } catch (Exception e) {
        e.printStackTrace();
        errstr = e.toString();
        err = ERR_SYNC_SERVER;
    }
    if (accs.length == 0) {
        err = ERR_REM_NO_CALENDARS;
        errstr = errString(err);
    }

    try {
        msg.replyTo.send(Message.obtain(null, MSG_REMOVE, err, 0, errstr));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

private boolean unpackZip(String path, String zipname) {
    InputStream is;//  ww  w .  j  av  a2 s.  co m
    ZipInputStream zis;
    BufferedInputStream bis;
    try {
        String filename;
        is = new FileInputStream(path + zipname);
        bis = new BufferedInputStream(is);
        zis = new ZipInputStream(bis);
        ZipEntry ze;
        //                 byte[] buffer = new byte[1024];
        //                 int count;
        long fileSize = 0;

        //Gesamtdownloadgre bestimmen
        //                 while ((ze = zis.getNextEntry()) != null) 
        //                 { 
        ze = zis.getNextEntry();
        fileSize = ze.getSize() + fileSize;
        //                 }

        int fileSizeInKB = (int) (fileSize / 1024);

        Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UNZIP_STARTED, fileSizeInKB, 0, "");
        activityHandler.sendMessage(msg);

        int bytesRead = 0, totalRead = 0;

        FileInputStream gis = new FileInputStream(path + zipname);

        BufferedInputStream fis = new BufferedInputStream(gis);

        ZipInputStream dis = new ZipInputStream(fis);

        while ((ze = dis.getNextEntry()) != null) {
            // zapis do souboru
            filename = ze.getName();

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(path + filename);
                fmd.mkdirs();
                continue;
            }

            //

            //                BufferedInputStream inStream = new BufferedInputStream(mFTPClient.retrieveFileStream(ftpPathName));
            //                File outFile = new File(fileName);
            FileOutputStream fileStream = new FileOutputStream(path + filename);
            byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE];

            while (!isInterrupted() && (bytesRead = zis.read(data)) >= 0) {
                fileStream.write(data, 0, bytesRead);

                // update progress bar
                totalRead += bytesRead;
                int totalReadInKB = totalRead / 1024;
                msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0);
                activityHandler.sendMessage(msg);
            }
            //                
            fileStream.close();
            //                 inStream.close();

            //                     FileOutputStream fout = new FileOutputStream(path + filename);
            //
            //                     while ((count = zis.read(buffer)) != -1) 
            //                     {
            //                         fout.write(buffer, 0, count);             
            //                     }
            //
            //                     fout.close();               
            //                     zis.closeEntry();
        }

        zis.close();
        dis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

public boolean ftpConnect(String host, String username, String password, int port) {
    try {/*from   w w w . j  ava 2s .  c  o m*/
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
            // login using username & password
            boolean status = mFTPClient.login(username, password);

            /* Set File Transfer Mode
             *
             * To avoid corruption issue you must specified a correct
             * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
             * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
             * for transferring text, image, and compressed files.
             */
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            return status;
        }
    } catch (Exception e) {
        String errMsg = parentActivity.getString(R.string.error_message_general);
        Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR_FTP_CONNECT, 0, 0,
                errMsg);
        activityHandler.sendMessage(msg);
    }

    return false;
}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

public boolean ftpDisconnect() {
    try {/*ww  w. j a va 2  s.  co  m*/
        mFTPClient.logout();
        mFTPClient.disconnect();
        return true;
    } catch (Exception e) {
        String errMsg = parentActivity.getString(R.string.error_message_general);
        Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR, 0, 0, errMsg);
        activityHandler.sendMessage(msg);
    }

    return false;
}

From source file:info.guardianproject.otr.app.im.service.RemoteImService.java

public void showToast(CharSequence text, int duration) {
    Message msg = Message.obtain(mServiceHandler, EVENT_SHOW_TOAST, duration, 0, text);
    msg.sendToTarget();
}

From source file:com.justone.android.main.MainActivity.java

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

    if (this.justOne.getCurrentTabIndex() != 0) {
        tabs.setCurrentTab(this.justOne.getCurrentTabIndex());
    }//w  ww.  j av a2 s . c o m
    mStatusTracker.setStatus(mActivityName, getString(R.string.on_start));
    Utils.printStatus(mStatusView, mStatusAllView);

    /**
     * Activity
     * timeViewHandler Handler
     * MSG_UPDATE int
     */

    new Thread(new Runnable() {
        @Override
        public void run() {

            isUpdate = true;
            int currentTab = 0;
            String id = "";
            TextView idView;
            View targetView = null;
            boolean isNew = false;
            String currentUrl = "";
            do {

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                if (currentTab != tabs.getCurrentTab())
                    isUpdate = true;
                if (isUpdate && main_item != null) {
                    currentTab = tabs.getCurrentTab();

                    switch (currentTab) {
                    //home 
                    case 0:
                        if (main_item == null)
                            break;
                        targetView = main_item.findViewById(R.id.homeTab);
                        if (targetView == null)
                            break;

                        if (targetView.findViewById(R.id.home_id) != null) {

                            targetView = main_item.findViewById(R.id.homeTab);
                            idView = (TextView) targetView.findViewById(R.id.home_id);
                            id = (String) idView.getText();
                            if (id == "")
                                id = "0";

                            if (currentId != 0) {
                                if (leftOrRight == 1) {
                                    currentId = currentId - 1;
                                    leftOrRight = 0;
                                    if (currentId <= 0)
                                        break;
                                } else if (leftOrRight == 2) {
                                    currentId = currentId + 1;
                                    leftOrRight = 0;
                                    if (currentId > maxId)
                                        break;
                                }
                            }

                            if (currentId > -1 && currentId <= maxId) {
                                isUpdate = false;
                            }
                            if (currentId == 0) {
                                currentUrl = url + "home";
                                isNew = true;
                            } else
                                currentUrl = url + "home&id=" + currentId;

                            /*synchronized (this){
                            Thread.yield();}
                            System.out.println("wait.................");*/

                        }
                        break;
                    //
                    case 1:
                        if (main_item == null)
                            break;
                        if (main_item.findViewById(R.id.tab2) == null)
                            break;
                        if (main_item.findViewById(R.id.tab2).findViewById(R.id.list_id) != null) {
                            targetView = main_item.findViewById(R.id.tab2);
                            idView = (TextView) targetView.findViewById(R.id.list_id);
                            id = (String) idView.getText();
                            if (id == "")
                                id = "0";

                            if (currentId != 0) {
                                if (leftOrRight == 1) {
                                    currentId = currentId - 1;
                                    leftOrRight = 0;
                                    if (currentId <= 0)
                                        break;
                                } else if (leftOrRight == 2) {
                                    currentId = currentId + 1;
                                    leftOrRight = 0;
                                    if (currentId > maxId)
                                        break;
                                }
                            }

                            if (currentId > -1 && currentId <= maxId) {

                                isUpdate = false;
                            }

                            if (currentId == 0) {
                                currentUrl = url + "list";
                                isNew = true;
                            } else
                                currentUrl = url + "list&id=" + currentId;

                        }
                        break;
                    //
                    case 2:
                        if (main_item == null)
                            break;
                        if (main_item.findViewById(R.id.QAtab) == null)
                            break;
                        if (main_item.findViewById(R.id.QAtab).findViewById(R.id.QA_id) != null) {
                            targetView = main_item.findViewById(R.id.QAtab);
                            idView = (TextView) targetView.findViewById(R.id.QA_id);
                            id = (String) idView.getText();
                            if (id == "")
                                id = "0";
                            if (currentId != 0) {
                                if (leftOrRight == 1) {
                                    currentId = currentId - 1;
                                    leftOrRight = 0;
                                    if (currentId <= 0) {
                                        break;
                                    }
                                } else if (leftOrRight == 2) {
                                    currentId = currentId + 1;
                                    leftOrRight = 0;
                                    if (currentId > maxId) {
                                        break;
                                    }
                                }
                            }

                            if (currentId > -1 && currentId <= maxId) {

                                isUpdate = false;

                            }

                            if (currentId == 0) {
                                currentUrl = url + "QA";
                                isNew = true;
                            } else
                                currentUrl = url + "QA&id=" + currentId;

                        }
                        break;

                    }

                    if (isUpdate == false) {
                        try {
                            viewHandler.sendMessage(Message.obtain(viewHandler, 0, currentId, 1, targetView));

                            data = dataOp.getDataAsyn(currentUrl);

                            if (isNew) {
                                //maxId= getDataId(data);
                                maxId = JustOne.getMaxId();
                                isNew = false;
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        viewHandler.sendMessage(Message.obtain(viewHandler, 1, currentId, 1, targetView));

                    }

                }

            } while (true);

        }
    }).start();

    //viewMap.put("list", this.listAdapter);

    try {
        checkVersion();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.uguess.android.sysinfo.ApplicationManager.java

void export(final List<AppInfoHolder> apps) {
    if (apps == null || apps.isEmpty()) {
        Util.shortToast(getActivity(), R.string.no_app_selected);
        return;/*  w w  w  .  ja  va 2s .  co  m*/
    }

    if (progress != null) {
        progress.dismiss();
    }
    progress = new ProgressDialog(getActivity());
    progress.setMessage(getResources().getString(R.string.start_exporting));
    progress.setIndeterminate(false);
    progress.setCancelable(false);
    progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progress.setMax(apps.size());

    progress.show();

    new Thread(new Runnable() {

        public void run() {
            String exportFolder = Util.getStringOption(getActivity(), PSTORE_APPMANAGER,
                    PREF_KEY_APP_EXPORT_DIR, DEFAULT_EXPORT_FOLDER);

            File output = new File(exportFolder);

            if (!output.exists()) {
                if (!output.mkdirs()) {
                    handler.sendMessage(Message.obtain(handler, MSG_COPING_ERROR, 0, 0,
                            getString(R.string.error_create_folder, output.getAbsolutePath())));

                    return;
                }
            }

            File sysoutput = new File(output, SYS_APP);

            if (!sysoutput.exists()) {
                if (!sysoutput.mkdirs()) {
                    handler.sendMessage(Message.obtain(handler, MSG_COPING_ERROR, 0, 0,
                            getString(R.string.error_create_folder, sysoutput.getAbsolutePath())));

                    return;
                }
            }

            File useroutput = new File(output, USER_APP);

            if (!useroutput.exists()) {
                if (!useroutput.mkdirs()) {
                    handler.sendMessage(Message.obtain(handler, MSG_COPING_ERROR, 0, 0,
                            getString(R.string.error_create_folder, useroutput.getAbsolutePath())));

                    return;
                }
            }

            int skipped = 0;
            int succeed = 0;

            for (int i = 0, size = apps.size(); i < size; i++) {
                ApplicationInfo app = apps.get(i).appInfo;

                String src = app.sourceDir;

                if (src != null) {
                    File srcFile = new File(src);

                    if (src.contains("/data/app-private") //$NON-NLS-1$
                            || !srcFile.canRead()) {
                        skipped++;

                        continue;
                    }

                    String appName = getFileName(src);

                    if (appName != null && app.packageName != null) {
                        // always use package name as the file name for
                        // versatile match
                        appName = app.packageName + ".apk"; //$NON-NLS-1$

                        File targetOutput = useroutput;

                        if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                            targetOutput = sysoutput;
                        }

                        File destFile = new File(targetOutput, appName);

                        handler.sendMessage(Message.obtain(handler, MSG_COPING, appName));

                        try {
                            copyFile(srcFile, destFile);

                            succeed++;
                        } catch (Exception e) {
                            Log.e(ApplicationManager.class.getName(), e.getLocalizedMessage(), e);

                            handler.sendMessage(
                                    Message.obtain(handler, MSG_COPING_ERROR, 1, 0, e.getLocalizedMessage()));

                            continue;
                        }
                    }
                }
            }

            handler.sendMessage(Message.obtain(handler, MSG_COPING_FINISHED, succeed, skipped, apps));
        }
    }).start();
}