Android development of four components Activity/service/broadcast Receiver/content provider Detailed

Source: Internet
Author: User
Tags gettext stub

Four components of Android development


First, the activity detailed


Second, the service detailed


Third, broadcast receiver detailed


Four, Content provider detailed explanation


Plus an important component intent the detailed.











First, the activity detailed





The life cycle of the activty is the life cycle of the process in which it resides.








The starting order of an activity:





OnCreate ()-->onstart ()-->onresume ()





When another activity is started:


The first activity OnPause ()--> The second activity onCreate ()-->onstart ()-->onresume ()


--> first Activity OnStop ()





When you return to the first activity:


The second activity OnPause ()--> The first activity Onrestart ()-->onstart ()-->onresume ()


--> second Activity onStop ()-->ondestroy ()





Order of destruction of an activity:


(case i) onpause ()--><process killed>


(ii) OnPause ()-->onstop ()--><process killed>


(Condition III) OnPause ()-->onstop ()-->ondestroy ()





Each activity is in a certain state, and for developers it is impossible to control the application in a certain state, which is done by the system.





However, when the state of an activity changes, the developer can obtain the relevant notification information by invoking the Onxx () method.





When implementing an activity class, you can call it by overriding (override) These methods when you need to process them.








OnCreate: When the activity first starts, triggers this method, can complete the activity initialization work at this time.


The OnCreate method has a parameter that can be null (NULL) or state information saved by the previous call to the Onsaveinstancestate () method.


Second, OnStart: The trigger of this method indicates that the activity will be displayed to the user.


Onresume: When an activity interacts with the user, the method is triggered.


OnPause: When an activity is running in the foreground because other activities require the foreground to run into the background, the method is triggered. This is the time to persist the state of the activity, such as the database record being edited.


OnStop: Triggers the method when an activity no longer needs to be displayed to the user. If memory is tight, the system will simply end the activity without triggering the OnStop method. So saving state information should be done at OnPause, not onstop. Activities that do not run in the foreground are stopped or the Linux management process ends these activities at any time in order to reserve enough storage space for new activities. So for developers, the principle must always be kept in mind when designing applications. In some cases, the OnPause method may be the last method of activity triggering, so the developer needs to save the information at this time.


Onrestart: This method is triggered when the activity in the stop state needs to be presented to the user again.


Vii. OnDestroy: When the activity is destroyed, the method is triggered. As with the OnStop method, if memory is tight, the system will end the activity directly without triggering the method.


· Onsaveinstancestate: The system calls this method, allowing the activity to save the previous state, such as the position of the cursor in a string of strings, and so on.


Typically, developers do not need to override this method, and in the default implementation, all state information about the user interface components involved in the AutoSave activity is provided.





Activity stacks





The above mentioned that the developer is unable to control the state of the activity, the state of the activity is based on what logic to operate it? This should know the activity stack.


The status of each activity is determined by its position in the activity stack (which is a LIFO LIFO, containing all the queues that are running the activity).


When a new activity is started, the active activities will move to the top of the action stack.


If the user returns with the Back button, or the activity at the front end, activities are moved out of the stack, and the activity on the previous event on the stack moves up and becomes active. As shown in the following illustration:

The priority of an application is affected by the highest-priority activity. When deciding whether an application will end up releasing resources, Android memory management uses stacks to determine the priority of an activity based application.


Activity status


Activity is generally considered to have the following four states:


Active: When an activity is on top of the stack, it is visible, focused, and acceptable to user input. Android tries to maintain its active status as much as possible, killing other activities to ensure that the current activity has enough resources to use. When another activity is activated, this will be suspended.


Pause: In many cases, your activity is visible but it has no focus, in other words it is paused. It is possible that a transparent or non full-screen activity is activated.


When paused, an activity is still active, but no user input can be accepted. In very special cases, Android will kill a suspended activity to provide sufficient resources for activities. When an activity becomes completely hidden, it will become a stop.


Stop: When an activity is not visible, it "stops". This activity will still hold all of its status and membership information in memory. However, when memory is needed elsewhere, it is most likely to be released. When an activity stops, an important step is to save the data and the current UI state. Once an activity exits or closes, it becomes a pending state.


