顯示具有 androidComponents 標籤的文章。 顯示所有文章
顯示具有 androidComponents 標籤的文章。 顯示所有文章

2013年1月20日 星期日

[Android] Service notices

  • Service 會被開啟在和 caller 同個 process 中,並且執行在 main thread 中,所以若是要在 service 中執行耗時動作時,必須執行在 background thread 中。
  • 如果想讓 service 執行在另一個 process 中,則可在 AndroidManifest 中宣告 android:process=":process_description"。
    • 此 service 有自己的分配空間。
    • a garbage collection, will not affect the user interface of your Activity。
    • 其中的 ":" 是表示此 service 為我們 application 私有的,若是沒有宣告,則表示是全域的而其他人也能存在到。
    • 當 service 執行在另外的 process,則需透過 interprocess communication (IPC) 與其溝通。


Binding to local service
  • If the Service is started in the same process as the Activity
    • The Activity can directly bind to the service a call of the bindService() method. This method has the ServiceConnection parameter.
    • The onServiceConnected() method is called on this object once the Service is available.
    • The Service return on its onBind() method an object of type IBinder which can be used to call to the service.



android.intent.action.BOOT_COMPLETED
  • 若 application 被安裝在 SD card 則接收不到 android.intent.action.BOOT_COMPLETED,因此必須再 register android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE。 (?)
    • If you application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. Register yourself in this case for the android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE event.
  • 在 Android 3.0,則是至少 user 開啟過 application 一次, application 才能接收到 android.intent.action.BOOT_COMPLETED。



* Reference
- Android Service Tutorial

2012年10月9日 星期二

[Android] Restart activity after backing from it

Message

Launch timeout has expired, giving up wake lock!

Activity idle timeout for ActivityRecord


Occurred when

當想要開啟的 activity 尚未 destroy 時,則會出現此 warning 且 activity 在 destroy 後不會再次被開啟。



* Reference
- Launch timeout has expired, giving up wake lock! - Google 網上論壇
- android - Launch timeout has expired, giving up wake lock! Activity idle timeout for HistoryRecord. Is this something to worry about? - Stack Overflow

2012年6月9日 星期六

[Android] Content Provider

  • Content providers are the standard interface that connects data in one process with code running in another process.
  • The provider and provider client automatically handle security and inter-process communication.

ContentResolver
  • In the client application's process.
  • Owns the provider automatically handle inter-process communication.
  • Acts as an abstraction layer between its repository of data and the external appearance of data as tables.

query(Uri, projection, selection, selectionArgs, sortOrder)
Should do queries asynchronously on a separate thread. (ex: CursorLoader class)
  • projection: the columns that will be returned for each row
  • The expression that specifies the rows to retrieve is split into a selection clause and selection arguments.
  • selection: 
    • The selection clause is a combination of logical and Boolean expressions, column names, and values (the variablemSelection).
    • selection 中的值應用 ? 取代,實際的值放在 selectionArgs(the selection arguments array ),作為對應.
    • The selection clause is set to null, and the query returns all the words in the provider

Query result:
  • If no rows match the selection criteria
    • Cursor.getCount() is 0 (an empty cursor).
  • If an internal error occurs
    • Return null, or it may throw an Exception.
  • Since a Cursor is a "list" of rows, a good way to display the contents of a Cursor is to link it to a ListView via a SimpleCursorAdapter.

Content providers can offer the following formats:
You can see the available data types by looking at the Cursor class "get" methods.
  • integer
  • long integer (long)
  • floating point
  • long floating point (double)
  • Binary Large OBject (BLOB) implemented as a 64KB byte array

Three alternative forms of provider access are important in application development:
  • Batch access: 
    • You can create a batch of access calls with methods in the ContentProviderOperation class, and then apply them with ContentResolver.applyBatch().
    • Useful for: 
      • Inserting a large number of rows.
      • Inserting rows in multiple tables in the same method call
      • Performing a set of operations across process boundaries as a transaction (an atomic operation).
  • Asynchronous queries: 
    • You should do queries in a separate thread. 
    • One way to do this is to use a CursorLoader object. The examples in the Loaders guide demonstrate how to do this.
  • Data access via intents: 
    • Although you can't send an intent directly to a provider, you can send an intent to the provider's application, which is usually the best-equipped to modify the provider's data.


