Four Component Learning Paths

Learning Records of Four Android Components

I used to memorize the contents of the four components for interviews. In fact, in project development, except for activities, they are seldom used. Even if they are used, they are just a copy of Du Niang. Now suddenly realize that I do not understand very much, I feel that I can no longer understand like this in the future, so today I began to record my way of in-depth learning of the four major components, sorting out the knowledge of many great gods!!! Follow-up will also be added, and continue to study in depth.

Activity

  1. Activity is the component responsible for interacting with users in Android applications
  2. Activities communicate through Intent

Activity needs to be configured in the application tag under the Android Manifest. XML file:

<activity android:name=".Activity ">
 </activity>

activity is enabled by default:

  <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>

Activity's life cycle:

  1. OnCrete (Bundle saved Instance State): When an Activity is first loaded, it executes only once without being destroyed. The parameter in the method body is the temporary data stored when we call onSave Instance State (Bundle out State).
  2. onStart(): activity is called when it is visible to the user on the screen.
  3. onResume(): Invoked when activity begins to interact with the user (whether it starts or restarts an activity, the method is always invoked).
  4. onPause(): An activity is called when it is suspended or retrieved from the cpu and other resources. This method is used to save the active state.
  5. onStop(): Called when activity is stopped and turned into an invisible phase and subsequent life cycle events.
  6. onRestart(): Called when the activity is restarted. The activity is still on the stack, rather than starting a new activity.
  7. onDestroy(): When activity is completely removed from system memory, it is called to destroy activity and release resources.

** A (Activity), B (Activity)** onPause(A) represents the onPause() method of A

  • When you first enter the activity interface: onCreate() - > onStart () - > onResume ()
  • When exiting the activity interface: onPause() - > onStop () - > onDestroy ()
  • When the activity interface is switched from horizontal to vertical screen: onPause() - > onSave Instance State () - > onStop () - > onDestroy () - > onCreate () - > onStart () - > onRestore Instance State () - > onResume ()
  • When entering interface B from interface A: onPause(A) - onCreate (B) - onStart (B) - onResume (B) - onSave Instance State (A) - onStop (A)
  • When returning to interface A from interface B: onPause(B) - > onRestart (A) - > onStart (A) - > onResume (A) - > onStop (B) - > onDestroy (B)

** Tip: ** onSaveInstanceState() executes every time, where only temporary data can be saved, and if persistent data can be cached. onRestoreInstanceState() is executed only when the interface is forced to be killed by the system (such as backstage killing when there is insufficient memory, horizontal and vertical screen switching, etc.), where temporary data stored by onSaveInstanceState() method can be obtained.

Activity's Intent Request Intent intent:

  • Intent display: specify the name of the target component, which is the target activity you want to jump.

    Intent intent=new Intent( this , A.class );
     startActivity(intent);
    
  • Intent implies that when using Intent to jump, there is no specific Activity or Service to jump. Matching filtering through Intent-Filter(Intent filter) will jump to matching Activity or Service. If there are multiple simultaneous matches, a dialog box pops up for the user to choose which component to activate, such as calling a mobile browser.

Intent-filter is added to the Activeness declaration of the manifest file AndroidManifest.xml:

    <intent-filter>  
        <action android:name="...."/>  
        <category android:name="...."/>  
        <category android:name="android.intent.category.DEFAULT"/>      
        <data android:scheme="..." android:host="..." android:path="/..." android:type="..."/>  
    </intent-filter>

intent jump code in activity:

    Intent intent = new Intent();  
    intent.setAction("....");  
    intent.addCategory("....");  
    intent.setData(Uri.parse("...."));  
    //Setting data scheme, host, path, type conditions   
    intent.setDataAndType(Uri.parse(""),String type);  
    startActivity(intent);

Note: If an Android is added to the data in Intent-filter: mimeType= "text/*", intent.setData should not be used at the jump point, but intent.setDataAndType();