To be used: it is to be used when an activity is killed and before it is loaded. The pending acitivity is removed from the activity stack and needs to be restarted before it is displayed and available.


Four kinds of loading modes for activity


In Android's multiple activity development, the jump between the activity may need to be a variety of ways, sometimes ordinary to generate a new instance, and sometimes want to jump to the original activity instance, rather than generate a lot of repetitive activity. Load mode is deciding which way to start a jump to a previous activity instance.


In Android, there are 4 activation modes for activity, respectively:


Standard: Standard mode, a call to the StartActivity () method produces a new instance.


Singletop: If an instance already exists at the top of the activity stack, no new instances are generated, but only the newinstance () method in the activity is invoked. If not at the top of the stack, a new instance is generated.


Singletask: this instance will be generated in a new task, which will be used every time in the call, and will not produce a new instance.


SingleInstance: This is basically the same as Singletask, there is only one difference: In this model of the activity instance in the task, there can be only this activity instance, no other instances.


These boot modes can be set in the feature manifest file Androidmanifest.xml, in the Launchmode property.


There are also some flags in the relevant code that can be used, for example, if we want to enable only one instance, we can use the INTENT.FLAG_ACTIVITY_REORDER_TO_FRONT flag, which says: If this activity has been started, There will be no new activity, but just add the activity instance to the top of the stack.





Intent Intent = new Intent (reorderfour.this, Reordertwo.class);


Intent.addflags (Intent.flag_activity_reorder_to_front);


StartActivity (Intent);














The load mode of the activity is controlled interactively by the attribute values of the elements of the activity in the flag and manifest files set in the intent object of the initiating activity.


Here are some features that affect the load mode


The core intent flag are:





Flag_activity_new_task


Flag_activity_clear_top


flag_activity_reset_task_if_needed


Flag_activity_single_top








The core features are:





Taskaffinity


Launchmode


Allowtaskreparenting


Cleartaskonlaunch


Alwaysretaintaskstate


Finishontasklaunch








The difference between the four load modes


The difference between the owning task


In general, the target task of the activity of "standard" and "Singletop", and the sender of the received intent in the same task, is equivalent to who calls it, and who is in the same task.


Unless intent includes parameter flag_activity_new_task. If the Flag_activity_new_task parameter is provided, it is launched into a different task.


"Singletask" and "singleinstance" always take the activity to start as the root element of a task, and they will not be launched into a different task.


Whether multiple instances are allowed


"Standard" and "singletop" can be instantiated multiple times and can exist in different tasks, where a task can include multiple instances of an activity;


"Singletask" and "singleinstance" restrict the generation of only one instance and are the root element of a task.


Singletop requires that if a intent is created with an instance of an activity to be created at the top of the stack, the intent is sent to the instance without creating a new instance.


Whether other activity is allowed to exist within this task


"SingleInstance" exclusive of a task, other activity can not exist in that task;


If it starts a new activity, regardless of the launch mode of the new activity, the new activity will run into another task (as with the Flag_activity_new_task argument).


The other three modes can coexist with other activity.


Whether new instances are generated each time


"Standard" will generate a new instance of activity for each startup intent;


Activity of "singletop" if it is at the top of the task stack, then the instance of the top of the stack is not generated, and the instance of the activity is generated directly.


Like what:


Now the task stack element is a-b-c-d (d at the top of the stack), which gives D a startup intent, if D is "standard", then a new instance of D is generated, and the stack becomes a-b-c-d-d.


If D is singletop, then a new instance of D is not produced and the stack state is still a-b-c-d


If you give B intent then, regardless of b launchmode is "standard" or "singletop", will generate a new instance of B, stack state into A-b-c-d-b.


"SingleInstance" is the only activity on its stack, which is reused every time.


If the "Singletask" is on the top of the stack, the intent is accepted, otherwise the intent is discarded, but the task will still return to the foreground. When an existing activity instance processes a new intent, the Onnewintent () method is invoked, and if a intent is generated to generate an activity instance, the user can return to the previous state via the back key If an activity already exists to handle this intent, the user cannot return to the previous state by pressing the back key.


