Example usage for android.os Looper prepare

List of usage examples for android.os Looper prepare

Introduction

In this page you can find the example usage for android.os Looper prepare.

Prototype

public static void prepare() 

Source Link

Document

Initialize the current thread as a looper.

Usage

From source file:com.ririjin.adminmobile.fragment.UpdateImageFragment.java

public void uploadImg(final String path, final String type) {
    new Thread(new Runnable() {
        @Override/*from  ww  w  .ja  v a  2  s .c  o m*/
        public void run() {
            // 
            File file = new File(path);
            long fileSize = file.length();
            Looper.prepare();
            //uploadDialog.show();
            MyProgressMonitor monitor = new MyProgressMonitor(fileSize, getActivity());
            SFTP.UpdateImage(path, type, monitor);

        }
    }).start();

}

From source file:com.ririjin.adminmobile.fragment.UploadImageFragment.java

public void uploadImg(final String path, final String type) {
    new Thread(new Runnable() {
        @Override/*www.  ja  v  a  2 s  .  co  m*/
        public void run() {
            // 
            File file = new File(path);
            long fileSize = file.length();
            Looper.prepare();
            MyProgressMonitor monitor = new MyProgressMonitor(fileSize, getActivity());
            SFTP.UploadImage(path, type, monitor);
        }
    }).start();

}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void runScheduledAlarm(int initialDelay, int period) {
    proximityAlertWatcher = new FiskinfoScheduledTaskExecutor(2).scheduleAtFixedRate(new Runnable() {

        @Override//from   ww w.  j ava  2 s.co m
        public void run() {
            // Need to get alarm status and handle kill
            if (!cacheDeserialized) {
                String directoryPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                String directoryName = "FiskInfo";
                String filename = "collisionCheckToolsFile";
                String format = "OLEX";
                String filePath = directoryPath + "/" + directoryName + "/" + filename + "." + format;
                tools = fiskInfoUtility.deserializeFiskInfoPolygon2D(filePath);
                cacheDeserialized = true;
                // DEMO: add point here for testing/demo purposes
                //                         Point point = new Point(69.650543, 18.956831);
                //                         tools.addPoint(point);
            } else {
                if (alarmFiring) {
                    return;
                }

                double latitude, longitude;

                if (mGpsLocationTracker.canGetLocation()) {
                    latitude = mGpsLocationTracker.getLatitude();
                    cachedLat = latitude;
                    longitude = mGpsLocationTracker.getLongitude();
                    cachedLon = longitude;
                    Log.i("GPS-LocationTracker", String.format("latitude: %s, ", latitude));
                    Log.i("GPS-LocationTracker", String.format("longitude: %s", longitude));
                } else {
                    mGpsLocationTracker.showSettingsAlert();
                    return;
                }
                Point userPosition = new Point(cachedLat, cachedLon);

                if (tools.checkCollisionWithPoint(userPosition, cachedDistance)) {
                    alarmFiring = true;
                    Looper.prepare();
                    notifyUserOfProximityAlert();
                }
            }

            System.out.println("Collision check run");
        }

    }, initialDelay, period, TimeUnit.SECONDS);
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendMMS(final byte[] bytesToSend) {
    revokeWifi(true);//w ww . j ava 2  s  .c  om

    // enable mms connection to mobile data
    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    int result = beginMmsConnectivity();

    if (LOCAL_LOGV)
        Log.v(TAG, "result of connectivity: " + result + " ");

    if (result != 0) {
        // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        final BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context1, Intent intent) {
                String action = intent.getAction();

                if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                    return;
                }

                @SuppressWarnings("deprecation")
                NetworkInfo mNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

                if ((mNetworkInfo == null) || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
                    return;
                }

                if (!mNetworkInfo.isConnected()) {
                    return;
                } else {
                    // ready to send the message now
                    if (LOCAL_LOGV)
                        Log.v(TAG, "sending through broadcast receiver");
                    alreadySending = true;
                    sendData(bytesToSend);

                    context.unregisterReceiver(this);
                }

            }

        };

        context.registerReceiver(receiver, filter);

        try {
            Looper.prepare();
        } catch (Exception e) {
            // Already on UI thread probably
        }

        // try sending after 3 seconds anyways if for some reason the receiver doesn't work
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!alreadySending) {
                    try {
                        if (LOCAL_LOGV)
                            Log.v(TAG, "sending through handler");
                        context.unregisterReceiver(receiver);
                    } catch (Exception e) {

                    }

                    sendData(bytesToSend);
                }
            }
        }, 7000);
    } else {
        // mms connection already active, so send the message
        if (LOCAL_LOGV)
            Log.v(TAG, "sending right away, already ready");
        sendData(bytesToSend);
    }
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendMMSWiFi(final byte[] bytesToSend) {
    // enable mms connection to mobile data
    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo.State state = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getState();

    if ((0 == state.compareTo(NetworkInfo.State.CONNECTED)
            || 0 == state.compareTo(NetworkInfo.State.CONNECTING))) {
        sendData(bytesToSend);/*from w w w .  ja v a2 s.c o m*/
    } else {
        int resultInt = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");

        if (resultInt == 0) {
            try {
                Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                sendData(bytesToSend);
            } catch (Exception e) {
                Log.e(TAG, "exception thrown", e);
                sendData(bytesToSend);
            }
        } else {
            // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            final BroadcastReceiver receiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context1, Intent intent) {
                    String action = intent.getAction();

                    if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                        return;
                    }

                    NetworkInfo mNetworkInfo = mConnMgr.getActiveNetworkInfo();
                    if ((mNetworkInfo == null)
                            || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE_MMS)) {
                        return;
                    }

                    if (!mNetworkInfo.isConnected()) {
                        return;
                    } else {
                        alreadySending = true;

                        try {
                            Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                            sendData(bytesToSend);
                        } catch (Exception e) {
                            Log.e(TAG, "exception thrown", e);
                            sendData(bytesToSend);
                        }

                        context.unregisterReceiver(this);
                    }

                }

            };

            context.registerReceiver(receiver, filter);

            try {
                Looper.prepare();
            } catch (Exception e) {
                // Already on UI thread probably
            }

            // try sending after 3 seconds anyways if for some reason the receiver doesn't work
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!alreadySending) {
                        try {
                            context.unregisterReceiver(receiver);
                        } catch (Exception e) {

                        }

                        try {
                            Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                            sendData(bytesToSend);
                        } catch (Exception e) {
                            Log.e(TAG, "exception thrown", e);
                            sendData(bytesToSend);
                        }
                    }
                }
            }, 7000);
        }
    }
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