For a detailed description of each attribute, please refer to God:
(http://blog.csdn.net/weihan1314/article/details/7973511)

Action action

An element should contain at least one, otherwise no Intent request can match it.
If the Action requested by Intent matches one of the items, the Intent passes the action test of this item.
If the specific Action type is not specified in the Intent request or in the Intent request, the following two situations will occur.
(1) If no Action type is included, then no Intent request can match this one;
(2) Conversely, if the Action type is not set in the Intent request, the Intent request will pass the behavior test smoothly as long as the Action type is included.

category Category

Only when all Categories in an Intent request match exactly one Intent-filter in the component will the Intent request pass the test, and the redundant declarations in the Intent-filter will not cause the match to fail. That is, as long as the German category in intent-filter contains the category set when intent requests.
—————————— The role of android.intent.category.DEFAULT————————-
Every implicit Intent emitted through the start Activity () method has at least one category, namely "android.intent.category.DEFAULT", so as long as you want to receive an implicit Intent, Active Intent should include "android.intent.category.DEFAULT" category, otherwise Intent matching will fail.

Data

Data is usually operational data defined in URI format. For example: tel:///. Set it through the setData() method.

Extras

Extras attributes are mainly used to transfer additional data required by the target component. Set by putExtras() method.

Activity loading method:

Activity stack (Task is a LIFO with all queues running Activity)

There are several Task-related attributes in Android:

  • taskAffinity
  • launchMode
  • allowTaskReparenting
  • alwaysRetainTaskState
  • clearTaskOnLaunch
  • finishOnTaskLaunch
  • noHistory

Loading mode is set in the < activity > tag registered in Android Manifest. xml: android:launchMode=".“

<activity android:name=".Activity"
        android:launchMode="standard">
    </activity>
Loading mode Effect
standard In standard mode, a call to the startActivity() method produces a new instance. The system uses this loading mode by default.
singleTop If an instance already exists at the top of the Activity stack, no new instances are generated, and only the new Instance () method in Activity is called. If it is not at the top of the stack, a new instance will be generated.
singleTask This instance will be generated in a new task, which will be used every time a call is made, and no new instance will be generated.
singleInstance This is basically the same as singleTask, except for one difference: in the task where the Activity instance is located in this mode, only this activity instance can exist, and no other instance can exist.

The settings in the ** code that affect the loading mode: ** intent.setFlags();

Intent intent=new Intent(this,A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Common attribute values Function (see: http://www.cnblogs.com/lwbqqyumidi/p/3775479.html ) The gods here write in great detail.
FLAG_ACTIVITY_NEW_TASK Determine whether a new Task needs to be created based on Activity Affinity, and then create a new Activity instance to put in (see details: http://www.cnblogs.com/lwbqqyumidi/p/3775479.html)
FLAG_ACTIVITY_CLEAR_TOP When an Intent object contains this tag, if an Activity instance is found on the stack, the Activity above the instance is emptied and placed at the top of the stack.
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED This tag takes effect in the following cases: 1. Create a new task to place an Activity instance when the Activity is started; 2. Existing tasks are placed in the foreground.
FLAG_ACTIVITY_SINGLE_TOP When there is a target Activity instance in task and it is at the top of the stack, no new one is created and it is used directly. It is found that the effect is the same as singleTop in Activity startup mode.
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET If this property is included in an Intent, the Activity to which it is directed and all activities on that Activity will be cleared from the task when the task is reset (premise: FLAG_ACTIVITY_RESET_TASK_IF_NEEDED).

Service

Referring to God's blog, take a look at God's blog: http://blog.csdn.net/javazejian/article/details/52709857

Service is a long life cycle program without user interface. It can be used to develop programs such as monitoring programs.

Service needs to be configured in the application tag under the AndroidManifest.xml manifest file: see God for more details: http://blog.csdn.net/think_soft/article/details/7584895

<service android:enabled=["true" | "false"]     //This property is used to indicate whether the service can be instantiated. If set to true, it can be instantiated, otherwise it cannot be instantiated. The default value is true. If the enabled attribute of an element is set to false, the service is disabled and cannot be instantiated.
  android:exported=["true" | "false"]           //This property is used to indicate whether the service can be invoked or interacted with by other application components. If set to true, it can be called or interacted, otherwise it cannot. When set to false, only components of the same application or applications with the same user ID can start or bind the service.
  android:icon="drawable resource"              //This property defines an icon representing the service, which must refer to a drawing resource containing the image definition. If this property is not set, the icon attribute of the < Application > element is used instead.
  android:isolatedProcess=["true" | "false"]    //If set to true, the service will run in a dedicated process that is independent of the rest of the system and has no privileges of its own. The only way to communicate with it is through this Service API (binding or starting).
  android:label="string resource"               //This property is used to set the name of a service to be displayed to the user. If this property is not set, the label attribute value of the < Application > element is used instead.
  android:name="string"                         //This property is used to specify the class name of the Service subclass that implements the service. Once an application is published, this name should not be changed (unless android: export= "false"). There is no default value for this property, and the name must be specified.
  android:permission="string"                   //This property defines the permissions that an entity must have to start or bind a service. If this property is not set, the permission set by the permission attribute of the < Application > element will apply to the service. If the < Application > element does not set permissions, the service is not protected by permissions.
  android:process="string" >                    //This property is used to set the name of the process that the service is running. Typically, all components of an application run in the process created for the application, and the process name is the same as the package name of the application.
  . . .
 </service>

Classification of Service:

Classified according to start-up mode:

  • Open service startService(): Service will always run in the background. In Service, you can call Context.startService() to start and call Context.stopService() to end. Internally, you can call Service.stopSelf() or Service.stopSelfResult() to stop by yourself. No matter how many times startService() is invoked, it only needs to call stopService() once to stop.

  • Binding service bindService(): Call the Context.bindService() method to establish the connection and start to call Context.unbindService() to close the connection. Multiple clients can be bound to the same service. When all bindings of the service are unbound, the service is destroyed.

Classified by nature of service:

  • Local Service: Local Service is used within the application, and the activity of the service and the startup service are in the same process. In Service, you can call Context.startService() to start, Context.stopService() to end, and onDestroy() method to end the service. Internally, you can call Service.stopSelf() or Service.stopSelfResult() to stop by yourself. No matter how many times startService() is invoked, it only needs to call stopService() once to stop.

  • Remote Service: Remote Service is used between applications within the android system, and the activity of the service and the startup service are not in the same process. Interfaces can be defined and exposed for other applications to operate on. The client establishes a connection to the service object and invokes the service through that connection. Call the Context.bindService() method to establish the connection and start to call Context.unbindService() to close the connection. Multiple clients can be bound to the same service. If the service is not loaded at this time, bindService() loads it first.

Service life cycle:

  • startService() - > onCreate () - > onStartCommand () - Service running --- Call stopService() - > onDestroy ()
  • bindService() - > onCreate () - > onBind () - Service running -> Call onUnbind() - > onDestroy ()

Be careful:
- If the service is open (startService(), its activity life cycle and the entire application life cycle end together. Unless you turn it off on your own initiative.
- If service s are bound (bindService()), their activity life cycle ends after the onUnbind() method returns.
- Although an open service is stopped by calling stopSelf() or stopService(), there is no corresponding callback function corresponding to it, that is, there is no onStop() callback method. So, when a stop method is called, unless the service is bound to the client component, the system will destroy it directly. The onDestory() method will be called, and is the only callback method that will be called at this time.

Small dots:

After API level 2.0, the onStart() method was replaced by onStartCommand().

@Override
public int onStartCommand(Intent intent,
               int flags, 
               int startId){
       return super.onStartCommand(intent, flags, startId);
}

Parameters:

  • Intent: intent in startService(Intent);
  • flags: Additional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY;
    START_FLAG_REDELIVERY: If you implement onStartCommand() to schedule asynchronous work or work in another thread, you may need to use it to get the system to resend an intent. This way, if your service is dropped by Kill while it is being processed, Intent will not be lost.
    _START_FLAG_RETRY: Represents that the service was set to START_STICKY before it was passed into this tag.
  • StartId: is the number of the activity or other entity of the service request, used in conjunction with stopSelfResult (int startId), which can safely stop the service according to ID.

Four return values of the method:

  • START_STICKY: If the service process is kill ed, the service state is retained as the start state, but the delivered intent object is not retained. Then the system will try to recreate the service. Since the service state is the start state, the onStartCommand(Intent,int,int) method will be invoked after the service is created. If no startup command is passed to the service during this period, the parameter Intent will be null.
  • START_NOT_STICKY: "Nonsticky". With this return value, if the service is abnormally kill ed after onStartCommand is executed, the system will not automatically restart the service.
  • START_REDELIVER_INTENT: Retransmit Intent. When using this return value, if the service is abnormally kill ed after onStartCommand is executed, the system will automatically restart the service and pass in the value of Intent.
  • START_STICKY_COMPATIBILITY: A compatible version of START_STICKY, but there is no guarantee that the service will be restarted after kill ing.

** Reminds: ** After Android 5.0, the self-startup of the service when the main program exits is invalid, fork() group kills, and when your main program process is killed, the whole group will be killed. Because I want to write a reminder program APP, I tested some dual services to wake up each other. The method of broadcasting wake-up service makes the service hang in the background all the time, but all fail. I can't make the service run in the background after the exit of APP. I inquired about some gods, but I didn't understand them at all.





If your service is turned on and binding is accepted, then when the system calls your onUnbind() method, if you want to accept an onRebind() call at the next client binding (instead of onBind()), you can choose to return true in onUnbind().

 @Override
 public boolean onUnbind(Intent intent) {
     return super.onUnbind(intent);
 }

The lifecycle of this service (which is open and also allows binding) is shown in the figure.

Call examples:

Open and close services (be careful not to forget to configure services in the manifest file):

import android.app.Service;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

public class ServiceTest extends Service{

/**
 *  This method is not invoked if the service is already running. This method is called only once
 */
@Override
public void onCreate() {
    super.onCreate();
    Log.i("ServiceText","onCreate()");
}
/**
 * Each time a Service is started through the startService() method, it is called back.
 * @param intent
 * @param flags
 * @param startId
 * @return
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("ServiceText","onStartCommand()");
    return START_NOT_STICKY;
}
/**
 * The service is invoked only when it is bound. onBind() is called only for the first time in multiple bindings.
 * Methods that must be implemented
 * @param intent
 * @return
 */
@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.i("ServiceText","onBind()");
    return null;
}
/**
 * Callback at Service Destruction
 */
@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("ServiceText","onDestroy()");
}
}


    Intent intent=new Intent(this, ServiceTest.class);
    //Open Services
    startService(intent);
    //Shut down services
    stopService(intent);

Binding Services and Unbinding Services:

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class ServiceTest extends Service{

//Communication between caller client and Service through binder
private MyIBinder binder=new MyIBinder();

public class MyIBinder extends Binder{
    public ServiceTest getService(){
        return ServiceTest.this;
    }
}

/**
 *  This method is not invoked if the service is already running. This method is called only once
 */
@Override
public void onCreate() {
    super.onCreate();
    Log.i("ServiceText","onCreate()");
}
/**
 * The service is invoked only when it is bound. onBind() is called only for the first time in multiple bindings.
 * Methods that must be implemented
 * @param intent
 * @return
 */
@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.i("ServiceText","onBind()");
    return binder;
}

/**
 * Unbound
 * @param intent
 * @return true,Execute onRebind the next time you rebind; false, onBind the next time you rebind.
 */
@Override
public boolean onUnbind(Intent intent) {
    Log.i("ServiceText","onUnbind()");
    return false;
}

/**
 * Rebinding
 * @param intent
 */
@Override
public void onRebind(Intent intent) {
    Log.i("ServiceText","onRebind()");
    super.onRebind(intent);
}
/**
 * Callback at Service Destruction
 */
@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("ServiceText","onDestroy()");
}
}


 /**
  * ServiceConnection Representing the connection to a service, it has only two methods.
  * onServiceConnected And onService Disconnected,
  * The former is invoked when the operator succeeds in connecting a service, while the latter is invoked when the connection is interrupted due to service crash or killing.
  */
 private ServiceConnection conn;
 private ServiceTest mService;
 Intent intent=new Intent(this, ServiceTest.class);

 conn = new ServiceConnection() {
        /**
         * The interface method interacting with the server side is called back when binding the Service, in which the IBinder object passed by the binding Service is retrieved.
         * Through this IBinder object, the interaction between host and Service is realized.
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("ServiceTest", "Binding successful invocation: onServiceConnected");
            // Get Binder
            ServiceTest.MyIBinder binder = (ServiceTest.MyIBinder) service;
            mService = binder.getService();
        }
        /**
         * Callback when unbound is cancelled. Normally, it is not invoked. It is invoked when the Service service is accidentally destroyed.
         * For example, this method is called automatically when memory resources are insufficient. When the client unbinds, the system "never" calls this method.
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService=null;
        }
    };

 /**
  * Binding services
  * @param intent Is an Intent that specifies the service to be bound explicitly.
  * @param ServiceConnection ServiceConnection Object.
  * @param flags It should be BIND_AUTO_CREATE, which will automatically create a service when it does not exist.
  *              The other optional values are BIND_DEBUG_UNBIND and BIND_NOT_FOREGROUND, which can be set to 0 when you do not want to specify (not automatically created).
  */
 bindService(intent, conn, Service.BIND_AUTO_CREATE);

  //Unbound
  if(mService!=null) {
     mService = null;
     unbindService(conn);
  }

Small dots:
The implementation class of IBinder interface, which provides a programming interface for client to interact with services, can define interfaces in three ways: extended Binder class, Messenger, AIDL (God's blog address: http://blog.csdn.net/javazejian/article/details/52709857)

Broadcast Receive

External events are filtered to receive and respond only to external events of interest (e.g. when the phone calls in, or when the data network is available). The broadcast receiver has no user interface. However, they can start an activity or series to respond to the information they receive, or notify users with Notification Manager.

Registration method of broadcasting:

  • Static registration:
    Register in the Android Manifest. XML file

    <receiver android:enabled=["true" | "false"] //This property is used to indicate whether the service can be instantiated. If set to true, it can be instantiated, otherwise it cannot be instantiated. The default value is true. If the enabled attribute of an element is set to false, the broadcast is disabled and cannot be instantiated.
    android:exported=["true" | "false"]          //Whether this broadcastReceiver can receive broadcasts from other App s is interesting. The default value is determined by whether there is intent-filter in the receiver. If there is intent-filter, the default value is true, otherwise it is false. (Similarly, the default value of this property in activity/service follows the same rule)
    android:icon="drawable resource"             //This property defines an icon for broadcasting, which must refer to a drawing resource that contains the image definition. If this property is not set, the icon attribute of the < Application > element is used instead.
    android:label="string resource"              //This property is used to set the name of the broadcast to be displayed to the user. If this property is not set, the label attribute value of the < Application > element is used instead.
    android:name="string"                        //This broadcastReceiver class name
    android:permission="string"                  //If set, the broadcastReceiver can receive the broadcastReceiver only if the broadcastReceiver has the corresponding permission to send the broadcastReceiver.
    android:process="string" >                   //The broadcastReceiver runs the process. Processes that default to app. Independent processes can be specified
    . . .
    </receiver>
    

Examples of registration:

<receiver android:name=".MyBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> //Broadcasting by network state change
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" /> //Broadcasting by the system itself at start-up
    </intent-filter>
</receiver>
  • Dynamic registration:
    When registering dynamically, components do not need to be registered in Android Manifest. Broadcast Receiver can be dynamically registered in the program by calling the registerReceiver function of Context directly in the code.

    Context.registerReceiver(BroadcastReceiver receiver, IntentFilter filter);
    Context.registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler);

Call examples:

    private MyBroadcastReceiver mBroadcastReceiver;


    mBroadcastReceiver = new MyBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ACTION);
    //Dynamic Registered Broadcasting
    registerReceiver(mBroadcastReceiver, intentFilter);

    //Turn off broadcasting on Destroy
    unregisterReceiver(mBroadcastReceiver);

Broadcasting classification:

References are from: http://www.jianshu.com/p/ca3d87a4cdf3

Normal Broadcast: Ordinary Broadcast_Developer Defines Intet Broadcast

Intent intent = new Intent();
//ACTION is the action value of the intentFilter filter in the manifest file
intent.setAction(ACTION);
//Send ordinary broadcasting
sendBroadcast(intent);


//Register <receiver/> components in Android Manifest
//This broadcast receiver class is MyBroadcast Receiver 
<receiver android:name=".MyBroadcastReceiver" >
    <intent-filter> 
         <action android:name="ACTION" />
    </intent-filter>
</receiver>

System Broadcast: System Broadcast

system operation Action
Monitoring network changes android.net.conn.CONNECTIVITY_CHANGE
Turn off or turn on flight mode Intent.ACTION_AIRPLANE_MODE_CHANGED
Change in charge or power Intent.ACTION_BATTERY_CHANGED
Low battery Intent.ACTION_BATTERY_LOW
Batteries are adequately charged (i.e., they broadcast when they change from low to full). Intent.ACTION_BATTERY_OKAY
Once the system is started (broadcast only once) Intent.ACTION_BOOT_COMPLETED
When the camera button (hardware button) is pressed Intent.ACTION_CAMERA_BUTTON
Screen lock screen Intent.ACTION_CLOSE_SYSTEM_DIALOGS
When the current device settings are changed (interface language, device orientation, etc.) Intent.ACTION_CONFIGURATION_CHANGED
When inserting headphones Intent.ACTION_HEADSET_PLUG
When the SD card is not removed correctly but has been taken out (correct removal method: setting SD card and device memory uninstalling SD card) Intent.ACTION_MEDIA_BAD_REMOVAL
Insert external storage devices (such as SD cards) Intent.ACTION_MEDIA_CHECKING
Successful installation of APK Intent.ACTION_PACKAGE_ADDED
Successful deletion of APK Intent.ACTION_PACKAGE_REMOVED
reboot device Intent.ACTION_REBOOT
The screen is turned off Intent.ACTION_SCREEN_OFF
The screen is turned on Intent.ACTION_SCREEN_ON
When shutting down the system Intent.ACTION_SHUTDOWN

Ordered broadcast: Ordered broadcast

Sequence Rules for Broadcast Receivers to Receive Broadcasting (for both Static and Dynamic Registered Broadcast Receivers)

  • Priority attribute values are sorted from large to small.
  • For those with the same Priority attribute, dynamic registration is preferred.

Characteristic:

  • Receiving broadcasts in sequence
  • The first receiving broadcasting receiver can truncate the broadcasting, that is, the later receiving broadcasting receiver no longer receives the broadcasting.
  • The first broadcasting receiver can modify the broadcasting, then the later receiving broadcasting receiver will receive the modified broadcasting.

How to use it:

Intent intent = new Intent();
intent.setAction(ACTION);
//Sending Ordered Broadcasting
sendOrderedBroadcast(intent);

Sticky Broadcast: Sticky Broadcast (in android 5.0/api 21, deprecated, no longer recommended, and corresponding Sticky Ordered Broadcast, also deprecated)

Local Broadcast: Intra-App Broadcast

  • App intra-application broadcasting can be understood as a kind of local broadcasting. The sender and receiver of the broadcasting belong to the same App.
  • Compared with global broadcasting (general broadcasting), the advantages of in-App broadcasting are high security and efficiency.

Realization 1: Only dynamic registration, not static registration

//Registered intra-application broadcast receiver 
//Step 1: Instantiate BroadcastReceiver subclass & IntentFilter 
MyBroadcastReceiver mBroadcastReceiver= new MyBroadcastReceiver(); 
IntentFilter intentFilter = new IntentFilter(); 

//Step 2: Instance of Local Broadcast Manager
localBroadcastManager = LocalBroadcastManager.getInstance(this);

//Step 3: Set the type of broadcast received 
intentFilter.addAction(ACTION);

//Step 4: Call the registerReceiver () method of a single instance of LocalBroadcast Manager for dynamic registration 
localBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);

//Unregistered intra-application broadcast receiver
localBroadcastManager.unregisterReceiver(mBroadcastReceiver);

//Transmitting intra-application broadcasting
Intent intent = new Intent();
intent.setAction(ACTION);
localBroadcastManager.sendBroadcast(intent);

Mode 2:

  1. When registering broadcasting, the exported attribute is set to false, so that the broadcasting that is not issued within this App will not be received.
  2. When broadcasting is sent and received, permission is added to verify the permission.
  3. When sending a broadcast, specify the package name where the broadcast receiver is located, and the broadcast will only be sent to the valid broadcast receiver that matches the App in the packet. Entry is specified by intent.setPackage(packageName).

Custom broadcast code:

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;

    /**
     * Custom Broadcasting
     */

    public class MyBroadcastReceiver extends BroadcastReceiver{
        public static final String TAG="MyBroadcastReceiver";
        /**
        * Receiving callbacks from broadcasts
        * @param context
        * @param intent
        */
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG,"onReceive");
        }
    }

Keywords: Android Attribute xml network

Added by Virtuali on Sat, 08 Jun 2019 02:35:13 +0300