-----------------------------------


Second, the service detailed





Service can be used in and multiple applications, for example, when playing multimedia, users start other activity this time the program to continue to play in the background, such as the detection of SD card file changes, or in the background to record the location of your geographical information changes and so on, in short service, always hidden behind.





Service is run in the background for an indefinite period of time and does not interact with the user to apply the component. Each service must be declared by <service> in manifest. Can be started by Contect.startservice and Contect.bindserverice.





The service, like other application components, runs in the main thread of the process. This means that if a service requires a lot of time-consuming or blocking operations, it needs to be implemented in its child threads.





The two Modes of service (StartService ()/bindservice () are not completely separated):





Native service local services are used within the application.





It can be started and run until someone stops it or stops it by itself. In this way, it starts with the call to Context.startservice () and ends with the call to Context.stopservice (). It can call Service.stopself () or Service.stopselfresult () to stop on its own. No matter how many times the StartService () method is invoked, you only need to call StopService () once to stop the service.





Some of the time-consuming tasks that are used to implement the application, such as query upgrade information, do not occupy the application, such as the activity-owned thread, but rather a single-thread background execution, so the user experience is better.





Remote services are used between applications within the Android system.





It can be programmed to operate through interfaces that are defined and exposed by itself. The client establishes a connection to the service object and invokes the service through that connection. The connection is established by calling the Context.bindservice () method to invoke Context.unbindservice () shutdown. Multiple clients can be bound to the same service. If the service is not loaded at this time, bindservice () loads it first.





Can be reused by other applications, such as weather forecasting services, other applications do not need to write such a service, call the existing can.








Life cycle





Using Context.startservice () to start a service will experience:





Context.startservice ()->oncreate ()->onstart ()->service running





Context.stopservice () | ->ondestroy ()->service stop





If the service is not already running, then Android calls OnCreate () and then calls OnStart (), and if the service is running, only call OnStart (), so a service's OnStart method may be repeated multiple times.





StopService Direct OnDestroy, if the caller himself to exit directly without invoking the StopService, the service will always run in the background. When the caller of the service is restarted, the service can be turned off by StopService.





So the lifecycle of invoking StartService is: OnCreate--> onStart (callable multiple times)--> OnDestroy





Using Context.bindservice () to start the service will experience:





Context.bindservice ()->oncreate ()->onbind ()->service running





Onunbind ()-> OnDestroy ()->service stop





Onbind will return to the client a Ibind interface instance, Ibind a method that allows the client to callback the service, such as the State or other operations where the services are running. This time the caller (context, for example, activity) is bound to the service, the context exits, and Srevice calls Onunbind->ondestroy to exit accordingly.





So the life cycle of the invocation Bindservice is: OnCreate--> onbind (only once, not multiple bindings)--> Onunbind the-->.





Only OnStart can be invoked multiple times (through multiple StartService calls) during each open shutdown of the service, and other oncreate,onbind,onunbind,ondestory can only be invoked once in a lifecycle.








The start service, depending on the return value of the Onstartcommand, has two additional modes:





1. Start_sticky is used to display the start and stop service.





2. Start_not_sticky or start_redeliver_intent is used for patterns that are run when a command needs to be processed.





The service cannot run itself, and you need to start the service by calling the Context.startservice () or Context.bindservice () method. Both of these methods can start the service, but they are used in different contexts.





1. Using the StartService () method to enable the service, there is no connection between the caller and the service, even if the caller exits, the service is still running.





If you intend to start the service using the Context.startservice () method, the service's OnCreate () method is invoked, followed by the OnStart () method, when the service is not created.





If the service has been created before the StartService () method is invoked, calling the StartService () method multiple times does not cause the service to be created multiple times, but will cause multiple calls to the OnStart () method.





Services started with the StartService () method can only call the Context.stopservice () method to end the service, and the OnDestroy () method is invoked at the end of the service.





2. Using the Bindservice () method to enable the service, the caller and the service are bound together, once the caller exits, the service is terminated, there is a "no need to live, must die at the same time" characteristics.





Onbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is invoked when the caller and the service are bound, and when the caller and the service have already been bundled, calling the Context.bindservice () method multiple times does not cause the method to be invoked more than once.





When a service is started with the Context.bindservice () method, only the Onunbind () method can be invoked to dismiss the caller and the service, and the OnDestroy () method is invoked at the end of the service.





Check out the official comparison process diagram:





The official document tells us that a service can start and bind at the same time, in which case the system will keep the service running if the service is already started or the BIND_AUTO_CREATE flag is set. If none of the conditions are met, the system will call the Ondestory method to terminate the service. All cleanup work (terminating the thread, the reverse registers the receiver) is done in the ondestory.





A process with a service has a higher priority





The official document tells us that the Android system will try to keep the process running with the service as long as the service has been started (start) or client connected (Bindservice) to it. When there is not enough memory to maintain, the process that owns the service has a higher priority.





1. If the service is calling the Oncreate,onstartcommand or Ondestory method, the process used for the current service becomes the foreground process to avoid being killed.





2. If the current service has been started (start), the process that owns it has a lower priority than those visible to those users, but it is more important than the invisible process, which means that the service is generally not killed.





3. If the client is already connected to the service (Bindservice), the process with the service has the highest priority, and the service can be considered visible.





4. If the service can use the startforeground (int, Notification) method to set the service to the foreground state, the system is considered to be visible to the user and will not be killed when there is not enough memory.





If there are other application components running in the same process as service,activity, it will increase the importance of the process.





Local Service





1. Local services that do not need to interact with the activity





public class LocalService extends Service {





private static final String TAG = "LocalService";





@Override


Public IBinder Onbind (Intent Intent) {


LOG.I (TAG, "Onbind");


return null;


}





@Override


public void OnCreate () {


LOG.I (TAG, "onCreate");


Super.oncreate ();


}





@Override


public void OnDestroy () {


LOG.I (TAG, "OnDestroy");


Super.ondestroy ();


}





@Override


public void OnStart (Intent Intent, int startid) {


LOG.I (TAG, "OnStart");


Super.onstart (Intent, Startid);


}


}








Activity:





public class Serviceactivity extends activity {





@Override


protected void OnCreate (Bundle savedinstancestate) {


Super.oncreate (savedinstancestate);


Setcontentview (R.layout.servicedemo);





(Button) Findviewbyid (R.id.startlocalservice)). Setonclicklistener (


New View.onclicklistener () {





@Override


public void OnClick (view view) {


TODO auto-generated Method Stub


StartService (New Intent ("Com.demo.SERVICE_DEMO"));


}


});





(Button) Findviewbyid (R.id.stoplocalservice)). Setonclicklistener (


New View.onclicklistener () {





@Override


public void OnClick (view view) {


TODO auto-generated Method Stub


StopService (New Intent ("Com.demo.SERVICE_DEMO"));


}


});


}





}








Add in Androidmanifest.xml:





<service android:name= ". LocalService ">


<intent-filter>


<action android:name= "Com.demo.SERVICE_DEMO"/>


<category android:name= "Android.intent.category.default"/>


</intent-filter>


</service>








Otherwise, when you start the service, you are prompted that new intent cannot find "Com.demo.SERVICE_DEMO."





For this type of local service that does not need to interact with the activity, it is the best example of using Startservice/stopservice.





The runtime can find that the first time StartService, will invoke OnCreate and OnStart, no stopservice before, no matter how many clicks StartService, will only call OnStart. Call OnDestroy when StopService. Clicking StopService again will find that it will not enter the life cycle of the service, that is, Oncreate,onstart and OnDestroy will not be called again.





And Onbind is not invoked in Startservice/stopservice.





2. Local services and activity interaction





For this case, the official sample (Apidemo\app. LocalService) is the best example:





/**


* This is a example of implementing a application service that runs locally


* In the same process as the application. The {@link Localservicecontroller}


* and {@link localservicebinding} classes show I interact with the


* Service.


*


* <p>notice the use of the ' {@link Notificationmanager} when interesting things


* happen in the service. This is generally how background services should


* Interact with the user, rather than doing something more disruptive such as


* Calling StartActivity ().


*/