@Override
public void onBackPressed() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);

    if (GTConstants.sendData) {
        dialog.setTitle("Warning");
        dialog.setMessage("You must end shift before exit!");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override//from  ww w .j  ava 2 s.  co  m
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        dialog.show();
    } else {
        dialog.setTitle("Exit?");
        dialog.setMessage("Are you sure you want to exit?");
        dialog.setNegativeButton(android.R.string.no, null);
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                // Create a Dialog to let the User know that we're waiting for a GPS Fix
                pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Exiting GT Android ...", true);

                Runnable showWaitDialog = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Looper.prepare();
                            MainService.closeLocationListener(); //close out GPS

                            //only send 92 if online
                            if (Utility.isOnline(HomeScreen.this)) {
                                GTConstants.sendData = true; //allow the exit event to be sent
                                send_event("92"); //send the event
                                Utility.Sleep(4000); //give time for the event to be sent before exiting
                            }

                            stopService();

                            Utility.Sleep(1000);
                            pdialog.dismiss();
                            Utility.Sleep(1000);

                            //terminating the running threads and finishing program must be run on the main thread
                            HomeScreen.this.runOnUiThread(new Runnable() {
                                public void run() {
                                    if (pdialog.isShowing())
                                        pdialog.dismiss();
                                    HomeScreen.super.onBackPressed();
                                    android.os.Process.killProcess(android.os.Process.myPid());
                                    finish();
                                }
                            });
                        } catch (Exception e) {

                            //terminating the running threads and finishing program must be run on the main thread
                            HomeScreen.this.runOnUiThread(new Runnable() {
                                public void run() {
                                    if (pdialog.isShowing())
                                        pdialog.dismiss();
                                    HomeScreen.super.onBackPressed();
                                    android.os.Process.killProcess(android.os.Process.myPid());
                                    finish();
                                }
                            });

                        }
                    }
                };

                Thread t = new Thread(showWaitDialog);
                t.start();
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!Utility.deviceRegistered()) {
                    //send_data = true;
                    scan_click(false);
                }
            }
        });

        dialog.show();
    }
}