* Reference
- Content Providers
- Content Provider Basics

2012年4月28日 星期六

[Android] INSTALL_FAILED_CONFLICTING_PROVIDER

Error Message
[2010-02-28 04:14:38 - mobileFinder]Installation error: INSTALL_FAILED_CONFLICTING_PROVIDER
[2010-02-28 04:14:38 - mobileFinder]Please check logcat output for more details.
[2010-02-28 04:14:38 - mobileFinder]Launch canceled!


Solution
在安裝 apk 時,系統便會依 AndroidManifast.xml 中的宣告註冊

android:authorities 在系統中不可重覆。


* Reference
- Android: INSTALL_FAILED_CONFLICTING_PROVIDER « Hustle Play

2011年12月7日 星期三

[Android] startActivity by external component

Error Message
Uncaught handler: thread main exiting due to uncaught exception
java.lang.SecurityException: Permission Denial: starting Intent { cmp=..../.TestActivity } from ProcessRecord{44710d48 4955../10053} (pid=4955, uid=10053) requires null

Occurred when call A activity from B activity of B application.


Solution

Add this intent-filter in B activity will solve this error.

    



* Reference
- http://hi.baidu.com/spare_h/blog/item/27c25edc800e5ff577c63857.html

2011年11月1日 星期二

[Android] Start Activity in Service or Content Provider

* 可以在 Service 或 Content Provider 中開啟 Activity,但 Intent 中必須加入 Intent.FLAG_ACTIVITY_NEW_TASK Flag 才行,否則會出現以下錯誤。


* In Service
   ......
java.lang.RuntimeException: Unable to start service com.yellow.android.service.EmptyService@444bde30 with Intent { cmp=TestService}: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
   ......
Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at android.app.ApplicationContext.startActivity(ApplicationContext.java:560)
   ......


* In Content Provider
   ......
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at android.app.ApplicationContext.startActivity(ApplicationContext.java:560)
   ......


* Pending Issues
  • Why must sartActivity with new task?
  • Different tasks in an application will have any effects?


Related

2011年10月29日 星期六

[Android] 螢幕保護

Want To

就像電腦的螢幕保護程式,當手機閒置一段時間,不會鎖螢幕或是螢幕暗下來

而是顯示我們想要的內容,例如輪播照片之類的


Try To

[Lock Screen/Keyguard]
  • 取代系統原有的 Lock Screen/Keyguard
    • May Relative API
      • DevicePolicyManager
      • KeyguardManager
      • WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED, WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
    • Issues:
      • What is the different between Lock Screen and Keyguard means?
      • Keyguard includes 螢幕鎖和圖案解鎖等。(refer. 1)
      • Many events should be considered, ex:
        • Screen off/on, Incoming call/SMS, Alert Message.....
      • 是否可以在原有的 Lock Screen/Keyguard 上再執行自己的 application?
  • Disable Lock Screen/Keyguard and using Service or Thread to record touch event. 如果事件間隔超過設定,則啟動 Activity。
    • Events handler problems.
    • Start Activity in Service is allowed?
// Using KeyguardManager can disable/re-enable keyguard
KeyguardManager mKeyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); 
KeyguardLock mKeyguardLock = mKeyguardManager.newKeyguardLock("Activity1"); 
mKeyguardLock.disableKeyguard(); 



[Live Wallpaper]
  • Live wallpaper still showing when screen is locked,所以若是僅顯示在螢幕鎖之下即可...
    • 動態設定 live wallpaper,也就是當螢幕鎖了,才設定(因為應該要不影響 user 原有的桌步設定),取消後恢復 user 原有設定。
    • 但沒有正式官方的相官 method。


* Reference
  1. android的KeyGuard_谢彦_新浪博客
  2. [Android]替换系统的Lock Screen - sunny09290的专栏 - 博客频道 - CSDN.NET
  3. Handling Screen OFF and Screen ON Intents

2011年10月2日 星期日

[Android] ContentProviderClient vs. ContentResolver

