[关闭]
@mSolo 2015-04-23T08:42:57.000000Z 字数 8713 阅读 2036

Android 知识碎片笔记(二)

Android


6. Android Manifest Package 初探

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.androidbook.library.testlibraryapp"
  3. sharedUserId="com.androidbook.mysharedusrid"
  4. ...

在应用间共享数据

  1. //Identify package you want to use
  2. String targetPackageName="com.androidbook.samplepackage1";
  3. //Decide on an appropriate context flag
  4. int flag=Context.CONTEXT_RESTRICTED;
  5. //Get the target context through one of your activities
  6. Activity myContext = ……;
  7. Context targetContext = myContext.createPackageContext(targetPackageName, flag);
  8. //Use context to resolve file paths
  9. Resources res = targetContext.getResources();
  10. File path = targetContext.getFilesDir();

7. 线程通信

管道(Pipes)

  1. r = new PipedReader();
  2. w = new PipedWriter();
  3. try {
  4. w.connect(r);
  5. } catch (IOException e) {
  6. e.printStackTrace();
  7. }

Handler,请参考第 8 节

Binder,请参考这里

8. 研究 Handlers

A handler is a mechanism to drop a message on the main queue(Looper) so that the message can be processed at a later point in time by the main thread.
a). More precisely, the queue attached to the thread on which the handler is instantiated
b). The message that is dropped has an internal reference pointing to the handler that dropped it.

  1. Handler handler = new Handler(Looper.getMainLooper());
  2. handler.post(new Runnable(){
  3. public void run() {
  4. // do some work on the main thread.
  5. }
  6. });
  7. handler.postAtFrontOfQueue(new Runnable(){
  8. public void run() {
  9. // do some work on the main thread.
  10. }
  11. });
  12. handler.postDelayed(new Runnable(){
  13. public void run() {
  14. // do some work on the main thread in 10 seconds time
  15. }
  16. }, TimeUnit.SECONDS.toMillis(10));
  17. final Runnable runnable = new Runnable(){
  18. public void run() {
  19. // … do some work
  20. }
  21. };
  22. handler.postDelayed(runnable, TimeUnit.SECONDS.toMillis(10));
  23. Button cancel = (Button) findViewById(R.id.cancel);
  24. cancel.setOnClickListener(new OnClickListener(){
  25. public void onClick(View v) {
  26. handler.removeCallbacks(runnable);
  27. }
  28. });

IdleHandler

  1. // Get the message queue of the current thread.
  2. MessageQueue mq = Looper.myQueue();
  3. // Create and register an idle listener.
  4. MessageQueue.IdleHandler idleHandler = new MessageQueue.IdleHandler();
  5. mq.addIdleHandler(idleHandler)
  6. // Unregister an idle listener.
  7. mq.removeIdleHandler(idleHandler)

使用 Handler

与 UIThread 通信要点

  1. private void postFromUiThreadToUiThread() {
  2. new Handler().post(new Runnable() { ... });
  3. // The code at this point is part of a message being processed
  4. // and is executed before the posted message.
  5. }
  6. private void postFromUiThreadToUiThread() {
  7. runOnUiThread(new Runnable() { ... });
  8. // The code at this point is executed after the message.
  9. }

理解 Looper

A Looper is a mechanism that quite literally loops forever, waiting for Messages to be added to its queue and dispatching them to target Handlers.

  1. class SimpleLooper extends Thread {
  2. public Handler handler;
  3. public void run() {
  4. Looper.prepare();
  5. handler = new Handler();
  6. Looper.loop();
  7. }
  8. }

使用 Message

Sending Messages versus posting Runnables
The runtime difference mostly comes down to efficiency. Creating new instances of Runnable each time we want our Handler to do something adds garbage collection overhead, while sending messages re-uses Message instances, which are sourced from an application-wide pool.

发现线程

  1. Thread t = Thread.currentThread();
  2. t.getId();
  3. t.getName();
  4. t.getPriority();
  5. t.getThreadGroup().getName();
  6. public static void logThreadSignature(){
  7. Log.d("ThreadUtils", getThreadSignature());
  8. }

主线程与工作线程示例

  1. public class WorkerThreadRunnable implements Runnable
  2. {
  3. //the handler to communicate with the main thread Set this in the constructor
  4. Handler statusBackMainThreadHandler = null;
  5. public WorkerThreadRunnable(Handler h) {
  6. statusBackMainThreadHandler = h;
  7. }
  8. public void run() {
  9. informStart();
  10. for(int i=1;i <= 5;i++) {
  11. //In the real world instead of sleeping work will be done here.
  12. Utils.sleepForInSecs(1);
  13. //Report back the work is progressing
  14. informMiddle(i);
  15. }
  16. informFinish();
  17. }
  18. public void informStart() {
  19. Message m = this.statusBackMainThreadHandler.obtainMessage();
  20. m.setData(Utils.getStringAsABundle("starting run"));
  21. this.statusBackmainThreadHandler.sendMessage(m);
  22. }
  23. // ...
  24. }

9. 研究 AsyncTask

  1. protected Result doInBackground(Params params)
  2. protected void onPreExecute() // Main Thread
  3. protected void onProgressUpdate(Progress values) // Main Thread
  4. protected void onPostExecute(Result result) // Main Thread
  5. protected void onCancelled(Result result)
  1. private static final Queue<Runnable> QUEUE = new LinkedBlockingQueue<Runnable>();
  2. public static final Executor MY_EXECUTOR =
  3. new ThreadPoolExecutor(4, 8, 1, TimeUnit.MINUTES, QUEUE);
  4. task.executeOnExecutor(MY_EXECUTOR, params);

内存泄漏、浪费电量等

A common usage of AsyncTask is to declare it as an anonymous inner class of the host Activity, which creates an implicit reference to the Activity and an even bigger memory leak.

10. 理解 Intents

  1. public static void invokeMyApplication(Activity parentActivity) {
  2. String actionName= "com.androidbook.intent.action.ShowBasicView";
  3. Intent intent = new Intent(actionName);
  4. parentActivity.startActivity(intent);
  5. }

Intent属性

  1. <activity......>
  2. <intent-filter>
  3. <action android:name="android.intent.action.VIEW" />
  4. <data android:scheme="http"/>
  5. <data android:scheme="https"/>
  6. </intent-filter>
  7. </activity>

直接唤起特定的 Activity

  1. Intent intent = new Intent();
  2. intent.setComponent(new ComponentName(
  3. "com.android.contacts",
  4. "com.android.contacts.DialContactsEntryActivity");
  5. startActivity(intent);

理解 Intent Categories

  1. //Go to home screen
  2. Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
  3. mainIntent.addCategory(Intent.CATEGORY_HOME);
  4. startActivity(mainIntent);

Android 平台发送的广播 Intent

Action Description
ACTION_BATTERY_CHANGED Sent when the battery charge level or charging state changes
ACTION_BOOT_COMPLETED Sent when the platform completes booting
ACTION_PACKAGE_ADDED Sent when a package is added to the platform
ACTION_PACKAGE_REMOVED Sent when a package is removed from the platform
ACTION_TIME_CHANGED Sent when the user changes the time on the device
ACTION_TIME_TICK Sent every minute to indicate that time is ticking
ACTION_TIMEZONE_CHANGED Sent when the user changes the time
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注