public class LocalService extends Service {


Private Notificationmanager MNM;





/**


* Class for clients to access. Because we know this service always


* runs in the same process as it clients, we don ' t need to deal with


* IPC.


*/


public class Localbinder extends Binder {


LocalService GetService () {


return localservice.this;


}


}





@Override


public void OnCreate () {


MNM = (Notificationmanager) getsystemservice (Notification_service);





Display a notification about us starting. We put a icon in the status bar.


Shownotification ();


}





@Override


public int Onstartcommand (Intent Intent, int flags, int startid) {


LOG.I ("LocalService", "Received start ID" + Startid + ":" + intent);


We want this service to continue running until it is explicitly


Stopped, so return sticky.


return start_sticky;


}





@Override


public void OnDestroy () {


Cancel the persistent notification.


Mnm.cancel (r.string.local_service_started);





Tell the user we stopped.


Toast.maketext (This, r.string.local_service_stopped, Toast.length_short). Show ();


}





@Override


Public IBinder Onbind (Intent Intent) {


return mbinder;


}





This is the object of receives interactions from clients. The


Remoteservice for a more complete example.


Private final IBinder Mbinder = new Localbinder ();





/**


* Show a notification while this service is running.


*/


private void Shownotification () {


In this sample, we'll use the same text for the ticker and the expanded notification


Charsequence Text = GetText (r.string.local_service_started);





Set the icon, scrolling text and timestamp


Notification Notification = new Notification (r.drawable.stat_sample, text,


System.currenttimemillis ());





The pendingintent to launch we activity if the user selects this notification


Pendingintent contentintent = pendingintent.getactivity (this, 0,


New Intent (this, localservicecontroller.class), 0);





Set the info for the "views" of the notification panel.


Notification.setlatesteventinfo (This, GetText (R.string.local_service_label),


text, contentintent);





Send the notification.


We use a layout ID to because it is a unique number. We use it later to cancel.


Mnm.notify (r.string.local_service_started, notification);


}


}








Here you can find that Onbind needs to return a IBinder object. In other words, unlike the previous example LocalService,





1. Add a public inner class inheritance binder and add the GetService method to return the current service object;





2. Create a new IBinder object--new that binder inner class;





3. The Onbind method returns the IBinder object.





Activity:





/**


* <p>example of binding and unbinding to the {@link LocalService}.


* This demonstrates the implementation of a service which the client would


* Bind to, receiving a object through which it can communicate with the service.</p>


*/


public class Localservicebinding extends activity {


Private Boolean misbound;


Private LocalService Mboundservice;





@Override


protected void OnCreate (Bundle savedinstancestate) {


Super.oncreate (savedinstancestate);





Setcontentview (r.layout.local_service_binding);





Watch for button clicks.


Button button = (button) Findviewbyid (R.id.bind);


Button.setonclicklistener (Mbindlistener);


Button = (button) Findviewbyid (R.id.unbind);


Button.setonclicklistener (Munbindlistener);


}





Private Serviceconnection mconnection = new Serviceconnection () {


public void onserviceconnected (componentname className, IBinder service) {


This is called the connection with the service has been


Established, giving us the service object we can use to


Interact with the service. Because we have bound to a explicit


Service that we know are running in our own process, we can


Cast its ibinder to a concrete class and directly access it.


Mboundservice = ((localservice.localbinder) service). GetService ();





Tell the user about this for our demo.


Toast.maketext (Localservicebinding.this, r.string.local_service_connected,


Toast.length_short). Show ();


}





public void onservicedisconnected (ComponentName className) {


This is called the connection with the service has been


Unexpectedly disconnected--that's, its process crashed.


Because it is running into our same process, we should never


This happen.


Mboundservice = null;


Toast.maketext (Localservicebinding.this, r.string.local_service_disconnected,


Toast.length_short). Show ();


}


};





Private Onclicklistener Mbindlistener = new Onclicklistener () {


public void OnClick (View v) {


Establish a connection with the service. We Use an explicit


Class name because we want a specific service implementation that


We know would be running into our own process (and thus won ' t being


Supporting component replacement by the other applications).


Bindservice (New Intent (Localservicebinding.this,


Localservice.class), mconnection, context.bind_auto_create);


Misbound = true;


}


};





Private Onclicklistener Munbindlistener = new Onclicklistener () {


public void OnClick (View v) {


if (misbound) {


Detach our existing connection.


Unbindservice (mconnection);


Misbound = false;


}


}


};


}