* Your android device has many databases, each of which is identified by a unique Content Authority. This is the "domain name" equivalent part in the content:// uri -- everything before the first slash.


[ContentResolver]
  • ContentResolver stores data providing a mapping from String contentAuthority to ContentProvider.
  • When you call ContentResolver.query() or update() or what have you, the URI is parsed apart into its components, the contentAuthority string is identified, and contentResolver has to search that map for a matching string, and direct the query to the right provider.
  • This expensive search occurs during every single call, becuase the URI might be different from call to call, with a different contentAuthority as well.
  • Additinally, there may be some costs involved in setting up and tearing down a connection to that specific provider -- It can't be reused across calls. I'm not sure of the overhead involved there, that's some pretty deep OS level code.


[ContentProviderClient]
  • By contrast, when you call acquireContentProviderClient(authority), that "what-provider do I need?" lookup is done once, and you are given a ContentProviderClient which is essentially a direct link to the ContentProvider. (There's a bit of glue between you and the provider that involves cross-thread communication and concurrency locking).
  • However, when you use ContentProviderClient, you will talk directly to the Provider for the authority you requested. This removes the waste of constantly re-computing "which provider do I want?"


NOTE:
Per acquireContentProviderClient() documentation: If you obtain a ContentProviderClient,
"The caller must indicate that they are done with the provider by calling ContentProviderClient.release() which will allow the system to release the provider it it determines that there is no other reason for keeping it active."
So essentially, leaving a stale Client open will force the Provider to keep running as a service in the background. So, remember to clean up!


Summary:
  • Many calls to varying contentAuthorities: Use ContentResolver.
  • Repeated calls to the same Authority: Obtain and use ContentProviderClient. Remember to release() it when you're done.



* Reference
- android - using ContentProviderClient vs ContentResolver to access content provider - Stack Overflow

2011年9月27日 星期二

[Android] Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

Error Message

Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

(發生在 content provider 中開啟 activity 時?)


Solution

Android has 4 components: Activity, Service, ContentProvider and Broadcast.

When Android needs to activate one of this components from your application, it looks if there is already existing running process with your application.

If not, then Android starts new process, initializes it, then it initializes your custom Application instance. And then it activates one of needed components.



Now, let's consider next scenario:

your application declared content provider in AndroidManifest.xml, and Android just about to start your application so you can provide some data to another foreground application.
and Android just about to start your application so you can provide some data to another foreground application.
Content Provider request is sent

  1. Your application wasn't running, and Android starts new process for it.
  2. Your custom Application instance is created
  3. Application.onCreate() is called.
  4. You start an activity
  5. Your Content Provider receives request

Somebody just wanted to connect to your content provider, but your application started an Activity instead. Same true for starting background Service and sometimes broadcast receivers.

Activity entends Context, and Override startActivity(). 如果使用 activity 中的 startActivity(),不會有任何限制,而如果使用 Context 的 startActivity(),就必須是在另一個新的 task. (?)

That's because you need to start new task when Activity is started outside of Activity context. But I strongly recommend to not start Activity from your Application'sonCreate().

Because Android guarantees that Application will be created only once and before any other component


* Reference
- startActivity的requires new task异常解析 - Android - mobile - ITeye论坛
- Android Application vs Activity - Stack Overflow **

2011年9月23日 星期五

[Android] Content Provider between Threads?

Error Message

java.lang.UnsupportedOperationException: Only CrossProcessCursor cursors are supported across process for now...



Solution

發生在 content provider 呼叫另一 content provider 的情況下

原因待解

20110923
- matrixCursor
- crossprocesscursor
- call content provider in another thread

2011年9月17日 星期六

[AndroidDev] Process and Thread

[Process]
* 如果 application 在沒有任何 component 被執行中的情況下開啟,則會開啟新的 process 執行單一執行緒;若是已有被執行中的 component,則會在相同的 process and thread 執行你所要執行的功能。
  • When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution.
  • By default, all components of the same application run in the same process and thread (called the "main" thread).
  • If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution.
* However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.
  • <activity>, <service>, <receiver>, and 中可利用 android:process 屬性來指定其 component 要跑在那個 process 上。
  • <application> 也能利用 android:process 去設定所有 components 的預設值。
  • By default, all components of the same application run in the same process and most applications should not change this.
* Process Types
To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components.
  1. Foreground process: user 正在執行中的 process。ex:
    • User 正在使用的 activity (activity is onResume())。
    • User 正在使用的 activity 所使用的 service。
    • The Service has called startForeground().
    • A Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
    • A BroadcastReceiver that's executing its onReceive() method.
  2. Visible process: A process that doesn't have any foreground components, but still can affect what the user sees on screen. ex:
    • An Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
    • A Service that's bound to a visible (or foreground) activity.
  3. Service process: A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories.
  4. Background process: A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience.
    • Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. 
    • If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state.
  5. Empty process: A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it.
    • A process running a service is ranked higher than a process with background activities.


[Thread]


* Main/UI Thread
  • When an application is launched, the system creates a thread of execution for the application, called "main."
  • It is in charge of dispatching events to the appropriate user interface widgets, including drawing events.
  • The thread in which your application interacts with components from the Android UI toolkit (components from the android.widget and android.view packages).
  • By default, the system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread.
  • If the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog.
  • Is not thread-safe.


* Worker/Background Thread
  • If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads).
  • Do not access the Android UI toolkit from outside the UI thread.
  • Android offers several ways to access the UI thread from other threads. ex:
