List of usage examples for android.os Handler obtainMessage
public final Message obtainMessage(int what)
From source file:Main.java
public static void loadFailed(Handler handler) { handler.sendMessageDelayed(handler.obtainMessage(LOAD_FAIL), 3000); //handler.sendMessage(handler.obtainMessage(20)); return;/*from ww w. ja v a 2s. c o m*/ }
From source file:Main.java
public static boolean raise(int signal, Handler handler, Object value) { Message msg = handler.obtainMessage(signal); msg.obj = value;/*from www .j a v a 2 s .co m*/ return handler.sendMessage(msg); }
From source file:Main.java
public static void delivery2Handler(Handler handler, int what, Object obj) { if (handler == null) return;/* w w w .j ava 2s. c o m*/ Message msg = handler.obtainMessage(what); msg.obj = obj; handler.sendMessage(msg); }
From source file:de.unwesen.packrat.api.APIBase.java
public byte[] fetchRawSynchronous(HttpRequestBase request, Handler handler) { HttpResponse response;/*from www . j ava 2 s .c o m*/ try { response = sClient.execute(request); // Read response HttpEntity entity = response.getEntity(); if (null == entity) { Log.e(LTAG, "Response is empty: " + request.getURI().toString()); if (null != handler) { handler.obtainMessage(ERR_EMPTY_RESPONSE).sendToTarget(); } return null; } return readStreamRaw(entity.getContent()); } catch (IOException ex) { Log.w(LTAG, "An exception occurred when reading the API response: " + ex.getMessage()); if (null != handler) { handler.obtainMessage(ERR_TRANSMISSION).sendToTarget(); } return null; } }
From source file:de.ub0r.android.callmeter.data.RuleMatcher.java
/** * Match all unmatched logs./* www . ja va 2 s.co m*/ * * @param context {@link Context} * @param showStatus post status to dialog/handler * @return true if a log was matched */ static synchronized boolean match(final Context context, final boolean showStatus) { Log.d(TAG, "match(ctx, ", showStatus, ")"); long start = System.currentTimeMillis(); boolean ret = false; load(context); final ContentResolver cr = context.getContentResolver(); final Cursor cursor = cr.query(DataProvider.Logs.CONTENT_URI, DataProvider.Logs.PROJECTION, DataProvider.Logs.PLAN_ID + " = " + DataProvider.NO_ID, null, DataProvider.Logs.DATE + " ASC"); if (cursor != null && cursor.moveToFirst()) { final int l = cursor.getCount(); Handler h; if (showStatus) { h = Plans.getHandler(); if (h != null) { final Message m = h.obtainMessage(Plans.MSG_BACKGROUND_PROGRESS_MATCHER); m.arg1 = 0; m.arg2 = l; m.sendToTarget(); } } try { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int i = 1; do { ret |= matchLog(cr, ops, cursor); if (i % PROGRESS_STEPS == 0 || (i < PROGRESS_STEPS && i % CallMeter.TEN == 0)) { h = Plans.getHandler(); if (h != null) { final Message m = h.obtainMessage(Plans.MSG_BACKGROUND_PROGRESS_MATCHER); m.arg1 = i; m.arg2 = l; Log.d(TAG, "send progress: ", i, "/", l); m.sendToTarget(); } else { Log.d(TAG, "send progress: ", i, " handler=null"); } Log.d(TAG, "save logs.."); cr.applyBatch(DataProvider.AUTHORITY, ops); ops.clear(); Log.d(TAG, "sleeping.."); try { Thread.sleep(CallMeter.MILLIS); } catch (InterruptedException e) { Log.e(TAG, "sleep interrupted", e); } Log.d(TAG, "sleep finished"); } ++i; } while (cursor.moveToNext()); if (ops.size() > 0) { cr.applyBatch(DataProvider.AUTHORITY, ops); } } catch (IllegalStateException e) { Log.e(TAG, "illegal state in RuleMatcher's loop", e); } catch (OperationApplicationException e) { Log.e(TAG, "illegal operation in RuleMatcher's loop", e); } catch (RemoteException e) { Log.e(TAG, "remote exception in RuleMatcher's loop", e); } } try { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } catch (IllegalStateException e) { Log.e(TAG, "illegal state while closing cursor", e); } if (ret) { final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); final boolean a80 = p.getBoolean(Preferences.PREFS_ALERT80, true); final boolean a100 = p.getBoolean(Preferences.PREFS_ALERT100, true); // check for alerts if ((a80 || a100) && plans != null && plans.size() > 0) { final long now = System.currentTimeMillis(); int alert = 0; Plan alertPlan = null; int l = plans.size(); for (int i = 0; i < l; i++) { final Plan plan = plans.valueAt(i); if (plan == null) { continue; } if (plan.nextAlert > now) { Log.d(TAG, "%s: skip alert until: %d now=%d", plan, plan.nextAlert, now); continue; } int used = DataProvider.Plans.getUsed(plan.type, plan.limitType, plan.billedAmount, plan.billedCost); int usedRate = plan.limit > 0 ? (int) ((used * CallMeter.HUNDRED) / plan.limit) : 0; if (a100 && usedRate >= CallMeter.HUNDRED) { alert = usedRate; alertPlan = plan; } else if (a80 && alert < CallMeter.EIGHTY && usedRate >= CallMeter.EIGHTY) { alert = usedRate; alertPlan = plan; } } if (alert > 0) { final NotificationManager mNotificationMgr = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final String t = String.format(context.getString(R.string.alerts_message), alertPlan.name, alert); NotificationCompat.Builder b = new NotificationCompat.Builder(context); b.setSmallIcon(android.R.drawable.stat_notify_error); b.setTicker(t); b.setWhen(now); b.setContentTitle(context.getString(R.string.alerts_title)); b.setContentText(t); Intent i = new Intent(context, Plans.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); b.setContentIntent(PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); mNotificationMgr.notify(0, b.build()); // set nextAlert to beginning of next day Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); alertPlan.nextAlert = cal.getTimeInMillis(); final ContentValues cv = new ContentValues(); cv.put(DataProvider.Plans.NEXT_ALERT, alertPlan.nextAlert); cr.update(DataProvider.Plans.CONTENT_URI, cv, DataProvider.Plans.ID + " = ?", new String[] { String.valueOf(alertPlan.id) }); } } } long end = System.currentTimeMillis(); Log.i(TAG, "match(): ", end - start, "ms"); return ret; }
From source file:de.unwesen.packrat.api.FeedReader.java
private void updateFeed(Uri uri, Handler handler) { // Log.d(LTAG, "Fetching feed: " + uri); // Convert Uri to URI... yes, it sucks. URI feed_uri = null;/* w w w. j av a 2 s.c om*/ try { feed_uri = new URI(uri.toString()); } catch (URISyntaxException ex) { Log.e(LTAG, "Invalid feed URI: " + uri); Message m = handler.obtainMessage(FR_INVALID_FEED_URI); m.sendToTarget(); return; } // Construct request HttpGet request = new HttpGet(feed_uri); request.addHeader("Referer", REFERER_URL); HttpResponse response; try { response = sClient.execute(request); // Read response HttpEntity entity = response.getEntity(); if (null == entity) { Log.e(LTAG, "Feed is empty: " + uri); Message m = handler.obtainMessage(FR_EMPTY_FEED); m.sendToTarget(); return; } MediaParser parser = new MediaParser(); MediaParser.AtomFeed feed = parser.parse(entity.getContent()); if (null == feed) { Log.e(LTAG, "Unable to parse feed, exiting: " + uri); Message m = handler.obtainMessage(FR_FEED_PARSE_FAILURE); m.sendToTarget(); return; } LinkedList<Media> result = parseFeed(feed); if (null != result && result.size() > 0) { Message m = handler.obtainMessage(FR_SUCCESS, result); m.sendToTarget(); } else { Message m = handler.obtainMessage(FR_EMPTY_FEED); m.sendToTarget(); } } catch (IOException ex) { Log.w(LTAG, "IO exception: " + ex); Message m = handler.obtainMessage(FR_NETWORK_ERROR); m.sendToTarget(); } catch (Exception ex) { Log.e(LTAG, "An exception occurred when reading the feed: " + ex); Message m = handler.obtainMessage(FR_UNKNOWN_ERROR); m.sendToTarget(); } }
From source file:de.unwesen.packrat.api.FeedReader.java
private void webSearch(String term, final Handler handler) { Uri uri = Uri.parse(String.format(WEB_BASE_URI, WEB_SEARCH_API_KEY, Uri.encode(term))); //Log.d(LTAG, "Search URI: " + uri); requestUri(uri, new Handler(new Handler.Callback() { public boolean handleMessage(Message msg) { if (ERR_SUCCESS == msg.what) { String data = (String) msg.obj; handleWebSearchResults(data, handler); } else { handler.obtainMessage(msg.what).sendToTarget(); }/*from ww w.j a va 2 s. c om*/ return true; } })); }
From source file:de.unwesen.packrat.api.FeedReader.java
private void handleWebSearchResults(String data, final Handler handler) { // Log.d(LTAG, "Result: " + data); try {//from w w w .j a v a 2 s. c o m // First check response status. If that is != 200, we may have an error // message to log, and definitely can bail out early. JSONObject result = new JSONObject(data); int status = result.getInt("responseStatus"); if (200 != status) { Log.e(LTAG, "Server error: " + result.getString("responseDetails")); handler.obtainMessage(ERR_SERVER).sendToTarget(); return; } JSONObject d = result.getJSONObject("responseData"); JSONArray res = d.getJSONArray("results"); // Count the occurrences of various words across all returned titles. // If a word is known to designate media type, we'll ignore it. We'll // also ignore words shorter than MIN_WORD_LENGTH. HashMap<String, Integer> wordCount = new HashMap<String, Integer>(); for (int i = 0; i < res.length(); ++i) { JSONObject entry = res.getJSONObject(i); String title = entry.getString("titleNoFormatting"); String[] words = title.split(" "); for (String word : words) { if (MIN_WORD_LENGTH > word.length()) { // Too short continue; } Integer type = sMediaTypes.get(word); if (null != type) { // This word is a media type keyword, so we'll ignore it. continue; } word = word.toLowerCase(); Integer count = wordCount.get(word); if (null == count) { wordCount.put(word, 1); } else { wordCount.put(word, count + 1); } } } // Now that we've counted words, first filter out all words that contain // non-letters. Those are likely not good candidates for further searching. // We ignore them by putting their count to zero. // The tricky part here is that trailing non-letters are likely fine, we // just can't use them for searches. HashMap<String, Integer> filteredWordCount = new HashMap<String, Integer>(); for (String word : wordCount.keySet()) { // Log.d(LTAG, "Word: " + word + " -> " + wordCount.get(word)); int lastLetter = -1; int lastNonLetter = -1; for (int i = 0; i < word.length(); ++i) { int codePoint = word.codePointAt(i); if (Character.isLetter(codePoint) || Character.isDigit(codePoint)) { lastLetter = i; if (lastNonLetter > 0) { // Due to the sequential nature of our iteration, we know that // at(i) is now a letter following a non-letter, so we can // safely ignore this word. break; } } else { lastNonLetter = i; if (-1 == lastLetter) { // We have non-letters preceeding letters, that word should // likely be discarded. break; } } } if (-1 == lastNonLetter) { // Word is pure letters, keep it. filteredWordCount.put(word, wordCount.get(word)); } else if (-1 == lastLetter) { // Word is pure non-letters, discard it. } else if (lastNonLetter > lastLetter) { // Word has trailing non-letters, cut it. Integer count = wordCount.get(word); word = word.substring(0, lastLetter + 1); filteredWordCount.put(word, count); } else { // Word has non-letters in the middle. } } // Next filter step is optional: if we had more than one title to go // through, then chances are that words with only one count should be // ignored. If we had only one title, that's not an optimization we can // safely make. if (1 < res.length()) { wordCount = filteredWordCount; filteredWordCount = new HashMap<String, Integer>(); for (String word : wordCount.keySet()) { int count = wordCount.get(word); if (count > 1) { filteredWordCount.put(word, count); } } } // If we're left with no results, give up right here. if (0 == filteredWordCount.size()) { handler.obtainMessage(ERR_EMPTY_RESPONSE).sendToTarget(); return; } // If we've got results, sort them. List<HashMap.Entry> wordList = new LinkedList<HashMap.Entry>(filteredWordCount.entrySet()); Collections.sort(wordList, new Comparator() { public int compare(Object o1, Object o2) { return -1 * ((Comparable) ((HashMap.Entry) (o1)).getValue()) .compareTo(((HashMap.Entry) (o2)).getValue()); } }); // With the resulting wordList, we'll generate search terms, preferring // more words over fewer words, and words with a higher count over words // with a lower count. WebSearchMachine machine = new WebSearchMachine(wordList, handler); machine.nextTerm(); } catch (JSONException ex) { handler.obtainMessage(ERR_SERIALIZATION).sendToTarget(); } }