It is obvious that this adds a name to the Serviceconnection class and implements the Onserviceconnected (Get service object from IBinder) and onservicedisconnected (set service to null).





The Bindservice and Unbindservice methods are all manipulating the Serviceconnection object.





Add in Androidmanifest.xml:





<service android:name= ". App. LocalService "/>








There's nothing special about this, because the service doesn't need any special action, so it's just stating the service, and the activity is no different from the normal.





At run time, the discovery invocation order is as follows:





Bindservice:





1.localservice:oncreate





2.localservice:onbind





3.activity:onserviceconnected





Unbindservice: Just call OnDestroy





Visible, OnStart is not invoked, and the reason onservicedisconnected is not invoked is described in the comments on the code above.








------------------------


Third, broadcast receiver detailed








Broadcastreceiver is used to receive broadcast intent asynchronously. There are two main categories that are used to receive broadcasts:





• Normal broadcasts (sent with Context.sendbroadcast ()) is fully asynchronous. They all run in an undefined order, usually at the same time. This is more efficient, but it means that receiver cannot contain the results or aborted APIs that you want to use.





• Ordered broadcast Ordered broadcasts (sent with Context.sendorderedbroadcast ()) is sent to a receiver each time. The so-called order is that each receiver can be propagated to the next receiver after execution, or it can stop spreading completely--not to other receiver. The sequence of receiver runs can be controlled by the android:priority inside the matched Intent-filter, and priority in any order when the receiver priority is the same.





It should be noted that even in normal broadcasts, the system may revert to a receiver in some cases. In particular, receiver may need to create a process to run only one receiver at a time to avoid overloading the system.





Broadcast Receiver does not provide a visual interface to display broadcast information. You can use notification and notification Manager to visualize the interface of the information, display the contents of broadcast information, icons and vibration information.





Life cycle





A Broadcastreceiver object is valid only if it is invoked onreceive (context, Intent), and when returned from the function, the object is invalid, ending the lifecycle.





Therefore, it can be seen from this feature that in the invoked OnReceive (context, Intent) function, there can be no too time-consuming operation, can not use the thread to execute. For time-consuming operations, please start service to complete. Because the broadcastreceiver may not be valid when the result returned by another asynchronous operation is obtained.





Send broadcast





Events are relatively simple to broadcast, build Intent objects, and invoke the Sendbroadcast (Intent) method to emit the broadcast. In addition to Sendorderedbroadcast (), Sendstickybroadcast () and other methods, please consult the API Doc.





1.new Intent with action name





Intent Intent = new Intent (String action);





Or just new Intent, and then





Intent.setaction (String action);





2.set data etc when ready, in an activity,





Sendbroadcast (Intent); Send broadcast





Receive broadcast





Implemented by defining an inherited Broadcastreceiver class, inheriting the class, overwriting its Onreceiver method, and responding to the event in that method.





public class Smsreceiver extends Broadcastreceiver {





@Override


public void OnReceive (context context, Intent Intent) {


Get data from SMS intent


Bundle Bundle = Intent.getextras ();


if (bundle!= null) {


Get message by "PDUs"


Object[] Objarray = (object[]) bundle.get ("PDUs");





Rebuild SMS


smsmessage[] messages = new Smsmessage[objarray.length];


for (int i=0 i < objarray.length; i++) {


Messages[i] = SMSMESSAGE.CREATEFROMPDU ((byte[)) objarray[i]);





StringBuilder str = new StringBuilder ("From:");


Str.append (Messages[i].getdisplayoriginatingaddress ());


Str.append ("\nmessage:\n");


Str.append (Messages[i].getdisplaymessagebody ());





Toast.maketext (Context, str.tostring (), Toast.length_long)


. Show ();


}


}


}


}








