Android ApiDemos example resolution (44): App-& gt; Service

Source: Internet
Author: User

This example is the last example of ApiDemos about the Service. The main purpose of this example is to introduce how to pass parameters to the Service. The previous example ignores an important issue: the onStartCommand or onStart of the Service (Before Version 2.1) is executed using the same Thread that calls its Android component (usually Activity, for the Activity, this Thread is usually a UI Thread, and the previous Service examples provide very simple services, which will not greatly affect the UI performance, however, if a time-consuming operation is used in the Service, if the network access, database query, and UI Thread are still used for running, the UI response performance may be greatly reduced, even the ANR (Application Not Response) dialog box appears, so a new thread is usually created in the Service to process requests from the Client.

Handler, HandlerThread, Loop, and Message of Android. OS are commonly used in Service. For more information about Handler, see Handler usage in Android.

In Android, each Thread can have a Message Queue. Except for the UI Thread, the Thread does not contain the Message Queue by default. To create a Message Queue for a Thread, see the following code:

[Java]
Class LooperThread extends Thread {
Public Handler mHandler;
Public void run (){
Logoff. prepare ();
MHandler = new Handler (){
Public void handleMessage (Message msg ){
// Process incoming messages here
}
};
Logoff. loop ();
}
}
Class LooperThread extends Thread {
Public Handler mHandler;
Public void run (){
Logoff. prepare ();
MHandler = new Handler (){
Public void handleMessage (Message msg ){
// Process incoming messages here
}
};
Logoff. loop ();
}
}
Logoff. prepare () is used to create a Message Queue. logoff. loop () processes the Message until the Loop stops. The Handler created in the Thread will be associated with the Message Queue of the Thread. HandleMessage of Handler is used to process messages. Its type is Message class.

HandlerThread is derived from Thread to facilitate the creation of a Thread with logoff. In this example, HandlerThread is used.

[Java]
Private volatile low.mserviceloaders;
Private volatile ServiceHandler mServiceHandler;

Private final class ServiceHandler extends Handler {
Public ServiceHandler (low.logoff ){
Super (logoff );
}

@ Override
Public void handleMessage (Message msg ){
...
}

...
HandlerThread thread = new HandlerThread ("ServiceStartArguments ",
Process. THREAD_PRIORITY_BACKGROUND );
Thread. start ();

Mserviceloaders = thread. getLooper ();
MServiceHandler = new ServiceHandler (mserviceloader );
Private volatile low.mserviceloaders;
Private volatile ServiceHandler mServiceHandler;
 
Private final class ServiceHandler extends Handler {
Public ServiceHandler (low.logoff ){
Super (logoff );
}
 
@ Override
Public void handleMessage (Message msg ){
...
}
 
...
HandlerThread thread = new HandlerThread ("ServiceStartArguments ",
Process. THREAD_PRIORITY_BACKGROUND );
Thread. start ();
 
Mserviceloaders = thread. getLooper ();
MServiceHandler = new ServiceHandler (mserviceloader );
ServiceStartArguments Service uses a newly created Thread to process messages from the Client. This Thread is not a UI Thread, and HandlerThread is used to create a Thread with logoff, the specific message processing is handled by ServiceHandler's handleMessage.

The Message class defines a Message, which can contain the description and type of the Message. The parameter arg1, arg2, and obj can be directly used by default. The obtain () static function is provided to construct a new Message object.

ServiceStartArguments. Controller is the Client of ServiceStartArguments Service. It defines four buttons and Passes parameters to the Service through the Extra of Intent:

[Java]
StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "One "));

StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "Two "));

StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "Three ")
. PutExtra ("redeliver", true ));

StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "Failure ")
. PutExtra ("fail", true ));
StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "One "));
 
StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "Two "));
 
StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "Three ")
. PutExtra ("redeliver", true ));
 
StartService (new Intent (Controller. this,
ServiceStartArguments. class)
. PutExtra ("name", "Failure ")
. PutExtra ("fail", true ));
The parameter name (string), redeliver (boolean), and fail (boolean) are passed to the Service.

StartService triggers the onStartCommand method of the Service:

[Java]
@ Override
Public int onStartCommand (Intent intent, int flags, int startId ){
Log. I ("ServiceStartArguments ",
"Starting #" + startId + ":" + intent. getExtras ());
Message msg = mServiceHandler. obtainMessage ();
Msg. arg1 = startId;
Msg. arg2 = flags;
Msg. obj = intent. getExtras ();
MServiceHandler. sendMessage (msg );
Log. I ("ServiceStartArguments", "Sending:" + msg );

// For the start fail button, we will simulate the process dying
// For some reason in onStartCommand ().
If (intent. getBooleanExtra ("fail", false )){
// Don't do this if we are in a retry... the system will
// Eventually give up if we keep crashing.
If (flags & START_FLAG_RETRY) = 0 ){
// Since the process hasn' t finished handling the command,
// It will be restarted with the command again, regardless
// Whether we return START_REDELIVER_INTENT.
Process. killProcess (Process. myPid ());
}
}

// Normally we wowould consistently return one kind of result...
// However, here we will select between these two, so you can see
// How they impact the behavior. Try killing the process while it
// Is in the middle of executing the different commands.
Return intent. getBooleanExtra ("redeliver", false)
? START_REDELIVER_INTENT: START_NOT_STICKY;
}
@ Override
Public int onStartCommand (Intent intent, int flags, int startId ){
Log. I ("ServiceStartArguments ",
"Starting #" + startId + ":" + intent. getExtras ());
Message msg = mServiceHandler. obtainMessage ();
Msg. arg1 = startId;
Msg. arg2 = flags;
Msg. obj = intent. getExtras ();
MServiceHandler. sendMessage (msg );
Log. I ("ServiceStartArguments", "Sending:" + msg );
 
// For the start fail button, we will simulate the process dying
// For some reason in onStartCommand ().
If (intent. getBooleanExtra ("fail", false )){
// Don't do this if we are in a retry... the system will
// Eventually give up if we keep crashing.
If (flags & START_FLAG_RETRY) = 0 ){
// Since the process hasn' t finished handling the command,
// It will be restarted with the command again, regardless
// Whether we return START_REDELIVER_INTENT.
Process. killProcess (Process. myPid ());
}
}
 
// Normally we wowould consistently return one kind of result...
// However, here we will select between these two, so you can see
// How they impact the behavior. Try killing the process while it
// Is in the middle of executing the different commands.
Return intent. getBooleanExtra ("redeliver", false)
? START_REDELIVER_INTENT: START_NOT_STICKY;
}
In onStartCommand, ServiceStartArguments constructs a Message (obtainMessage) based on intent, flags, and startId, and then sends the sendMessage to Handle.

ServiceHandler handleMessage is used to process each message,

Msg. arg1 = startId; startId can be used to stop the specified service stopSelf (msg. arg1 );
Msg. arg2 = flags; START_FLAG_REDELIVERY or START_FLAG_RETRY.
Msg. obj = intent. getExtras (); defines the name.

HandleMessage performs different operations based on these parameters, which are not described in detail.

 
Author: mapdigit
 


 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.