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:eu.dirtyharry.androidopsiadmin.Main.java

public void getOpsiClientsTask() {
    final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait),
            getString(R.string.pd_getclients), true);
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();//w w w .  j  a v  a2  s . c  o  m
            if (GlobalVar.getInstance().getError().equals("null")) {
                if (doit.equals("true")) {

                    Intent i = new Intent(Main.this, ShowOpsiClientsListView.class);
                    Bundle b = new Bundle();
                    b.putStringArrayList("allclients", allclients);
                    b.putStringArrayList("clientdescriptions", clientdescription);
                    b.putStringArrayList("clientmacs", clientmac);
                    b.putStringArrayList("clientnotes", clientnotes);
                    b.putStringArrayList("clientips", clientip);
                    b.putStringArrayList("clientinventorys", clientinventory);
                    b.putStringArrayList("clientlastseens", clientlastseen);
                    i.putExtras(b);
                    startActivityForResult(i, GET_OPSI_CLIENT_REQUEST);

                } else if (doit.equals("serverdown")) {
                    Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip),
                            Toast.LENGTH_LONG).show();
                }
            } else {
                new Functions().msgBox(Main.this, getString(R.string.gen_title_error),
                        GlobalVar.getInstance().getError(), false);
                // GlobalVar.getInstance().setError("null");
            }

        }
    };

    checkUpdate = new Thread() {
        public void run() {
            Looper.prepare();
            if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) {
                getOpsiClients("rpc", serverip, serverport, "host_getHashes", serverusername, serverpasswd);
                doit = "true";
            } else {
                doit = "serverdown";
                //
            }

            handler.sendEmptyMessage(0);

        }
    };
    checkUpdate.start();
    // RTM ????
    // checkUpdate.interrupt();
}

From source file:net.line2soft.preambul.views.ExcursionInfoActivity.java

/**
 * Displays a message to user/*from   w  w w.  j  a  v  a 2  s  . c  om*/
 * @param message The message to display
 */
public void displayInfo(CharSequence message) {
    try {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    } catch (RuntimeException e) {
        Looper.prepare();
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Download the stop database from the server and put it in the
 * application's working data directory.
 *
 * @param context The context to use this method with.
 * @param url The URL of the bus stop database to download.
 *//* w  w w. j  a  va 2s.c  o m*/
private static void updateStopsDB(final Context context, final String url, final String checksum) {
    if (context == null || url == null || url.length() == 0 || checksum == null || checksum.length() == 0)
        return;
    try {
        // Connect to the server.
        final URL u = new URL(url);
        final HttpURLConnection con = (HttpURLConnection) u.openConnection();
        final InputStream in = con.getInputStream();

        // Make sure the URL is what we expect.
        if (!u.getHost().equals(con.getURL().getHost())) {
            in.close();
            con.disconnect();
            return;
        }

        // The location the file should be downloaded to.
        final File temp = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp");
        // The eventual destination of the file.
        final File dest = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME);
        final FileOutputStream out = new FileOutputStream(temp);

        // Get the file from the server.
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        // Make sure the stream is flushed then close resources and
        // disconnect.
        out.flush();
        out.close();
        in.close();
        con.disconnect();

        // Do a MD5 checksum on the downloaded file. Make sure it matches
        // what the server reported.
        if (!md5Checksum(temp).equalsIgnoreCase(checksum)) {
            // If it doesn't match, delete the downloaded file.
            temp.delete();
            return;
        }

        try {
            // Open the temp database and execute the index operation on it.
            final SQLiteDatabase db = SQLiteDatabase.openDatabase(temp.getAbsolutePath(), null,
                    SQLiteDatabase.OPEN_READWRITE);
            BusStopDatabase.setUpIndexes(db);
            db.close();
        } catch (SQLiteException e) {
            // If we couldn't create the index, continue anyway. The user
            // will still be able to use the database, it will just run
            // slowly if they want route lines.
        }

        // Close a currently open database. Delete the old database then
        // move the downloaded file in to its place. Do this while
        // synchronized to make sure noting else uses the database in this
        // time.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        synchronized (bsd) {
            try {
                bsd.getReadableDatabase().close();
            } catch (SQLiteException e) {
                // Nothing to do here. Assume it's already closed.
            }

            dest.delete();
            temp.renameTo(dest);
        }

        // Delete the associated journal file because we no longer need it.
        final File journalFile = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp-journal");
        if (journalFile.exists())
            journalFile.delete();

        // Alert the user that the database has been updated.
        Looper.prepare();
        Toast.makeText(context, R.string.bus_stop_db_updated, Toast.LENGTH_LONG).show();
        Looper.loop();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
}

From source file:com.honeywell.printer.net.autobaln_websocket.WebSocketWriter.java

@Override
public void run() {
    OutputStream outputStream = null;
    try {//ww w.  j a  va 2s.c  o m
        outputStream = mSocket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage());
    }

    this.mOutputStream = outputStream;

    Looper.prepare();

    this.mHandler = new ThreadHandler(this);

    synchronized (this) {
        Log.d(TAG, "WebSocker writer running.");

        notifyAll();
    }

    Looper.loop();
}