Register receiver





There are two ways of registering:





1. Static mode, define the receiver in the Androidmanifest.xml application and set the action to receive.





<receiver android:name= ". Smsreceiver ">





<intent-filter>





<action android:name= "Android.provider.Telephony.SMS_RECEIVED"/>





</intent-filter>





</receiver>








2. Dynamic mode, in the activity inside the call function to register, and static content almost. One parameter is receiver and the other is Intentfilter, which is the action to receive.





public class Hellodemo extends activity {


Private Broadcastreceiver receiver;





@Override


protected void OnStart () {


Super.onstart ();





Receiver = new Callreceiver ();


Registerreceiver (receiver, New Intentfilter ("Android.intent.action.PHONE_STATE"));


}





@Override


protected void OnStop () {


Unregisterreceiver (receiver);


Super.onstop ();


}


}








A receiver can receive multiple action, that is, there can be multiple intent-filter, and the Intent.getaction (action name) needs to be judged in onreceive.





The personal recommendation uses the static registration way, by the system manages the receiver, moreover all receiver in the program, may in the XML inside glance. and dynamic registration method, hidden in the code, more difficult to find.





and dynamic registration, you need to pay special attention to, before exiting the program to remember to call the Context.unregisterreceiver () method. Generally in the activity of the onstart () inside to register, OnStop () inside for cancellation. The official reminder that if you register in Activity.onresume (), you must log off at Activity.onpause ().





Permission permissions





To receive some action, you need to add the corresponding permission inside the androidmanifest.xml. For example, receive SMS:





<uses-permission android:name= "Android.permission.RECEIVE_SMS"/>








The following is a dynamically registered Callreceiver code to receive incoming calls for broadcast processing:





One way is to read Intent.getstringextra ("Incoming_number") directly to get the caller number:





public class Callreceiver extends Broadcastreceiver {





@Override


public void OnReceive (context context, Intent Intent) {


Telephonymanager Telemanager = (telephonymanager) context.getsystemservice (Context.telephony_service);





Switch (telemanager.getcallstate ()) {


Case telephonymanager.call_state_ringing://Bell


Toast.maketext (Context, "ringing:" + Intent.getstringextra ("Incoming_number"), Toast.length_long). Show ();


Break


Case Telephonymanager.call_state_offhook://Answer


Toast.maketext (Context, "Offhook:" + Intent.getstringextra ("Incoming_number"), Toast.length_long). Show ();


Break


Case Telephonymanager.call_state_idle://Hang Up


Toast.maketext (M_context, "Idle:" + Incomingnumber, Toast.length_long). Show ();


Break


}


}


}








At run time, it is found that you can get the caller number in addition to the ring, and the answer and hang are not successful, and the display is null.





Another way is to listen for changes in state through the Phonestatelistener oncallstatechanged:





public class Callreceiver extends Broadcastreceiver {





Private context M_context;


@Override


public void OnReceive (context context, Intent Intent) {


M_context = context;


Telephonymanager Telemanager = (telephonymanager) context.getsystemservice (Context.telephony_service);


Telemanager.listen (New Phonestatelistener () {





@Override


public void oncallstatechanged (int state, String incomingnumber) {


Switch (state) {


Case telephonymanager.call_state_ringing://Bell


Toast.maketext (M_context, "ringing:" + incomingnumber, Toast.length_long)


. Show ();


Break


Case Telephonymanager.call_state_offhook://Answer


Toast.maketext (M_context, "Offhook:" + Incomingnumber, Toast.length_long)


. Show ();


Break


Case Telephonymanager.call_state_idle://Hang Up


Toast.maketext (M_context, "Idle:" + Incomingnumber, Toast.length_long)


. Show ();


Break


}


}}, Phonestatelistener.listen_call_state);


}


}








The runtime also finds that the Incomingnumber is blank when answering and hanging up.





This receiver is called 3 times because the state of the call is being monitored.





Listen for call status need to add permissions:





<uses-permission android:name= "Android.permission.READ_PHONE_STATE"/>








===========





Summary:





