List of usage examples for android.os Looper prepare
public static void prepare()
From source file:cn.xiongyihui.wificar.Car.java
public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { String url = "http://" + mIp + "/cgi-bin/serial?" + (String) msg.obj; URI uri = URI.create(url); HttpResponse httpResponse;//from w ww. j a va2s . c o m DefaultHttpClient httpClient = new DefaultHttpClient(); try { httpResponse = httpClient.execute(new HttpGet(uri)); } catch (IOException e) { Log.v(TAG, "Unable to connect to car."); mState = STATE_UNCONNECTED; return; } char get; try { get = (char) httpResponse.getEntity().getContent().read(); } catch (IOException e) { Log.v(TAG, "Unkown situation when connecting car."); mState = STATE_UNKOWN; return; } mState = mCommandList.indexOf(Character.toString(get)); } }; changeTo(STATE_STOP); Looper.loop(); }
From source file:org.smssecure.smssecure.notifications.MessageNotifier.java
public static void sendDeliveryToast(final Context context, final String recipientName) { new Thread() { @Override/*from ww w . j a v a 2 s . c o m*/ public void run() { Looper.prepare(); Toast.makeText(context.getApplicationContext(), context.getString(R.string.MessageNotifier_message_received, recipientName), Toast.LENGTH_LONG).show(); Looper.loop(); } }.start(); }
From source file:fi.mikuz.boarder.gui.ZipImporter.java
@SuppressWarnings("rawtypes") public void unzipArchive(final File archive, final File outputDir) { Thread t = new Thread() { public void run() { Looper.prepare(); String archiveName = archive.getName(); String boardName = archiveName.substring(0, archiveName.indexOf(".zip")); String boardDirectory = SoundboardMenu.mSbDir.getAbsolutePath() + "/" + boardName; try { File boardDirectoryFile = new File(boardDirectory); if (boardDirectoryFile.exists()) { postMessage(boardDirectoryFile.getName() + " already exists."); } else { ZipFile zipfile = new ZipFile(archive); boolean normalStructure = true; log = "Checking if zip structure is legal\n" + log; for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); File outputFile = new File(outputDir, entry.getName()); if (!Pattern.matches(boardDirectory + ".*", outputFile.getAbsolutePath())) { normalStructure = false; log = entry.getName() + " failed\n" + outputFile.getAbsolutePath() + "\ndoens't match\n" + boardDirectory + "\n\n" + log; Log.e(TAG, entry.getName() + " failed\n" + outputFile.getAbsolutePath() + "\ndoens't match\n" + boardDirectory); }/*from w w w. ja v a 2 s . c o m*/ } if (normalStructure) { log = "\nGoing to extract\n" + log; outputDir.mkdirs(); for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); log = "Extracting " + entry.getName() + "\n" + log; postMessage("Please wait\n\n" + log); unzipEntry(zipfile, entry, outputDir); } log = "Success\n\n" + log; postMessage(log); } else { postMessage("Zip was not extracted because it doesn't follow the normal structure.\n\n" + "Please use another application to check the content of this zip file and extract it if you want to.\n\n" + log); } } } catch (Exception e) { log = "Couldn't extract " + archive + "\n\nError: \n" + e.getMessage() + "\n\n" + log; postMessage(log); Log.e(TAG, "Error while extracting file " + archive, e); } mHandler.post(showContinueButton); } }; t.start(); }
From source file:com.gtosoft.libvoyager.net.GTONet.java
/** * Creates a new "worker" thread, to which we can post new work to be performed asynchronously from the main (UI) thread. */// w w w . j a va 2 s . c o m public void startWorkerThread() { if (mWorkerThread != null) return; // create a new thread. mWorkerThread = new Thread() { public void run() { //mWorkerHandler.getLooper(); Looper.prepare(); // set the worker to a new handler owned by this thead. mWorkerHandler = new Handler(); // main loop. just loop, sleeping, waiting for work. while (1 == 1) { Looper.loop(); try { Thread.sleep(1000); } catch (InterruptedException e) { break; // break out of the while loop, kills the thread. } } // end while loop. Looper.myLooper().quit(); }// end of thread run() }; mWorkerThread.start(); // sleep for a second while thread starts... Prevents calling tasks from hitting it before it has a chance to start! try { Thread.sleep(1000); } catch (InterruptedException e) { return; } }
From source file:com.phonegap.plugin.bluetooth.BluetoothPlugin.java
@Override public PluginResult execute(String action, JSONArray arg1, String callbackId) { Log.d("BluetoothPlugin", "Plugin Called"); PluginResult result = null;//from w w w. j a v a 2 s.com context = this.ctx; // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery starts filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); context.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); context.registerReceiver(mReceiver, filter); // Register for broadcasts when connectivity state changes filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(mReceiver, filter); Looper.prepare(); btadapter = BluetoothAdapter.getDefaultAdapter(); found_devices = new ArrayList<BluetoothDevice>(); if (ACTION_DISCOVER_DEVICES.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_DISCOVER_DEVICES); found_devices.clear(); discovering = true; if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } Log.i("BluetoothPlugin", "Discovering devices..."); btadapter.startDiscovery(); while (discovering) { } String devicesFound = null; int count = 0; devicesFound = "["; for (BluetoothDevice device : found_devices) { Log.i("BluetoothPlugin", device.getName() + " " + device.getAddress() + " " + device.getBondState()); if ((device.getName() != null) && (device.getBluetoothClass() != null)) { devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count < found_devices.size() - 1) devicesFound = devicesFound + ","; } else Log.i("BluetoothPlugin", device.getName() + " Problems retrieving attributes. Device not added "); count++; } devicesFound = devicesFound + "] "; Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Returning: " + devicesFound); result = new PluginResult(Status.OK, devicesFound); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_IS_BT_ENABLED.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_IS_BT_ENABLED); boolean isEnabled = btadapter.isEnabled(); Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Returning " + "is Bluetooth Enabled? " + isEnabled); result = new PluginResult(Status.OK, isEnabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_ENABLE_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_ENABLE_BT); boolean enabled = false; Log.d("BluetoothPlugin", "Enabling Bluetooth..."); if (btadapter.isEnabled()) { enabled = true; } else { enabled = btadapter.enable(); } Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Returning " + "Result: " + enabled); result = new PluginResult(Status.OK, enabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_DISABLE_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_DISABLE_BT); boolean disabled = false; Log.d("BluetoothPlugin", "Disabling Bluetooth..."); if (btadapter.isEnabled()) { disabled = btadapter.disable(); } else { disabled = true; } Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Returning " + "Result: " + disabled); result = new PluginResult(Status.OK, disabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_PAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_PAIR_BT); String addressDevice = arg1.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean paired = false; Log.d("BluetoothPlugin", "Pairing with Bluetooth device with name " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("createBond"); paired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Returning " + "Result: " + paired); result = new PluginResult(Status.OK, paired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_UNPAIR_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_UNPAIR_BT); String addressDevice = arg1.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean unpaired = false; Log.d("BluetoothPlugin", "Unpairing Bluetooth device with " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("removeBond"); unpaired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Returning " + "Result: " + unpaired); result = new PluginResult(Status.OK, unpaired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_LIST_BOUND_DEVICES.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_LIST_BOUND_DEVICES); Log.d("BluetoothPlugin", "Getting paired devices..."); Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices(); int count = 0; String resultBoundDevices = "[ "; if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i("BluetoothPlugin", device.getName() + " " + device.getAddress() + " " + device.getBondState()); if ((device.getName() != null) && (device.getBluetoothClass() != null)) { resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count < pairedDevices.size() - 1) resultBoundDevices = resultBoundDevices + ","; } else Log.i("BluetoothPlugin", device.getName() + " Problems retrieving attributes. Device not added "); count++; } } resultBoundDevices = resultBoundDevices + "] "; Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Returning " + resultBoundDevices); result = new PluginResult(Status.OK, resultBoundDevices); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_STOP_DISCOVERING_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_STOP_DISCOVERING_BT); boolean stopped = true; Log.d("BluetoothPlugin", "Stop Discovering Bluetooth Devices..."); if (btadapter.isDiscovering()) { Log.i("BluetoothPlugin", "Stop discovery..."); stopped = btadapter.cancelDiscovery(); discovering = false; } Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Returning " + "Result: " + stopped); result = new PluginResult(Status.OK, stopped); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else if (ACTION_IS_BOUND_BT.equals(action)) { try { Log.d("BluetoothPlugin", "We're in " + ACTION_IS_BOUND_BT); String addressDevice = arg1.getString(0); BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); Log.i("BluetoothPlugin", "BT Device in state " + device.getBondState()); boolean state = false; if (device != null && device.getBondState() == 12) state = true; else state = false; Log.d("BluetoothPlugin", "Is Bound with " + device.getName() + " - address " + device.getAddress()); Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Returning " + "Result: " + state); result = new PluginResult(Status.OK, state); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(Status.ERROR); } } else { result = new PluginResult(Status.INVALID_ACTION); Log.d("BluetoothPlugin", "Invalid action : " + action + " passed"); } return result; }
From source file:org.sigimera.app.android.ProfileFragment.java
@Override public final View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { view = inflater.inflate(R.layout.profile_fragment, container, false); progessDialog = ProgressDialog.show(getActivity(), "Preparing profile information!", "Please be patient until the information are ready...", true); progessDialog.setCancelable(true);/*from w ww. j a va2s . c om*/ Thread worker = new Thread() { @Override public void run() { try { Looper.prepare(); authToken = ApplicationController.getInstance().getSessionHandler().getAuthenticationToken(); stats = PersistanceController.getInstance().getUsersStats(authToken); if (stats == null) { Log.d("[PROFILE FRAGMENT]", "User stats are empty."); } if (stats != null && stats.getUsername() != null) { InputStream is = (InputStream) getAvatarURL(stats.getEmail()).getContent(); drawable = Drawable.createFromStream(is, "src name"); radius = stats.getRadius(); } guiHandler.post(updateGUI); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AuthenticationErrorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; worker.start(); return view; }
From source file:org.sigimera.app.android.CrisesListFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.crises_list, container, false); this.list = (ListView) view.findViewById(R.id.crisis_list); this.list.setOnItemClickListener(this.clickListener); // this.list.setOnScrollListener(this.scrollListener); registerForContextMenu(this.list); this.arguments = getArguments(); this.progessDialog = ProgressDialog.show(getActivity(), "Preparing crises information!", "Please be patient until the information are ready..."); Thread worker = new Thread() { @SuppressWarnings("unchecked") @Override//from w ww .ja va 2 s . c o m public void run() { Looper.prepare(); try { authToken = ApplicationController.getInstance().getSessionHandler().getAuthenticationToken(); PersistanceController.getInstance().addObserver(CrisesListFragment.this); // If there are crises passed as arguments -> show them if (arguments != null) { Object object = getArguments().getSerializable("crises"); if (object != null) crises = (ArrayList<Crisis>) object; } // otherwise check if the user wants to have near crises on crises list else if (PersistanceController.getInstance().getUsersStats(authToken).getRadius() != 0) { Log.i("[CRISES LIST]", "Show the near crises into the crises list"); crises = PersistanceController.getInstance().getNearCrises(); } } catch (AuthenticationErrorException e) { Log.d(Constants.LOG_TAG_SIGIMERA_APP, "Fetching public crises list..."); } if (crises == null || crises.isEmpty()) crises = PersistanceController.getInstance().getCrises(authToken, page); guiHandler.post(updateGUI); } }; worker.start(); return view; }
From source file:cw.kop.autobackground.files.DownloadThread.java
@Override public void run() { super.run();/*ww w. j a va2s . co m*/ Looper.prepare(); if (AppSettings.useDownloadNotification()) { PendingIntent pendingStopIntent = PendingIntent.getBroadcast(appContext, 0, new Intent(LiveWallpaperService.STOP_DOWNLOAD), 0); notificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE); notifyProgress = new Notification.Builder(appContext).setContentTitle("AutoBackground") .setContentText("Downloading images...").setSmallIcon(R.drawable.ic_photo_white_24dp); if (Build.VERSION.SDK_INT >= 16) { notifyProgress.setPriority(Notification.PRIORITY_MIN); notifyProgress.addAction(R.drawable.ic_cancel_white_24dp, "Stop Download", pendingStopIntent); } updateNotification(0); } String downloadCacheDir = AppSettings.getDownloadPath(); File cache = new File(downloadCacheDir); if (!cache.exists() || !cache.isDirectory()) { cache.mkdir(); } List<Integer> indexes = new ArrayList<>(); for (int index = 0; index < AppSettings.getNumberSources(); index++) { Source source = AppSettings.getSource(index); if (!source.getType().equals(AppSettings.FOLDER) && source.isUse()) { indexes.add(index); progressMax += source.getNum(); } } usedLinks = new HashSet<>(); if (AppSettings.checkDuplicates()) { Set<String> rawLinks = AppSettings.getUsedLinks(); for (String link : rawLinks) { if (link.lastIndexOf("Time:") > 0) { link = link.substring(0, link.lastIndexOf("Time:")); } usedLinks.add(link); } } downloadedFiles = new ArrayList<>(); for (int index : indexes) { Source source = AppSettings.getSource(index); if (isInterrupted()) { cancel(); return; } try { if (AppSettings.deleteOldImages()) { FileHandler.deleteBitmaps(appContext, source); } String title = source.getTitle(); File file = new File(downloadCacheDir + "/" + title + " " + AppSettings.getImagePrefix()); if (!file.exists() || !file.isDirectory()) { file.mkdir(); } String sourceType = source.getType(); String sourceData = source.getData(); switch (sourceType) { case AppSettings.WEBSITE: downloadWebsite(sourceData, source); break; case AppSettings.IMGUR_SUBREDDIT: downloadImgurSubreddit(sourceData, source); break; case AppSettings.IMGUR_ALBUM: downloadImgurAlbum(sourceData, source); break; case AppSettings.GOOGLE_ALBUM: downloadPicasa(sourceData, source); break; case AppSettings.TUMBLR_BLOG: downloadTumblrBlog(sourceData, source); break; case AppSettings.TUMBLR_TAG: downloadTumblrTag(sourceData, source); break; case AppSettings.REDDIT_SUBREDDIT: downloadRedditSubreddit(sourceData, source); break; } totalTarget += source.getNum(); updateNotification(totalTarget); } catch (IOException | IllegalArgumentException e) { sendToast("Invalid URL: " + source.getData()); Log.i(TAG, "Invalid URL"); } } finish(); }
From source file:ru.dublgis.androidhelpers.mobility.CellListener.java
public synchronized boolean start() { Log.d(TAG, "start"); try {//from w w w .ja va 2s . c o m if (mManager == null) { mManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); } Runnable listenRunnable = new Runnable() { @Override public void run() { if (mManager != null) { try { Looper.prepare(); mListenerLooper = Looper.myLooper(); mListener = new CellListenerImpl(); mManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); Looper.loop(); mManager.listen(mListener, PhoneStateListener.LISTEN_NONE); } catch (Throwable ex) { Log.e(TAG, "Failed to start TelephonyManager listener", ex); } } } }; mListenerThread = new Thread(listenRunnable, "Listen TelephonyManager"); mListenerThread.start(); return true; } catch (Throwable e) { Log.e(TAG, "Exception while starting cell listener: ", e); return false; } }
From source file:com.lostad.app.base.util.DownloadUtil.java
public static void downFileAsyn(final Activity ctx, final String upgradeUrl, final String savedPath, final MyCallback<Boolean> callback) { final ProgressDialog xh_pDialog = new ProgressDialog(ctx); // ?/*ww w .j a v a 2 s .c om*/ xh_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // ProgressDialog xh_pDialog.setTitle("???"); // ProgressDialog??? xh_pDialog.setMessage("..."); // ProgressDialog // xh_pDialog.setIcon(R.drawable.img2); // ProgressDialog ??? false ?? xh_pDialog.setIndeterminate(false); // ProgressDialog ? // xh_pDialog.setProgress(100); // ProgressDialog ??? xh_pDialog.setCancelable(true); // ProgressDialog xh_pDialog.show(); new Thread() { public void run() { boolean downloadSuccess = true; FileOutputStream fileOutputStream = null; try { Looper.prepare(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(upgradeUrl); File f = new File(savedPath); if (!f.exists()) { f.createNewFile(); } HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); // ? Long length = entity.getContentLength(); xh_pDialog.setMax(length.intValue()); // InputStream is = entity.getContent(); fileOutputStream = null; if (is != null && length > 0) { fileOutputStream = new FileOutputStream(f); byte[] buf = new byte[1024]; int ch = -1; int count = 0; while ((ch = is.read(buf)) != -1) { if (xh_pDialog.isShowing()) { fileOutputStream.write(buf, 0, ch); // ? count += ch; xh_pDialog.setProgress(count); } else { downloadSuccess = false; break;// ? } } } else { callback.onCallback(false); } if (downloadSuccess && fileOutputStream != null) { xh_pDialog.dismiss(); fileOutputStream.flush(); fileOutputStream.close(); callback.onCallback(true);// ? } Looper.loop(); } catch (FileNotFoundException e) { xh_pDialog.dismiss(); e.printStackTrace(); callback.onCallback(false); xh_pDialog.dismiss(); } catch (Exception e) { xh_pDialog.dismiss(); e.printStackTrace(); callback.onCallback(false); } finally { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }.start(); }