From source file:applab.search.client.SynchronizationManager.java

/**
 * Called by our background or timer thread to perform the actual synchronization tasks from a separate thread.
 * // w  w  w.jav a2s . c  om
 * @throws XmlPullParserException
 */
private void performBackgroundSynchronization() throws XmlPullParserException {
    Boolean setupLooper = true;
    if (this.launchedFromTimer) {
        setupLooper = false;
    }

    if (setupLooper) {
        // we may want to associate UI with this task, so create
        // a looper to setup the message pump (by default, background threads
        // don't have a message pump)

        Looper.prepare();
    }

    try {
        sendInternalMessage(GlobalConstants.KEYWORD_DOWNLOAD_STARTING); // We send this so that the dialog shows up
                                                                        // immediately
        SynchronizationManager.singleton.isSynchronizing = true;

        // First submit pending farmer registrations and get latest registration form
        String serverUrl = Settings.getServerUrl();
        FarmerRegistrationController farmerRegController = new FarmerRegistrationController();
        farmerRegController.postFarmerRegistrationData(serverUrl);
        farmerRegController.fetchAndStoreRegistrationForm(serverUrl);

        // Then submit pending usage logs and incomplete searches
        InboxAdapter inboxAdapter = new InboxAdapter(ApplabActivity.getGlobalContext());
        inboxAdapter.open();
        submitPendingUsageLogs(inboxAdapter);

        inboxAdapter.close();

        // Finally update keywords
        updateKeywords();
    } catch (Exception e) {
        e.printStackTrace();
        completeSynchronization();
    }

    if (setupLooper) {
        // TODO: Looper.loop is problematic here. This should be restructured
        Looper.loop();
        Looper looper = Looper.getMainLooper();
        looper.quit();
    }
}

From source file:com.facebook.notifications.NotificationsManager.java

/**
 * Present a {@link Notification} to be presented from a GCM push bundle.
 * <p/>//ww  w . j av  a 2  s  .  c  o m
 * This does not present a notification immediately, instead it caches the assets from the
 * notification bundle, and then presents a notification to the user. This allows for a smoother
 * interaction without loading indicators for the user.
 * <p/>
 * Note that only one notification can be created for a specific push bundle, should you attempt
 * to present a new notification with the same payload bundle as an existing notification, it will
 * replace and update the old notification.
 *
 * @param context              The context to send the notification from
 * @param notificationBundle   The content of the push notification
 * @param launcherIntent       The launcher intent that contains your Application's activity.
 *                             This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and
 *                             FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the
 *                             notification in an already running application.
 *                             <p/>
 *                             Should you not want this behavior, you may use the notificationExtender
 *                             parameter to customize the contentIntent of the notification before
 *                             presenting it.
 * @param notificationExtender A nullable argument that allows you to customize the notification
 *                             before displaying it. Use this to configure Icons, text, sounds,
 *                             etc. before we pass the notification off to the OS.
 */