1. For a Sendbroadcast intent object, you need to set its action name;





2. It is recommended to use an explicit receiver specified in the configuration file androidmanifest.xml;





3. A receiver can receive multiple action;





4. Each receive broadcast will regenerate an object to receive the broadcast, call OnReceive again;





5. Try not to deal with too many logical problems in broadcast, and suggest that complex logic be given to activity or Service to deal with.











--------------------------------------------


Four, Content provider detailed explanation





ContentProvider (content Provider) is one of the four major components of Android. Mainly used for external sharing of data, that is, through ContentProvider the application of the data sharing to other applications access, other applications can use the ContentProvider to operate the data in the specified application. ContentProvider is divided into system and custom, the system is such as contact person, picture and other data.





The data operations in Android include:





File, Sqlite3, Preferences, Contectresolver and ContentProvider the first three types of data operations are only for the data in this application, the program can not use these three methods to manipulate the data in other applications.





Android provides Contectresolver and ContentProvider to manipulate data from other applications.





How to use:





An application implements ContentProvider to provide content for other applications to operate,





An application can use Contentresolver to manipulate other application data, of course, in its own application.





The following is a general overview of ContentProvider in Google Doc:





Content providers provide specific application data for use by other applications. The content provider inherits from the ContentProvider base class and implements a standard set of methods for other applications to access and store the data it manages. However, the application does not call these methods directly, but instead uses a Contentresolver object to invoke its methods as an alternative. Contentresolver can communicate with any content provider and work with it to manage all related interactive communications.





1.ContentProvider





Android provides contentprovider for some of the main data types, such as audio, video, pictures, and personal contacts. Some Android-provided ContentProvider can be found under the Android.provider pack. By obtaining these contentprovider, you can query the data they contain, provided that you have obtained the appropriate read permissions.





Main methods:





The public boolean onCreate () is called when the ContentProvider is created





Public Cursor query (Uri, string[], String, string[], string) is used to query the ContentProvider of the specified Uri, returning a Cursor





The public Uri Insert (URI, contentvalues) is used to add data to the ContentProvider of the specified Uri





public int update (URI, Contentvalues, String, string[]) is used to update data in the ContentProvider of the specified Uri





public int Delete (Uri, String, string[]) is used to delete data from the ContentProvider of the specified Uri





The public String GetType (URI) is used to return the MIME type of the data in the specified Uri








* If the data being manipulated is of a collection type, then the MIME type string should start with vnd.android.cursor.dir/.





For example, to get the URI of all person records to be Content://contacts/person, the MIME type string returned is "Vnd.android.cursor.dir/person".





* If the data to be manipulated belongs to a collection-type data, then the MIME type string should start with vnd.android.cursor.item/.





For example, to get the URI of the person record with ID 10 as CONTENT://CONTACTS/PERSON/10, the returned MIME type string should be "Vnd.android.cursor.item/person".





2.ContentResolver





When an external application needs to add, delete, modify, and query the data in the ContentProvider, you can use the Contentresolver class to get the Contentresolver object. You can use the Getcontentresolver () method provided by the context.





Contentresolver CR = Getcontentresolver ();





The methods provided by Contentresolver correspond to the methods provided by ContentProvider in the following ways.





The public URI insert (URI uri, contentvalues values) is used to add data to the ContentProvider of the specified Uri.





The public int Delete (URI Uri, String selection, string[] selectionargs) is used to delete data from the ContentProvider of the specified Uri.





public int update (URI uri, contentvalues values, String selection, string[] selectionargs) is used to update the data in the contentprovider of the specified Uri.





Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) used to query the co for the specified Uri Ntentprovider.














3.Uri





The URI specifies the ContentProvider to be manipulated, in fact, a URI can be thought of as a URL, and we divide the URI into three parts.





The first part is "content://". can be considered as "http://" in the Web site.





The second part is the hostname or authority, which is used to uniquely identify the contentprovider, and the external application needs to find it based on this identifier. Can be considered as the host name in the URL, such as "blog.csdn.net".





The third section is the pathname, which represents the data to be manipulated. Can be considered as a subdivision of the content path in the URL.

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.