// about Thread
new Thread(new Runnable() {
    Activity.runOnUiThread(Runnable)
}
View.post(Runnable)
View.postDelayed(Runnable, long)

// http://developer.android.com/reference/android/os/AsyncTask.html
public abstract class AsyncTask

// http://developer.android.com/reference/android/os/Handler.html
public class Handler

Using example:
new Thread(new Runnable() {
        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();


* AsyncTask
You can then run the task by calling execute() from the UI thread.
public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }
    
    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}


  • The method doInBackground() executes automatically on a worker thread.
  • onPreExecute(), onPostExecute(), and onProgressUpdate() are all invoked on the UI thread
  • You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread.


* Another problem you might encounter when using a worker thread is unexpected restarts in your activity due to a runtime configuration change (such as when the user changes the screen orientation), which may destroy your worker thread.


[Thread-safe methods]

* Service
  • When a call on a method implemented in an IBinder originates in the same process in which the IBinder is running, the method is executed in the caller's thread.
  • Because a service can have more than one client, more than one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe.


* Content Provider
  • A content provider can receive data requests that originate in other processes.
  • Although the ContentResolver and ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvider methods that respond to those requests—the methods query(), insert(), delete(), update(), and getType()—are called from a pool of threads in the content provider's process, not the UI thread for the process. Because these methods might be called from any number of threads at the same time, they too must be implemented to be thread-safe.

* These are the another issue need be explored.


* Reference
- Processes and Threads | Android Developers

2011年9月5日 星期一

[Lifecycle] Activity Lifecycle


應用程式中所使用的 activity 會被堆疊在 stack 中 (task?)。

畫面上的呈現與 activity 狀態對應如下:
  • running <-> visible and get focus
    • 正在運行的 activity 便是 stack 最上面的那個 activity,會顯示在畫面上的。
  • onPause <-> visible but lost focus
    • 在畫面上仍是可見的,但已失去焦點。
    • ex: 最上的 activity 畫面獲得焦點且是可看見背景的,那麼原本的 activity ,即使是 onPause 也仍存活著,保持自己的狀態與訊息,仍然與 window manager 保持連接,但有可能會被系統殺掉。
  • onStop <-> non-visible and lost focus
    • 在畫面上已被其他 activity 完全擋住兒而不可見的,仍保有自己的狀態與資訊,但 window manager 已不再管理其訊息,系統資源不夠時會被殺掉。


當 activity is onPause or onStop,系統則可以清楚它,可能提示 user 是否結束或只是殺掉其 process。




* 當Progress Dialog啟動時Activity模糊化(blur)進入OnPause()狀態, 並以執行緒(Thread)模擬事件進度.



* Reference
- Android activity 堆栈(1) - 嘴嘴的小的日志 - 网易博客
- tsots的Android範例Source: ProgressDialog~ProgressBar~搭配Handler顯示執行進度