public static boolean presentNotification(@NonNull final Context context,
        @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent,
        @Nullable final NotificationExtender notificationExtender) {
    final JSONObject alert;
    final int payloadHash;

    try {
        String payload = notificationBundle.getString(CARD_PAYLOAD_KEY);
        if (payload == null) {
            return false;
        }
        payloadHash = payload.hashCode();

        JSONObject payloadObject = new JSONObject(payload);
        alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert")
                : new JSONObject();
    } catch (JSONException ex) {
        Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex);
        return false;
    }

    final boolean[] success = new boolean[1];

    final Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            prepareCard(context, notificationBundle, new PrepareCallback() {
                @Override
                public void onPrepared(@NonNull Intent presentationIntent) {
                    Intent contentIntent = new Intent(launcherIntent);
                    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent);

                    NotificationManager manager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification.Builder builder = new Notification.Builder(context)
                            .setSmallIcon(android.R.drawable.ic_dialog_alert)
                            .setContentTitle(alert.optString("title")).setContentText(alert.optString("body"))
                            .setAutoCancel(true)
                            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(),
                                    payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT));

                    if (notificationExtender != null) {
                        builder = notificationExtender.extendNotification(builder);
                    }

                    manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification());
                    success[0] = true;
                    Looper.myLooper().quit();
                }

                @Override
                public void onError(@NonNull Exception exception) {
                    Log.e(LOG_TAG, "Error while preparing card", exception);
                    Looper.myLooper().quit();
                }
            });

            Looper.loop();
        }
    });

    backgroundThread.start();

    try {
        backgroundThread.join();
    } catch (InterruptedException ex) {
        Log.e(LOG_TAG, "Failed to wait for background thread", ex);
        return false;
    }
    return success[0];
}

From source file:com.wishlist.Wishlist.java

