Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Delta Between Two Patch Sets: src/org/adblockplus/android/AdblockPlus.java

Issue 8478117: ABP/Android core (Closed)
Left Patch Set: Created Oct. 5, 2012, 9:29 a.m.
Right Patch Set: ABP/Android core Created Oct. 30, 2012, 9:22 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | no next file » | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 package org.adblockplus.android; 1 package org.adblockplus.android;
2 2
3 import java.io.BufferedReader; 3 import java.io.BufferedReader;
4 import java.io.File; 4 import java.io.File;
5 import java.io.FileInputStream; 5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException; 6 import java.io.FileNotFoundException;
7 import java.io.FileOutputStream; 7 import java.io.FileOutputStream;
8 import java.io.IOException; 8 import java.io.IOException;
9 import java.io.InputStreamReader; 9 import java.io.InputStreamReader;
10 import java.net.HttpURLConnection; 10 import java.net.HttpURLConnection;
(...skipping 20 matching lines...) Expand all
31 import org.json.JSONException; 31 import org.json.JSONException;
32 import org.json.JSONObject; 32 import org.json.JSONObject;
33 import org.xml.sax.SAXException; 33 import org.xml.sax.SAXException;
34 34
35 import android.app.AlarmManager; 35 import android.app.AlarmManager;
36 import android.app.Application; 36 import android.app.Application;
37 import android.app.PendingIntent; 37 import android.app.PendingIntent;
38 import android.content.Context; 38 import android.content.Context;
39 import android.content.Intent; 39 import android.content.Intent;
40 import android.content.SharedPreferences; 40 import android.content.SharedPreferences;
41 import android.content.pm.PackageInfo;
41 import android.content.pm.PackageManager; 42 import android.content.pm.PackageManager;
42 import android.content.pm.PackageManager.NameNotFoundException; 43 import android.content.pm.PackageManager.NameNotFoundException;
43 import android.content.res.AssetManager; 44 import android.content.res.AssetManager;
44 import android.net.ConnectivityManager; 45 import android.net.ConnectivityManager;
45 import android.net.NetworkInfo; 46 import android.net.NetworkInfo;
46 import android.os.AsyncTask; 47 import android.os.AsyncTask;
48 import android.os.Build;
47 import android.os.Bundle; 49 import android.os.Bundle;
48 import android.os.Handler; 50 import android.os.Handler;
49 import android.os.Message; 51 import android.os.Message;
50 import android.os.SystemClock; 52 import android.os.SystemClock;
51 import android.preference.PreferenceManager; 53 import android.preference.PreferenceManager;
52 import android.util.Log; 54 import android.util.Log;
53 import android.widget.Toast; 55 import android.widget.Toast;
54 56
55 public class AdblockPlus extends Application 57 public class AdblockPlus extends Application
56 { 58 {
(...skipping 15 matching lines...) Expand all
72 private JSThread js; 74 private JSThread js;
73 75
74 /** 76 /**
75 * Indicates interactive mode (used to listen for subscription status 77 * Indicates interactive mode (used to listen for subscription status
76 * changes). 78 * changes).
77 */ 79 */
78 private boolean interactive = false; 80 private boolean interactive = false;
79 81
80 private boolean generateCrashReport = false; 82 private boolean generateCrashReport = false;
81 83
82 private static AdblockPlus myself; 84 private static AdblockPlus instance;
Felix Dahlke 2012/10/29 15:06:36 Nit: Isn't "instance" a more typical name for a si
Andrey Novikov 2012/10/30 07:53:22 Done.
83 85
84 /** 86 /**
85 * Returns pointer to itself (singleton pattern). 87 * Returns pointer to itself (singleton pattern).
86 */ 88 */
87 public static AdblockPlus getApplication() 89 public static AdblockPlus getApplication()
88 { 90 {
89 return myself; 91 return instance;
92 }
93
94 public int getBuildNumber()
95 {
96 int buildNumber = -1;
97 try
98 {
99 PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
100 buildNumber = pi.versionCode;
101 }
102 catch (NameNotFoundException e)
103 {
104 // ignore - this shouldn't happen
105 Log.e(TAG, e.getMessage(), e);
106 }
107 return buildNumber;
108 }
109
110 /**
111 * Returns device name in user-friendly format
112 */
113 public static String getDeviceName()
114 {
115 String manufacturer = Build.MANUFACTURER;
116 String model = Build.MODEL;
117 if (model.startsWith(manufacturer))
118 return capitalize(model);
119 else
120 return capitalize(manufacturer) + " " + model;
121 }
122
123 private static String capitalize(String s)
124 {
125 if (s == null || s.length() == 0)
126 return "";
127 char first = s.charAt(0);
128 if (Character.isUpperCase(first))
129 return s;
130 else
131 return Character.toUpperCase(first) + s.substring(1);
90 } 132 }
91 133
92 /** 134 /**
93 * Checks if device has a WiFi connection available. 135 * Checks if device has a WiFi connection available.
94 */ 136 */
95 public static boolean isWiFiConnected(Context context) 137 public static boolean isWiFiConnected(Context context)
96 { 138 {
97 ConnectivityManager connectivityManager = (ConnectivityManager) context.getS ystemService(Context.CONNECTIVITY_SERVICE); 139 ConnectivityManager connectivityManager = (ConnectivityManager) context.getS ystemService(Context.CONNECTIVITY_SERVICE);
98 NetworkInfo networkInfo = null; 140 NetworkInfo networkInfo = null;
99 if (connectivityManager != null) 141 if (connectivityManager != null)
(...skipping 23 matching lines...) Expand all
123 { 165 {
124 subscriptions = new ArrayList<Subscription>(); 166 subscriptions = new ArrayList<Subscription>();
125 167
126 SAXParserFactory factory = SAXParserFactory.newInstance(); 168 SAXParserFactory factory = SAXParserFactory.newInstance();
127 SAXParser parser; 169 SAXParser parser;
128 try 170 try
129 { 171 {
130 parser = factory.newSAXParser(); 172 parser = factory.newSAXParser();
131 parser.parse(getAssets().open("subscriptions.xml"), new SubscriptionPars er(subscriptions)); 173 parser.parse(getAssets().open("subscriptions.xml"), new SubscriptionPars er(subscriptions));
132 } 174 }
133 catch (ParserConfigurationException e) 175 catch (ParserConfigurationException e)
Felix Dahlke 2012/10/29 15:06:36 Can we log the following exceptions as an error in
Andrey Novikov 2012/10/30 07:53:22 printStackTrace does pretty much the same, I use i
Felix Dahlke 2012/10/30 08:08:42 I think Log.e() is the canonical way to log except
134 { 176 {
135 // TODO Auto-generated catch block 177 // TODO Auto-generated catch block
136 e.printStackTrace(); 178 Log.e(TAG, e.getMessage(), e);
137 } 179 }
138 catch (SAXException e) 180 catch (SAXException e)
139 { 181 {
140 // TODO Auto-generated catch block 182 // TODO Auto-generated catch block
141 e.printStackTrace(); 183 Log.e(TAG, e.getMessage(), e);
142 } 184 }
143 catch (IOException e) 185 catch (IOException e)
144 { 186 {
145 // TODO Auto-generated catch block 187 // TODO Auto-generated catch block
146 e.printStackTrace(); 188 Log.e(TAG, e.getMessage(), e);
147 } 189 }
148 } 190 }
149 return subscriptions; 191 return subscriptions;
150 } 192 }
151 193
152 /** 194 /**
153 * Returns subscription information. 195 * Returns subscription information.
154 * 196 *
155 * @param url 197 * @param url
156 * subscription url 198 * subscription url
(...skipping 11 matching lines...) Expand all
168 } 210 }
169 211
170 /** 212 /**
171 * Adds provided subscription and removes previous subscriptions if any. 213 * Adds provided subscription and removes previous subscriptions if any.
172 * 214 *
173 * @param subscription 215 * @param subscription
174 * Subscription to add 216 * Subscription to add
175 */ 217 */
176 public void setSubscription(Subscription subscription) 218 public void setSubscription(Subscription subscription)
177 { 219 {
178 /*
179 * Subscription test = new Subscription();
Felix Dahlke 2012/10/29 15:06:36 Can we remove this commented code? It's in source
Andrey Novikov 2012/10/30 07:53:22 Done.
180 * test.url =
181 * "https://easylist-downloads.adblockplus.org/exceptionrules.txt";
182 * test.title = "Test";
183 * test.homepage = "https://easylist-downloads.adblockplus.org/";
184 * selectedItem = test;
185 */
186
187 if (subscription != null) 220 if (subscription != null)
188 { 221 {
189 final JSONObject jsonSub = new JSONObject(); 222 final JSONObject jsonSub = new JSONObject();
190 try 223 try
191 { 224 {
192 jsonSub.put("url", subscription.url); 225 jsonSub.put("url", subscription.url);
193 jsonSub.put("title", subscription.title); 226 jsonSub.put("title", subscription.title);
194 jsonSub.put("homepage", subscription.homepage); 227 jsonSub.put("homepage", subscription.homepage);
195 js.execute(new Runnable() { 228 js.execute(new Runnable()
229 {
196 @Override 230 @Override
197 public void run() 231 public void run()
198 { 232 {
199 js.evaluate("clearSubscriptions()"); 233 js.evaluate("clearSubscriptions()");
200 js.evaluate("addSubscription(\"" + StringEscapeUtils.escapeJavaScrip t(jsonSub.toString()) + "\")"); 234 js.evaluate("addSubscription(\"" + StringEscapeUtils.escapeJavaScrip t(jsonSub.toString()) + "\")");
201 } 235 }
202 }); 236 });
203 } 237 }
204 catch (JSONException e) 238 catch (JSONException e)
205 { 239 {
206 // TODO Auto-generated catch block 240 // TODO Auto-generated catch block
Felix Dahlke 2012/10/29 15:06:36 Can we log this exception as an error instead of u
Andrey Novikov 2012/10/30 09:24:17 Done.
207 e.printStackTrace(); 241 Log.e(TAG, e.getMessage(), e);
208 } 242 }
209 } 243 }
210 } 244 }
211 245
212 /** 246 /**
213 * Forces subscriptions refresh. 247 * Forces subscriptions refresh.
214 */ 248 */
215 public void refreshSubscription() 249 public void refreshSubscription()
216 { 250 {
217 js.execute(new Runnable() { 251 js.execute(new Runnable()
252 {
218 @Override 253 @Override
219 public void run() 254 public void run()
220 { 255 {
221 js.evaluate("refreshSubscriptions()"); 256 js.evaluate("refreshSubscriptions()");
222 } 257 }
223 }); 258 });
224 } 259 }
225 260
226 /** 261 /**
227 * Selects which subscription to offer for the first time. 262 * Selects which subscription to offer for the first time.
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
268 } 303 }
269 304
270 /** 305 /**
271 * Verifies that subscriptions are loaded and returns flag of subscription 306 * Verifies that subscriptions are loaded and returns flag of subscription
272 * presence. 307 * presence.
273 * 308 *
274 * @return true if at least one subscription is present and downloaded 309 * @return true if at least one subscription is present and downloaded
275 */ 310 */
276 public boolean verifySubscriptions() 311 public boolean verifySubscriptions()
277 { 312 {
278 Future<Boolean> future = js.submit(new Callable<Boolean>() { 313 Future<Boolean> future = js.submit(new Callable<Boolean>()
314 {
279 @Override 315 @Override
280 public Boolean call() throws Exception 316 public Boolean call() throws Exception
281 { 317 {
282 Boolean result = (Boolean) js.evaluate("verifySubscriptions()"); 318 Boolean result = (Boolean) js.evaluate("verifySubscriptions()");
283 return result; 319 return result;
284 } 320 }
285 }); 321 });
286 try 322 try
287 { 323 {
288 return future.get().booleanValue(); 324 return future.get().booleanValue();
289 } 325 }
290 catch (InterruptedException e) 326 catch (InterruptedException e)
291 { 327 {
292 // TODO Auto-generated catch block 328 // TODO Auto-generated catch block
Felix Dahlke 2012/10/29 15:06:36 Like above, log an error instead?
Andrey Novikov 2012/10/30 09:24:17 Done.
293 e.printStackTrace(); 329 Log.e(TAG, e.getMessage(), e);
294 } 330 }
295 catch (ExecutionException e) 331 catch (ExecutionException e)
296 { 332 {
297 // TODO Auto-generated catch block 333 // TODO Auto-generated catch block
298 e.printStackTrace(); 334 Log.e(TAG, e.getMessage(), e);
299 } 335 }
300 return false; 336 return false;
301 } 337 }
302 338
303 /** 339 /**
304 * Returns ElemHide selectors for domain. 340 * Returns ElemHide selectors for domain.
305 * 341 *
306 * @return ready to use HTML element with CSS selectors 342 * @return ready to use HTML element with CSS selectors
307 */ 343 */
308 public String getSelectorsForDomain(final String domain) 344 public String getSelectorsForDomain(final String domain)
309 { 345 {
310 Future<String> future = js.submit(new Callable<String>() { 346 Future<String> future = js.submit(new Callable<String>()
Felix Dahlke 2012/10/29 15:06:36 Is the future really necessary here? It seems you
Andrey Novikov 2012/10/30 07:53:22 No, I can't. JS runs in separate asynchronous thre
Felix Dahlke 2012/10/30 08:08:42 Oh, I see.
347 {
311 @Override 348 @Override
312 public String call() throws Exception 349 public String call() throws Exception
313 { 350 {
314 String result = (String) js.evaluate("ElemHide.getSelectorsForDomain('" + domain + "')"); 351 String result = (String) js.evaluate("ElemHide.getSelectorsForDomain('" + domain + "')");
315 return result; 352 return result;
316 } 353 }
317 }); 354 });
318 try 355 try
319 { 356 {
320 return future.get(); 357 return future.get();
321 } 358 }
322 catch (InterruptedException e) 359 catch (InterruptedException e)
323 { 360 {
324 // TODO Auto-generated catch block 361 // TODO Auto-generated catch block
Felix Dahlke 2012/10/29 15:06:36 Like above, error logging.
Andrey Novikov 2012/10/30 09:24:17 Done.
325 e.printStackTrace(); 362 Log.e(TAG, e.getMessage(), e);
326 } 363 }
327 catch (ExecutionException e) 364 catch (ExecutionException e)
328 { 365 {
329 // TODO Auto-generated catch block 366 // TODO Auto-generated catch block
330 e.printStackTrace(); 367 Log.e(TAG, e.getMessage(), e);
331 } 368 }
332 return null; 369 return null;
333 } 370 }
334 371
335 private class MatchesCallable implements Callable<Boolean> 372 private class MatchesCallable implements Callable<Boolean>
336 { 373 {
337 private String url; 374 private String url;
338 private String query; 375 private String query;
339 private String reqHost; 376 private String reqHost;
340 private String refHost; 377 private String refHost;
341 private String accept; 378 private String accept;
342 379
343 MatchesCallable(String url, String query, String reqHost, String refHost, St ring accept) 380 MatchesCallable(String url, String query, String reqHost, String refHost, St ring accept)
344 { 381 {
345 this.url = url; 382 this.url = url;
346 this.query = query; 383 this.query = query;
347 this.reqHost = reqHost != null ? reqHost : ""; 384 this.reqHost = reqHost != null ? reqHost : "";
348 this.refHost = refHost != null ? refHost : ""; 385 this.refHost = refHost != null ? refHost : "";
349 this.accept = accept != null ? accept : ""; 386 this.accept = accept != null ? accept : "";
350 } 387 }
351 388
352 @Override 389 @Override
353 public Boolean call() throws Exception 390 public Boolean call() throws Exception
354 { 391 {
355 Boolean result = (Boolean) js.evaluate("matchesAny('" + url + "', '" + que ry + "', '" + reqHost + "', '" + refHost + "', '" + accept + "');"); 392 Boolean result = (Boolean) js.evaluate("matchesAny('" + url + "', '" + que ry + "', '" + reqHost + "', '" + refHost + "', '" + accept + "');");
Felix Dahlke 2012/10/29 15:06:36 Nit: You could just return this directly
Andrey Novikov 2012/10/30 07:53:22 See above.
356 return result; 393 return result;
357 } 394 }
358 } 395 }
359 396
360 /** 397 /**
361 * Checks if filters match request parameters. 398 * Checks if filters match request parameters.
362 * 399 *
363 * @param url 400 * @param url
364 * Request URL 401 * Request URL
365 * @param query 402 * @param query
(...skipping 14 matching lines...) Expand all
380 boolean matches = future.get().booleanValue(); 417 boolean matches = future.get().booleanValue();
381 sendBroadcast(new Intent(BROADCAST_FILTER_MATCHES).putExtra("url", url).putE xtra("matches", matches)); 418 sendBroadcast(new Intent(BROADCAST_FILTER_MATCHES).putExtra("url", url).putE xtra("matches", matches));
382 return matches; 419 return matches;
383 } 420 }
384 421
385 /** 422 /**
386 * Notifies JS code that application entered interactive mode. 423 * Notifies JS code that application entered interactive mode.
387 */ 424 */
388 public void startInteractive() 425 public void startInteractive()
389 { 426 {
390 js.execute(new Runnable() { 427 js.execute(new Runnable()
428 {
391 @Override 429 @Override
392 public void run() 430 public void run()
393 { 431 {
394 js.evaluate("startInteractive()"); 432 js.evaluate("startInteractive()");
395 } 433 }
396 }); 434 });
397 interactive = true; 435 interactive = true;
398 } 436 }
399 437
400 /** 438 /**
401 * Notifies JS code that application quit interactive mode. 439 * Notifies JS code that application quit interactive mode.
402 */ 440 */
403 public void stopInteractive() 441 public void stopInteractive()
404 { 442 {
405 js.execute(new Runnable() { 443 js.execute(new Runnable()
444 {
406 @Override 445 @Override
407 public void run() 446 public void run()
408 { 447 {
409 js.evaluate("stopInteractive()"); 448 js.evaluate("stopInteractive()");
410 } 449 }
411 }); 450 });
412 interactive = false; 451 interactive = false;
413 } 452 }
414 453
415 /** 454 /**
(...skipping 14 matching lines...) Expand all
430 } 469 }
431 470
432 /** 471 /**
433 * Starts JS engine. It also initiates subscription refresh if it is enabled 472 * Starts JS engine. It also initiates subscription refresh if it is enabled
434 * in user settings. 473 * in user settings.
435 */ 474 */
436 public void startEngine() 475 public void startEngine()
437 { 476 {
438 if (js == null) 477 if (js == null)
439 { 478 {
440 Log.e(TAG, "startEngine"); 479 Log.i(TAG, "startEngine");
Felix Dahlke 2012/10/29 15:06:36 Shouldn't this be Log.d()?
Andrey Novikov 2012/10/30 07:53:22 I use logging not only for error reporting but als
Felix Dahlke 2012/10/30 08:08:42 That's fine for debugging of course, but I think w
Andrey Novikov 2012/10/30 09:24:17 Done.
441 js = new JSThread(this); 480 js = new JSThread(this);
442 js.start(); 481 js.start();
443 482
444 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferen ces(this); 483 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferen ces(this);
445 final int refresh = Integer.valueOf(prefs.getString(getString(R.string.pre f_refresh), Integer.toString(getResources().getInteger(R.integer.def_refresh)))) ; 484 final int refresh = Integer.valueOf(prefs.getString(getString(R.string.pre f_refresh), Integer.toString(getResources().getInteger(R.integer.def_refresh)))) ;
Felix Dahlke 2012/10/29 15:06:36 We should use a fixed string for storing these pre
Andrey Novikov 2012/10/30 07:53:22 These are not locale dependent. Locale dependent s
Felix Dahlke 2012/10/30 08:08:42 The string "pref_refresh" is "Subscription refresh
Andrey Novikov 2012/10/30 09:24:17 No, the string pref_refresh is "refresh", and what
Felix Dahlke 2012/10/30 09:30:50 True, repeated string literals aren't great. How a
446 final boolean wifionly = prefs.getBoolean(getString(R.string.pref_wifirefr esh), getResources().getBoolean(R.bool.def_wifirefresh)); 485 final boolean wifionly = prefs.getBoolean(getString(R.string.pref_wifirefr esh), getResources().getBoolean(R.bool.def_wifirefresh));
447 // Refresh if user selected refresh on each start 486 // Refresh if user selected refresh on each start
448 if (refresh == 1 && (!wifionly || isWiFiConnected(this))) 487 if (refresh == 1 && (!wifionly || isWiFiConnected(this)))
449 { 488 {
450 refreshSubscription(); 489 refreshSubscription();
451 } 490 }
452 } 491 }
453 } 492 }
454 493
455 /** 494 /**
456 * Stops JS engine. 495 * Stops JS engine.
457 * 496 *
458 * @param implicitly 497 * @param implicitly
459 * stop even in interactive mode 498 * stop even in interactive mode
460 */ 499 */
461 public void stopEngine(boolean implicitly) 500 public void stopEngine(boolean implicitly)
462 { 501 {
463 if ((implicitly || !interactive) && js != null) 502 if ((implicitly || !interactive) && js != null)
464 { 503 {
465 js.stopEngine(); 504 js.stopEngine();
466 try 505 try
467 { 506 {
468 js.join(); 507 js.join();
469 } 508 }
470 catch (InterruptedException e) 509 catch (InterruptedException e)
471 { 510 {
472 e.printStackTrace(); 511 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 As before, error logging?
Andrey Novikov 2012/10/30 09:24:17 Done.
473 } 512 }
474 js = null; 513 js = null;
475 } 514 }
476 } 515 }
477 516
478 /** 517 /**
479 * Sets or removes crash handler according to user setting 518 * Sets or removes crash handler according to user setting
480 */ 519 */
481 public void updateCrashReportStatus() 520 public void updateCrashReportStatus()
482 { 521 {
(...skipping 15 matching lines...) Expand all
498 catch (ClassCastException e) 537 catch (ClassCastException e)
499 { 538 {
500 // ignore - already default handler 539 // ignore - already default handler
501 } 540 }
502 } 541 }
503 generateCrashReport = report; 542 generateCrashReport = report;
504 } 543 }
505 } 544 }
506 545
507 /** 546 /**
508 * Sets Alarm to call updater after specified number of minutes or after one d ay if 547 * Sets Alarm to call updater after specified number of minutes or after one
548 * day if
509 * minutes are set to 0. 549 * minutes are set to 0.
510 * 550 *
511 * @param minutes 551 * @param minutes
512 * number of minutes to wait 552 * number of minutes to wait
513 */ 553 */
514 public void scheduleUpdater(int minutes) 554 public void scheduleUpdater(int minutes)
515 { 555 {
516 Calendar updateTime = Calendar.getInstance(); 556 Calendar updateTime = Calendar.getInstance();
517 557
518 if (minutes == 0) 558 if (minutes == 0)
519 { 559 {
520 // Start update checks at 10:00 GMT... 560 // Start update checks at 10:00 GMT...
521 updateTime.setTimeZone(TimeZone.getTimeZone("GMT")); 561 updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
522 updateTime.set(Calendar.HOUR_OF_DAY, 10); 562 updateTime.set(Calendar.HOUR_OF_DAY, 10);
523 updateTime.set(Calendar.MINUTE, 0); 563 updateTime.set(Calendar.MINUTE, 0);
524 // ...next day 564 // ...next day
525 updateTime.add(Calendar.HOUR_OF_DAY, 24); 565 updateTime.add(Calendar.HOUR_OF_DAY, 24);
526 // Spread out the “mass downloading” for 6 hours 566 // Spread out the “mass downloading” for 6 hours
527 updateTime.add(Calendar.MINUTE, (int) Math.random() * 60 * 6); 567 updateTime.add(Calendar.MINUTE, (int) Math.random() * 60 * 6);
528 } 568 }
529 else 569 else
530 { 570 {
531 updateTime.add(Calendar.MINUTE, minutes); 571 updateTime.add(Calendar.MINUTE, minutes);
532 } 572 }
533 573
534 Intent updater = new Intent(this, AlarmReceiver.class); 574 Intent updater = new Intent(this, AlarmReceiver.class);
535 PendingIntent recurringUpdate = PendingIntent.getBroadcast(this, 0, updater, PendingIntent.FLAG_CANCEL_CURRENT); 575 PendingIntent recurringUpdate = PendingIntent.getBroadcast(this, 0, updater, PendingIntent.FLAG_CANCEL_CURRENT);
536 // Set non-waking alarm 576 // Set non-waking alarm
537 AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE) ; 577 AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE) ;
538 Log.e(TAG, "Set updater alarm");
Felix Dahlke 2012/10/29 15:06:36 I guess Log.d() is more appropriate here?
Andrey Novikov 2012/10/30 09:24:17 Done.
539 alarms.set(AlarmManager.RTC, updateTime.getTimeInMillis(), recurringUpdate); 578 alarms.set(AlarmManager.RTC, updateTime.getTimeInMillis(), recurringUpdate);
540 } 579 }
541 580
542 @Override 581 @Override
543 public void onCreate() 582 public void onCreate()
544 { 583 {
545 super.onCreate(); 584 super.onCreate();
546 myself = this; 585 instance = this;
547 586
548 // Check for crash report 587 // Check for crash report
549 try 588 try
550 { 589 {
551 InputStreamReader reportFile = new InputStreamReader(openFileInput(CrashHa ndler.REPORT_FILE)); 590 InputStreamReader reportFile = new InputStreamReader(openFileInput(CrashHa ndler.REPORT_FILE));
552 final char[] buffer = new char[0x1000]; 591 final char[] buffer = new char[0x1000];
553 StringBuilder out = new StringBuilder(); 592 StringBuilder out = new StringBuilder();
554 int read; 593 int read;
555 do 594 do
556 { 595 {
(...skipping 10 matching lines...) Expand all
567 intent.putExtra("report", report); 606 intent.putExtra("report", report);
568 startActivity(intent); 607 startActivity(intent);
569 } 608 }
570 } 609 }
571 catch (FileNotFoundException e) 610 catch (FileNotFoundException e)
572 { 611 {
573 // ignore 612 // ignore
574 } 613 }
575 catch (IOException e) 614 catch (IOException e)
576 { 615 {
577 // TODO Auto-generated catch block 616 // TODO Auto-generated catch block
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
578 e.printStackTrace(); 617 Log.e(TAG, e.getMessage(), e);
579 } 618 }
580 619
581 if (!getResources().getBoolean(R.bool.def_release)) 620 if (!getResources().getBoolean(R.bool.def_release))
582 { 621 {
583 // Set crash handler 622 // Set crash handler
584 updateCrashReportStatus(); 623 updateCrashReportStatus();
585 // Initiate update check 624 // Initiate update check
586 scheduleUpdater(0); 625 scheduleUpdater(0);
587 } 626 }
588 } 627 }
589 628
590 /** 629 /**
591 * Handler for showing toast messages from JS code. 630 * Handler for showing toast messages from JS code.
592 */ 631 */
593 private final Handler messageHandler = new Handler() { 632 private static final Handler messageHandler = new Handler()
633 {
594 public void handleMessage(Message msg) 634 public void handleMessage(Message msg)
595 { 635 {
596 if (msg.what == MSG_TOAST) 636 if (msg.what == MSG_TOAST)
597 { 637 {
598 Toast.makeText(AdblockPlus.this, msg.getData().getString("message"), Toa st.LENGTH_LONG).show(); 638 Toast.makeText(AdblockPlus.getApplication(), msg.getData().getString("me ssage"), Toast.LENGTH_LONG).show();
599 } 639 }
600 } 640 }
601 }; 641 };
602 642
603 /** 643 /**
604 * JS execution thread. 644 * JS execution thread.
605 */ 645 */
606 private final class JSThread extends Thread 646 private final class JSThread extends Thread
607 { 647 {
608 private JSEngine jsEngine; 648 private JSEngine jsEngine;
(...skipping 23 matching lines...) Expand all
632 { 672 {
633 read = reader.read(buffer, 0, buffer.length); 673 read = reader.read(buffer, 0, buffer.length);
634 if (read > 0) 674 if (read > 0)
635 out.append(buffer, 0, read); 675 out.append(buffer, 0, read);
636 } 676 }
637 while (read >= 0); 677 while (read >= 0);
638 result = out.toString(); 678 result = out.toString();
639 } 679 }
640 catch (IOException e) 680 catch (IOException e)
641 { 681 {
642 e.printStackTrace(); 682 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
643 } 683 }
644 return result; 684 return result;
645 } 685 }
646 686
647 // JS helper 687 // JS helper
648 public FileInputStream getInputStream(String path) 688 public FileInputStream getInputStream(String path)
649 { 689 {
650 Log.e(TAG, path); 690 Log.d(TAG, path);
Felix Dahlke 2012/10/29 15:06:36 Log.d()?
Andrey Novikov 2012/10/30 09:24:17 Done.
651 File f = new File(path); 691 File f = new File(path);
652 try 692 try
653 { 693 {
654 return openFileInput(f.getName()); 694 return openFileInput(f.getName());
655 } 695 }
656 catch (FileNotFoundException e) 696 catch (FileNotFoundException e)
657 { 697 {
658 e.printStackTrace(); 698 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
659 } 699 }
660 return null; 700 return null;
661 } 701 }
662 702
663 // JS helper 703 // JS helper
664 public FileOutputStream getOutputStream(String path) 704 public FileOutputStream getOutputStream(String path)
665 { 705 {
666 Log.e(TAG, path); 706 Log.d(TAG, path);
Felix Dahlke 2012/10/29 15:06:36 Log.d()?
Andrey Novikov 2012/10/30 09:24:17 Done.
667 File f = new File(path); 707 File f = new File(path);
668 try 708 try
669 { 709 {
670 return openFileOutput(f.getName(), MODE_PRIVATE); 710 return openFileOutput(f.getName(), MODE_PRIVATE);
671 } 711 }
672 catch (FileNotFoundException e) 712 catch (FileNotFoundException e)
673 { 713 {
674 e.printStackTrace(); 714 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
675 } 715 }
676 return null; 716 return null;
677 } 717 }
678 718
679 // JS helper 719 // JS helper
680 public String getVersion() 720 public String getVersion()
681 { 721 {
682 String versionName = null; 722 String versionName = null;
683 try 723 try
684 { 724 {
(...skipping 13 matching lines...) Expand all
698 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferen ces(context); 738 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferen ces(context);
699 final int refresh = Integer.valueOf(prefs.getString(getString(R.string.pre f_refresh), Integer.toString(context.getResources().getInteger(R.integer.def_ref resh)))); 739 final int refresh = Integer.valueOf(prefs.getString(getString(R.string.pre f_refresh), Integer.toString(context.getResources().getInteger(R.integer.def_ref resh))));
700 final boolean wifionly = prefs.getBoolean(getString(R.string.pref_wifirefr esh), getResources().getBoolean(R.bool.def_wifirefresh)); 740 final boolean wifionly = prefs.getBoolean(getString(R.string.pref_wifirefr esh), getResources().getBoolean(R.bool.def_wifirefresh));
701 return refresh == 2 && (!wifionly || isWiFiConnected(context)); 741 return refresh == 2 && (!wifionly || isWiFiConnected(context));
702 } 742 }
703 743
704 // JS helper 744 // JS helper
705 @SuppressWarnings("unused") 745 @SuppressWarnings("unused")
706 public void httpSend(final String method, final String url, final String[][] headers, final boolean async, final long callback) 746 public void httpSend(final String method, final String url, final String[][] headers, final boolean async, final long callback)
707 { 747 {
708 Log.e(TAG, "httpSend('" + method + "', '" + url + "')"); 748 Log.d(TAG, "httpSend('" + method + "', '" + url + "')");
Felix Dahlke 2012/10/29 15:06:36 Log.d()?
Andrey Novikov 2012/10/30 09:24:17 Done.
709 messageHandler.post(new Runnable() { 749 messageHandler.post(new Runnable()
750 {
710 @Override 751 @Override
711 public void run() 752 public void run()
712 { 753 {
713 try 754 try
714 { 755 {
715 Task task = new Task(); 756 Task task = new Task();
716 task.callback = callback; 757 task.callback = callback;
717 task.connection = (HttpURLConnection) new URL(url).openConnection(); 758 task.connection = (HttpURLConnection) new URL(url).openConnection();
718 task.connection.setRequestMethod(method); 759 task.connection.setRequestMethod(method);
719 for (int i = 0; i < headers.length; i++) 760 for (int i = 0; i < headers.length; i++)
720 { 761 {
721 task.connection.setRequestProperty(headers[i][0], headers[i][1]); 762 task.connection.setRequestProperty(headers[i][0], headers[i][1]);
722 } 763 }
723 DownloadTask downloadTask = new DownloadTask(context); 764 DownloadTask downloadTask = new DownloadTask(context);
724 downloadTask.execute(task); 765 downloadTask.execute(task);
725 if (!async) 766 if (!async)
726 { 767 {
727 downloadTask.get(); 768 downloadTask.get();
728 } 769 }
729 } 770 }
730 catch (Exception e) 771 catch (Exception e)
731 { 772 {
732 e.printStackTrace(); 773 Log.e(TAG, e.getMessage(), e);
733 js.callback(callback, null); 774 js.callback(callback, null);
734 } 775 }
735 } 776 }
736 }); 777 });
737 } 778 }
738 779
739 // JS helper 780 // JS helper
740 @SuppressWarnings("unused") 781 @SuppressWarnings("unused")
Felix Dahlke 2012/10/29 15:06:36 I don't think this is necessary
Andrey Novikov 2012/10/30 07:53:22 This is necessary because Eclipse highlights all w
Felix Dahlke 2012/10/30 08:08:42 I know what it's for, but I can't see any unused v
Andrey Novikov 2012/10/30 09:24:17 It's not about variables but about the method itse
Felix Dahlke 2012/10/30 09:30:50 Ah, I see. You only need that code for debugging?
Andrey Novikov 2012/10/30 09:45:28 No, it's called by JS engine from native code, tha
741 public void setStatus(String text, long time) 782 public void setStatus(String text, long time)
742 { 783 {
743 sendBroadcast(new Intent(BROADCAST_SUBSCRIPTION_STATUS).putExtra("text", t ext).putExtra("time", time)); 784 sendBroadcast(new Intent(BROADCAST_SUBSCRIPTION_STATUS).putExtra("text", t ext).putExtra("time", time));
744 } 785 }
745 786
746 // JS helper 787 // JS helper
747 @SuppressWarnings("unused") 788 @SuppressWarnings("unused")
Felix Dahlke 2012/10/29 15:06:36 I don't think this is necessary
748 public void showToast(String text) 789 public void showToast(String text)
749 { 790 {
750 Log.e(TAG, "Toast: " + text); 791 Log.d(TAG, "Toast: " + text);
751 Message msg = messageHandler.obtainMessage(MSG_TOAST); 792 Message msg = messageHandler.obtainMessage(MSG_TOAST);
Felix Dahlke 2012/10/29 15:06:36 Log.d()?
Andrey Novikov 2012/10/30 09:24:17 Done.
752 Bundle data = new Bundle(); 793 Bundle data = new Bundle();
753 data.putString("message", text); 794 data.putString("message", text);
754 msg.setData(data); 795 msg.setData(data);
755 messageHandler.sendMessage(msg); 796 messageHandler.sendMessage(msg);
756 } 797 }
757 798
758 // JS helper 799 // JS helper
759 @SuppressWarnings("unused") 800 @SuppressWarnings("unused")
Felix Dahlke 2012/10/29 15:06:36 I don't think this is necessary
760 public void notify(long delay) 801 public void notify(long delay)
761 { 802 {
762 if (this.delay < 0 || delay < this.delay) 803 if (this.delay < 0 || delay < this.delay)
763 { 804 {
764 this.delay = delay; 805 this.delay = delay;
765 synchronized (queue) 806 synchronized (queue)
766 { 807 {
767 queue.notify(); 808 queue.notify();
768 } 809 }
769 } 810 }
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
813 jsEngine.put("_datapath", getFilesDir().getAbsolutePath()); 854 jsEngine.put("_datapath", getFilesDir().getAbsolutePath());
814 jsEngine.put("_separator", File.separator); 855 jsEngine.put("_separator", File.separator);
815 jsEngine.put("_version", getVersion()); 856 jsEngine.put("_version", getVersion());
816 857
817 try 858 try
818 { 859 {
819 jsEngine.evaluate("Android.load(\"start.js\");"); 860 jsEngine.evaluate("Android.load(\"start.js\");");
820 } 861 }
821 catch (Exception e) 862 catch (Exception e)
822 { 863 {
823 e.printStackTrace(); 864 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
824 } 865 }
825 866
826 while (run) 867 while (run)
827 { 868 {
828 try 869 try
829 { 870 {
830 Runnable r = null; 871 Runnable r = null;
831 synchronized (queue) 872 synchronized (queue)
832 { 873 {
833 r = queue.poll(); 874 r = queue.poll();
834 } 875 }
835 if (r != null) 876 if (r != null)
836 { 877 {
837 r.run(); 878 r.run();
838 } 879 }
839 else if (delay > 0) 880 else if (delay > 0)
840 { 881 {
841 long t = SystemClock.uptimeMillis(); 882 long t = SystemClock.uptimeMillis();
842 synchronized (queue) 883 synchronized (queue)
843 { 884 {
844 try 885 try
845 { 886 {
846 queue.wait(delay); 887 queue.wait(delay);
847 } 888 }
848 catch (InterruptedException e) 889 catch (InterruptedException e)
849 { 890 {
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
850 } 891 }
851 } 892 }
852 delay -= SystemClock.uptimeMillis() - t; 893 delay -= SystemClock.uptimeMillis() - t;
853 } 894 }
854 else if (delay <= 0) 895 else if (delay <= 0)
855 { 896 {
856 delay = jsEngine.runCallbacks(); 897 delay = jsEngine.runCallbacks();
857 } 898 }
858 else 899 else
859 { 900 {
860 synchronized (queue) 901 synchronized (queue)
861 { 902 {
862 try 903 try
863 { 904 {
864 queue.wait(); 905 queue.wait();
865 } 906 }
866 catch (InterruptedException e) 907 catch (InterruptedException e)
867 { 908 {
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
909 Log.e(TAG, e.getMessage(), e);
868 } 910 }
869 } 911 }
870 } 912 }
871 } 913 }
872 catch (Exception e) 914 catch (Exception e)
873 { 915 {
874 e.printStackTrace(); 916 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
875 } 917 }
876 } 918 }
877 919
878 jsEngine.release(); 920 jsEngine.release();
879 } 921 }
880 } 922 }
881 923
882 /** 924 /**
883 * Helper class for XMLHttpRequest implementation. 925 * Helper class for XMLHttpRequest implementation.
884 */ 926 */
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
931 { 973 {
932 headers[i][0] = header; 974 headers[i][0] = header;
933 headers[i][1] = StringUtils.join(result.headers.get(header).toArray( ), "; "); 975 headers[i][1] = StringUtils.join(result.headers.get(header).toArray( ), "; ");
934 i++; 976 i++;
935 } 977 }
936 } 978 }
937 params[0] = result.code; 979 params[0] = result.code;
938 params[1] = result.message; 980 params[1] = result.message;
939 params[2] = headers; 981 params[2] = headers;
940 params[3] = result.data; 982 params[3] = result.data;
941 js.execute(new Runnable() { 983 js.execute(new Runnable()
984 {
942 @Override 985 @Override
943 public void run() 986 public void run()
944 { 987 {
945 js.callback(callback, params); 988 js.callback(callback, params);
946 } 989 }
947 990
948 }); 991 });
949 } 992 }
950 } 993 }
951 994
952 @Override 995 @Override
953 protected void onCancelled() 996 protected void onCancelled()
954 { 997 {
955 } 998 }
956 999
957 @Override 1000 @Override
958 protected Result doInBackground(Task... tasks) 1001 protected Result doInBackground(Task... tasks)
959 { 1002 {
960 Task task = tasks[0]; 1003 Task task = tasks[0];
961 Result result = new Result(); 1004 Result result = new Result();
962 result.callback = task.callback; 1005 result.callback = task.callback;
963 try 1006 try
964 { 1007 {
965 HttpURLConnection connection = task.connection; 1008 HttpURLConnection connection = task.connection;
966 connection.connect(); 1009 connection.connect();
967 int lenghtOfFile = connection.getContentLength(); 1010 int lenghtOfFile = connection.getContentLength();
968 Log.w("D", "S: " + lenghtOfFile); 1011 Log.d("D", "S: " + lenghtOfFile);
Felix Dahlke 2012/10/29 15:06:36 Log.d()?
Andrey Novikov 2012/10/30 09:24:17 Done.
969 1012
970 result.code = connection.getResponseCode(); 1013 result.code = connection.getResponseCode();
971 result.message = connection.getResponseMessage(); 1014 result.message = connection.getResponseMessage();
972 result.headers = connection.getHeaderFields(); 1015 result.headers = connection.getHeaderFields();
973 1016
974 // download the file 1017 // download the file
975 String encoding = connection.getContentEncoding(); 1018 String encoding = connection.getContentEncoding();
976 if (encoding == null) 1019 if (encoding == null)
977 encoding = "utf-8"; 1020 encoding = "utf-8";
978 BufferedReader in = new BufferedReader(new InputStreamReader(connection. getInputStream(), encoding)); 1021 BufferedReader in = new BufferedReader(new InputStreamReader(connection. getInputStream(), encoding));
979 1022
980 final char[] buffer = new char[0x10000]; 1023 final char[] buffer = new char[0x10000];
Felix Dahlke 2012/10/29 15:06:36 Reminds me of the code up there, maybe have a sing
Andrey Novikov 2012/10/30 07:53:22 No, I can't. At least do not know how. Because her
981 StringBuilder out = new StringBuilder(); 1024 StringBuilder out = new StringBuilder();
982 long total = 0; 1025 long total = 0;
983 int read; 1026 int read;
984 do 1027 do
985 { 1028 {
986 read = in.read(buffer, 0, buffer.length); 1029 read = in.read(buffer, 0, buffer.length);
987 if (read > 0) 1030 if (read > 0)
988 { 1031 {
989 out.append(buffer, 0, read); 1032 out.append(buffer, 0, read);
990 total += read; 1033 total += read;
991 publishProgress((int) (total * 100. / lenghtOfFile)); 1034 publishProgress((int) (total * 100. / lenghtOfFile));
992 } 1035 }
993 } 1036 }
994 while (!isCancelled() && read >= 0); 1037 while (!isCancelled() && read >= 0);
995 result.data = out.toString(); 1038 result.data = out.toString();
996 in.close(); 1039 in.close();
997 } 1040 }
998 catch (Exception e) 1041 catch (Exception e)
999 { 1042 {
1000 e.printStackTrace(); 1043 Log.e(TAG, e.getMessage(), e);
Felix Dahlke 2012/10/29 15:06:36 Log.e()?
Andrey Novikov 2012/10/30 09:24:17 Done.
1001 result.data = ""; 1044 result.data = "";
1002 result.code = HttpURLConnection.HTTP_INTERNAL_ERROR; 1045 result.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
1003 result.message = e.toString(); 1046 result.message = e.toString();
1004 } 1047 }
1005 return result; 1048 return result;
1006 } 1049 }
1007 1050
1008 protected void onProgressUpdate(Integer... progress) 1051 protected void onProgressUpdate(Integer... progress)
1009 { 1052 {
1010 Log.i("HTTP", "Progress: " + progress[0].intValue()); 1053 Log.d("HTTP", "Progress: " + progress[0].intValue());
1011 } 1054 }
1012 } 1055 }
1013 } 1056 }
LEFTRIGHT
« no previous file | no next file » | Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Toggle Comments ('s')

Powered by Google App Engine
This is Rietveld