From source file:piuk.blockchain.android.WalletApplication.java

public void apiStoreKey(final String pin, final SuccessCallback callback) {
    final MyRemoteWallet blockchainWallet = this.blockchainWallet;

    if (blockchainWallet == null) {
        if (callback != null)
            callback.onFail();/*  w  w  w.  j  a  va  2  s  . co  m*/

        return;
    }

    final WalletApplication application = this;

    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();

            Editor edit = PreferenceManager.getDefaultSharedPreferences(application).edit();

            //
            // Save PIN
            //
            try {
                byte[] bytes = new byte[16];
                SecureRandom random = new SecureRandom();
                random.nextBytes(bytes);
                final String key = new String(Hex.encode(bytes), "UTF-8");
                random.nextBytes(bytes);
                final String value = new String(Hex.encode(bytes), "UTF-8");
                final JSONObject response = piuk.blockchain.android.ui.PinEntryActivity.apiStoreKey(key, value,
                        pin);
                if (response.get("success") != null) {
                    callback.onSuccess();
                    edit.putString("pin_kookup_key", key);
                    edit.putString("encrypted_password",
                            MyWallet.encrypt(application.getRemoteWallet().getTemporyPassword(), value,
                                    piuk.blockchain.android.ui.PinEntryActivity.PBKDF2Iterations));

                    if (!edit.commit()) {
                        throw new Exception("Error Saving Preferences");
                    } else {
                    }
                } else {
                    Toast.makeText(application, response.toString(), Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Toast.makeText(application, e.toString(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
            //
            //
            //

            Looper.loop();

        }
    }).start();
}

From source file:com.devwang.logcabin.LogCabinMainActivity.java

/**
 * Web/*www . j a  v a2s.c o m*/
 */
private void syncTimeMethod() {
    if (flag_sync_web == true) {
        Looper.prepare();// 
        // java.lang.RuntimeException: Can't create handler inside thread
        // that has not called Looper.prepare()
        // messagehandler Looper.prepare()
        for (int i = 0; i < SYNC_WEB_TIMES; i++) {
            try {

                handler.sendEmptyMessage(FLAG_HANDLER_MESSAGE_AUTO_SYNC_WEB);
                if (D)
                    Log.i("TEST_Sync", "==>>i=" + i + ";");
                Thread.sleep(SYNC_WEB_PERIOD);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        flag_sync_web = false;
        toastDisplay(LogCabinMainActivity.this,
                "" + SYNC_WEB_TIMES + "" + SYNC_WEB_PERIOD + "s", Gravity.BOTTOM, 0,
                Toast.LENGTH_SHORT);
    }
}

From source file:com.irccloud.android.NetworkConnection.java

public void request_backlog(int cid, int bid, long beforeId) {
    try {/* w  w  w  . j  a v  a  2  s  .co  m*/
        if (oobTasks.containsKey(bid)) {
            Crashlytics.log(Log.WARN, TAG, "Ignoring duplicate backlog request for BID: " + bid);
            return;
        }
        if (session == null || session.length() == 0) {
            Crashlytics.log(Log.WARN, TAG, "Not fetching backlog before session is set");
            return;
        }
        if (Looper.myLooper() == null)
            Looper.prepare();

        OOBIncludeTask task = new OOBIncludeTask(bid);
        oobTasks.put(bid, task);

        if (beforeId > 0)
            task.execute(new URL("https://" + IRCCLOUD_HOST + "/chat/backlog?cid=" + cid + "&bid=" + bid
                    + "&beforeid=" + beforeId));
        else
            task.execute(new URL("https://" + IRCCLOUD_HOST + "/chat/backlog?cid=" + cid + "&bid=" + bid));
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

From source file:dentex.youtube.downloader.DashboardActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        BugSenseHandler.leaveBreadcrumb("DashboardActivity_filechooser_RESULT_OK");
        @SuppressWarnings("unchecked")
        List<LocalFile> files = (List<LocalFile>) data.getSerializableExtra(FileChooserActivity._Results);

        String path = data.getStringExtra("path");
        String name = data.getStringExtra("name");
        File in = new File(path, name);

        final File chooserSelection = files.get(0);
        //Utils.logger("d", "file-chooser selection: " + chooserFolder.getPath(), DEBUG_TAG);
        //Utils.logger("d", "origin file's folder:   " + currentItem.getPath(), DEBUG_TAG);

        switch (requestCode) {

        case 1: // ------------- > COPY
            File out1 = new File(chooserSelection, name);

            if (chooserSelection.getPath().equals(currentItem.getPath())) {
                out1 = new File(chooserSelection, "copy_" + currentItem.getFilename());
            }/* w  ww. j  a v  a 2s .  c om*/

            if (!out1.exists()) {
                switch (Utils.pathCheck(chooserSelection)) {
                case 0:
                    // Path on standard sdcard
                    new AsyncCopy().execute(in, out1);
                    break;
                case 1:
                    // Path not writable
                    PopUps.showPopUp(getString(R.string.system_warning_title),
                            getString(R.string.system_warning_msg), "alert", DashboardActivity.this);
                    break;
                case 2:
                    // Path not mounted
                    Toast.makeText(DashboardActivity.this, getString(R.string.sdcard_unmounted_warning),
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                PopUps.showPopUp(getString(R.string.long_press_warning_title),
                        getString(R.string.long_press_warning_msg2), "info", DashboardActivity.this);
            }
            break;

        case 2: // ------------- > MOVE
            File out2 = new File(chooserSelection, name);

            if (!chooserSelection.getPath().equals(currentItem.getPath())) {
                if (!out2.exists()) {
                    switch (Utils.pathCheck(chooserSelection)) {
                    case 0:
                        // Path on standard sdcard
                        new AsyncMove().execute(in, out2);
                        break;
                    case 1:
                        // Path not writable
                        PopUps.showPopUp(getString(R.string.system_warning_title),
                                getString(R.string.system_warning_msg), "alert", DashboardActivity.this);
                        break;
                    case 2:
                        // Path not mounted
                        Toast.makeText(DashboardActivity.this, getString(R.string.sdcard_unmounted_warning),
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    PopUps.showPopUp(getString(R.string.long_press_warning_title),
                            getString(R.string.long_press_warning_msg2), "info", DashboardActivity.this);
                }
            } else {
                PopUps.showPopUp(getString(R.string.long_press_warning_title),
                        getString(R.string.long_press_warning_msg), "info", DashboardActivity.this);
            }
            break;

        case 3: // ------------- > MENU_BACKUP
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();

                    String date = new SimpleDateFormat("yyyy-MM-dd'_'HH-mm-ss", Locale.US).format(new Date());
                    final File backup = new File(chooserSelection, date + "_" + YTD.JSON_FILENAME);

                    try {
                        Utils.copyFile(YTD.JSON_FILE, backup);
                        Toast.makeText(sDashboard, getString(R.string.menu_backup_result_ok),
                                Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        Log.e(DEBUG_TAG, "IOException @ MENU_BACKUP: " + e.getMessage());
                        Toast.makeText(sDashboard, getString(R.string.menu_backup_result_failed),
                                Toast.LENGTH_LONG).show();
                    }

                    Looper.loop();
                }
            }).start();
            break;

        case 4: // ------------- > MENU_RESTORE
            AsyncRestore ar = new AsyncRestore();
            ar.execute(chooserSelection);

            break;

        case 5: // ------------- > MENU_IMPORT
            AsyncImport ai = new AsyncImport();
            ai.execute(chooserSelection);
        }
    }
}