public void fetchCurrentLocation() {
    new Thread() {
        public void run() {
            Looper.prepare();
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            MyLocationListener locationListener = new MyLocationListener();
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = mLocationManager.getBestProvider(criteria, true);
            if (provider != null && mLocationManager.isProviderEnabled(provider)) {
                mLocationManager.requestLocationUpdates(provider, 1, 0, locationListener,
                        Looper.getMainLooper());
            } else {
                showToast("Please turn on handset's GPS");
            }/*from   www.j  a  v  a2s . c om*/
            Looper.loop();
        }
    }.start();
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * retrieves the questions and sends them to the view Starts the connection
 *//*  w  ww.j a  v  a  2  s  .co  m*/
public void retrieveQuestions() {
    Thread t = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            try {
                postAndRecieve("GET", "/", null, null, true);
            } catch (Exception ex) {

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

    // notifyOfProggress();

}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Sends a message to the GUI thread to display a connection error
 *///from w  w w .  ja  v  a2  s  .c o  m
public void showNoConError() {
    Thread t = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            try {
                parent.showConnectionError();
            } catch (Exception ex) {

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

}

From source file:ro.ui.pttdroid.Client_Main.java

private void init() { //init=> OnResume

    final ParseQuery<ParseObject> query = ParseQuery.getQuery("offline");
    System.out.println("latitiude" + Globalvariable.latitude + " " + Globalvariable.longitude);

    dialog = ProgressDialog.show(Client_Main.this, "?", " ?  . . . . ", true);

    new Thread() {
        @Override/*from  w  w  w  . java2  s  .  co m*/
        public void run() {

            for (int i = 10; i > 0; i--) { //for 
                try {
                    System.out.println("i" + i);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            if (if_loading_final == false) { //load?final
                dialog.dismiss();
                if (if_Global_local == 0) {
                    Looper.prepare();
                    Toast.makeText(Client_Main.this, "? =>WIFI =>??wifi",
                            Toast.LENGTH_LONG).show();
                    Intent settintIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                    startActivity(settintIntent);

                } else {
                    Looper.prepare();
                    Toast.makeText(Client_Main.this, "?WIFI?WIFI??"
                            + Globalvariable.client_Main_SSID, Toast.LENGTH_LONG).show();
                    Intent settintIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                    startActivity(settintIntent);

                }

            }

        }
    }.start();

    new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(3000); ///?
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // Retrieve the object by id   
            query.whereEqualTo("latitude", Globalvariable.latitude); //???
            query.whereEqualTo("longitude", Globalvariable.longitude);
            query.findInBackground(new FindCallback<ParseObject>() {
                @Override
                public void done(List<ParseObject> objects, ParseException e) {
                    // TODO Auto-generated method stub
                    if (e == null) {
                        String userNameString = (String) objects.get(0).get("userName");
                        String titleString = (String) objects.get(0).get("title");
                        String contentString = (String) objects.get(0).get("content");
                        System.out.println("SHow" + userNameString + " " + titleString + " " + contentString);

                        if (if_Global_local == 1) {
                            if (userName != null) {
                                userNameString = userNameString + "()";
                                userName.setText(userNameString);
                            }
                            if (title != null)
                                title.setText("#" + titleString);
                            if (content != null)
                                content.setText(contentString);
                        } else {

                            if (title != null)
                                title.setText("#" + titleString);
                            if (content != null)
                                content.setText(contentString);

                        }
                        if_loading_final = true;
                        dialog.dismiss(); //? dialog

                        final ParseFile image = (ParseFile) objects.get(0).get("image");
                        // ((ParseObject) me).getParseFile("data");
                        // final ParseImageView imageView = (ParseImageView) findViewById(R.id.personalprfile);
                        // imageView.setParseFile(image);
                        // System.out.println("image"+image);
                        if (image != null) {
                            image.getDataInBackground(new GetDataCallback() {

                                @Override
                                public void done(byte[] data, ParseException e) {
                                    // TODO Auto-generated method stub
                                    if (e == null) {
                                        System.out.println("personalprofile" + " " + data.length);
                                        final Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                                        // Get the ImageView from main.xml
                                        //ImageView image = (ImageView) findViewById(R.id.ad1);
                                        imageView = (ParseImageView) findViewById(R.id.showimage);

                                        // ImageView imageView=(ImageView) findViewById(R.id.personalprfile);
                                        // Set the Bitmap into the
                                        // ImageView
                                        if (if_Global_local == 1) {
                                            imageView.setParseFile(image);
                                            imageView.setImageBitmap(bmp);
                                        } else {
                                            imageView.setParseFile(image);
                                            imageView.setImageBitmap(bmp);

                                        }
                                        if_loading_final = true;
                                        dialog.dismiss();

                                        /* imageView.loadInBackground(new GetDataCallback() {
                                             public void done(byte[] data, ParseException e) {
                                             // The image is loaded and displayed!                    
                                             int oldHeight = imageView.getHeight();
                                             int oldWidth = imageView.getWidth();     
                                             System.out.println("imageView height = " + oldHeight);
                                             System.out.println("imageView width = " + oldWidth);
                                             imageView.setImageBitmap(bmp);
                                                
                                                
                                            // Log.v("LOG!!!!!!", "imageView height = " + oldHeight);      // DISPLAYS 90 px
                                            // Log.v("LOG!!!!!!", "imageView width = " + oldWidth);        // DISPLAYS 90 px      
                                             }
                                         });*/

                                    } else {
                                        System.out.println("personalprofilerror");

                                    }

                                }
                            });
                        }

                    } else {
                        System.out.println("offlineerror");

                    }
                }

            });
        }
    }.start();

    microphoneSwitcher = new MicrophoneSwitcher();
    microphoneSwitcher.init();
    System.out.println("Client_Main");

    if (firstLaunch) {
        CommSettings.getSettings(this);
        AudioSettings.getSettings(this);

        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        Speex.open(AudioSettings.getSpeexQuality());

        //playerIntent = new Intent(this, Player.class);  
        //startService(playerIntent);
        System.out.println("clientConnectionIntent");
        /*clientConnectionIntent = new Intent(this,
              ClientConnectionService.class);
        startService(clientConnectionIntent);*/

        //customPlayerIntent = new Intent(this, CustomPlayer.class); // 
        //startService(customPlayerIntent);
        if (!if_guider) {

            recorder = new Recorder();
            recorder.start();

        } else {

        }
        firstLaunch = false;
    }
}