Broadcast Use Details

Posted by GreyBoy on Mon, 05 Aug 2019 09:19:42 +0200

Strongly Recommend Articles: Welcome to Collection
Android Dry Goods Sharing

Read for five minutes, ten o'clock a day, and study with you for life. Here's Android, a programmer.

This article mainly introduces some knowledge points in Android development. By reading this article, you will gain the following contents:

  1. Life Cycle of Broadcasting
  2. One of the four components must be registered in Androidmainfest.xml
  3. Registration of Broadcasting (Static Broadcasting, Dynamic Broadcasting)
  4. Broadcasting (normal, orderly, continuous)
  5. Broadcasting Receiving (System Broadcasting, Custom Broadcasting)

Broadcast yes Android One of the four components is a widely used mechanism for asynchronous transmission of information between applications.
Broadcast Essentially aIntent Objects, the difference is Broadcast Can be multiple BroadcastReceiver Handle.BroadcastReceiver Is a global listener, through which onReceive() It can filter the broadcasting users want, and then do other operations.

1. BroadcastReceiver brief introduction

BroadcastReceiver Inheritance relationship

BroadcastReceiver The default is to execute in the main thread ifonReceiver() Method Handling Event Overrun10s,Then the application will happenANR(Application Not Responding),At this point, if the establishment of worker threads does not solve this problem, it is recommended that: if dealing with time-consuming operations, please use Service Instead.

BroadcastReceiverThe relationship of succession is as follows:

java.lang.Object
   ↳    android.content.BroadcastReceiver

BroadcastReceiver's main declarative cycle method, onReceiver(), will be destroyed when this method is executed.

2. One of the four components must be registered in Androidmainfest.xml

        <receiver
            android:name="ReceiverMethod"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="String....." />
            </intent-filter>
        </receiver>

Be careful:
Failure to register will result in inability to receive and process broadcast messages

3. Broadcasting Registration (Static Registration, Dynamic Registration)

There are two kinds of broadcasting registration, one is static registration in ndroidMfest.xml, the other is dynamic registration in Java code.

1. Static registration

Some systems send broadcasts that need to be registered statically in Androidmainfest.xml, such as boot-up broadcasting, apk status change broadcasting, power status change broadcasting, etc. These statically registered broadcasts typically intercept specific strings in Androidmainfest.xml.

The method of static registration broadcasting is as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.programandroid"
    android:versionCode="1"
    android:versionName="1.0" >
         ... ...
        <receiver
            android:name="com.programandroid.BroadcastReceiver.NotificationReceived"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="Notification_cancel" />
                <action android:name="Notification_music_pre" />
                <action android:name="Notification_music_play" />
                <action android:name="Notification_music_next" />
            </intent-filter>
        </receiver>
        ... ...

1. Static registration boot-up broadcasting method

Start-up broadcasting is quite special, so you need to add permissions in Androidmainfest.xml. Otherwise, the boot broadcast cannot be obtained.

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

//Static Registration Broadcasting Method
        <receiver
            android:name=".component.BroadcastReceiver.BootReceiverMethod"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

2. Dynamic Registered Broadcasting

In Java, broadcasting is dynamically registered in the following format:

  //Dynamic Registered Broadcasting
  registerReceiver(BroadcastReceiver, IntentFilter);

Dynamic registration monitors the broadcasting of screen-killing and screen-lighting

When registering broadcasts dynamically in broadcasting, please note that context.getApplicationContext() must be used to prevent contexts from being null and causing null pointer exceptions.

public class ScreenOnOffReceiver {

    public static void ReceiverScreenOnOff(Context context) {
        IntentFilter screenOffFilter = new IntentFilter();
        screenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
        screenOffFilter.addAction(Intent.ACTION_SCREEN_ON);
        BroadcastReceiver mScreenOnOffReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                String action = intent.getAction();
                if (action.equals(Intent.ACTION_SCREEN_OFF)) {

                    Toast.makeText(context, "Receiving Screen Extinguishes Broadcasting", Toast.LENGTH_SHORT).show();

                }
                if (action.equals(Intent.ACTION_SCREEN_ON)) {

                    Toast.makeText(context, "Receiving Screen Lights Broadcasting", Toast.LENGTH_SHORT).show();
                }


            }

        };
        /**
         * context.getApplicationContext()
         * When registering broadcasting in broadcasting, attention should be paid to prevent null context from causing null pointer abnormalities.
         * **/
// 2. The Method of Dynamic Registration Broadcasting
        context.registerReceiver(mScreenOnOffReceiver, screenOffFilter);

    }
}

4. Broadcasting (disorderly, orderly and continuous)

1. The Method of Sending Disordered Broadcasting

Sending disorderly broadcasts is very common in Android, and it is a one-to-many relationship, mainly through sendBroadcast(intent); sending broadcasts.

Send a custom broadcast case

The broadcaster makes it clear that it is an Intent marked with strings such as Action. Examples of sending custom broadcasts are as follows:

        Intent customIntent=new Intent();
        customIntent.setAction("SendCustomBroadcast");
        sendBroadcast(customIntent);

Method of Receiving Custom Broadcasting

When the user is interested in certain broadcasts, the broadcasts can be acquired at this time, and then the onReceive method handles the operation of receiving broadcasts.


public class CustomBroadcast extends BroadcastReceiver {
    public CustomBroadcast() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("SendCustomBroadcast")){
            Toast.makeText(context,"Successful custom broadcasting reception: Action:SendCustomBroadcast",Toast.LENGTH_SHORT).show();
        }
    }
}

Note that custom broadcasts are registered statically in Androidmanfest.xml.

2. Sending Ordered Broadcasting

Broadcasting has priority in Android. Broadcasting with high priority can terminate or modify broadcast content. The method of sending ordered broadcasting is as follows: sendOrdered Broadcast (intent, "str_receiver_permission");

For example, send a custom ordered broadcast

        Intent customOrderIntent=new Intent();
        customOrderIntent.setAction("SendCustomOrderBroadcast");
        customOrderIntent.putExtra("str_order_broadcast","The boss said: Everyone in the company sends 10 mooncakes.");
        sendOrderedBroadcast(customOrderIntent,"android.permission.ORDERBROADCAST");

Broadcasting belongs to four components, and must be registered in AndroidMainfest.xml.

Ordered broadcasting static registration

The static registration method for receiving ordered broadcasting is as follows:

       <receiver
            android:name=".component.BroadcastReceiver.CustomHightBrodcast"
            android:enabled="true"
            android:exported="true"
           >
            <intent-filter android:priority="1000">
                <action android:name="SendCustomOrderBroadcast" />
            </intent-filter>
        </receiver>

        <receiver
            android:name=".component.BroadcastReceiver.CustomMiddleBroadcast"
            android:enabled="true"
            android:exported="true"
          >
            <intent-filter android:priority="500">
                <action android:name="SendCustomOrderBroadcast" />
            </intent-filter>
        </receiver>
        <receiver
            android:name=".component.BroadcastReceiver.CustomLowerBroadcast"
            android:enabled="true"
            android:exported="true"
           >
            <intent-filter android:priority="100">
                <action android:name="SendCustomOrderBroadcast" />
            </intent-filter>
        </receiver>
    1. Ordered broadcasting, high priority broadcasting can be processed first
public class CustomHightBrodcast extends BroadcastReceiver {
    public CustomHightBrodcast() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("SendCustomOrderBroadcast")) {
            Toast.makeText(context, intent.getStringExtra("str_order_broadcast"), Toast.LENGTH_SHORT).show();
            Bundle bundle=new Bundle();
            bundle.putString("str_order_broadcast","Manager said: The company sends out five mooncakes per person.");
//            Modification of broadcast transmission data
            setResultExtras(bundle);
        }
    }
}
    1. Post-processing of medium-priority broadcasting
public class CustomMiddleBroadcast extends BroadcastReceiver {
    public CustomMiddleBroadcast() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("SendCustomOrderBroadcast")) {
            Toast.makeText(context, getResultExtras(true).getString("str_order_broadcast"), Toast.LENGTH_SHORT).show();
            Bundle bundle=new Bundle();
            bundle.putString("str_order_broadcast","Supervisor: The company sends out 2 mooncakes per person.");
            setResultExtras(bundle);
        }
    }
}
    1. Low Priority Broadcast Final Processing
public class CustomLowerBroadcast extends BroadcastReceiver {
    public CustomLowerBroadcast() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("SendCustomOrderBroadcast")) {
            String notice= getResultExtras(true).getString("str_order_broadcast");
            Toast.makeText(context,notice, Toast.LENGTH_SHORT).show();
//          Stop broadcasting and continue to spread
            abortBroadcast();
        }
    }
}

Be careful:
Orderly broadcasting requires declaring and using permissions

  • 1. Declare permissions
 <! - Application for permission to use customized ordered broadcasting - >
 <uses-permission >   android:name="android.permission.ORDERBROADCAST" />
  • 2. Declaring permissions
 <!-- Privileges to customize ordered broadcasting -->
 <permission>
android:name="android.permission.ORDERBROADCAST"/>

In ordered broadcasting, high-priority broadcasting receives broadcasting, which can modify data and then transmit it to low-priority broadcasting.

3. Send continuous broadcasting (already abandoned)

Sticky broadcasting will always exist in Android systems, but with the constant updating of Android systems, this method is gradually abandoned, using the following methods: sendSticky Broadcast (intent);

5. Broadcasting Receiving (System Broadcasting, Custom Broadcasting)

When the broadcast is sent out, how to receive the broadcast? The following will introduce the method of receiving the broadcast.
The receiving broadcast class mainly inherits Broadcast Receiver, then filters the Intent carried in the broadcast Action by onReceive method, and then processes it.

Method of receiving boot-up broadcasting

1. Implementing BootReceiver Method to inherit Broadcast Receiver

p ublic class BootReceiverMethod extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //   Receiving boot-up broadcasts to handle things, such as booting services
        Intent mStartIntent = new Intent(context, StartServiceMethods.class);
        context.startService(mStartIntent);
    }
}

2. Declare component information in Androidmainfest.xml and filter boot to complete Action

        <receiver
            android:name=".component.BroadcastReceiver.BootReceiverMethod"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

3. Declare the permission to receive boot-up broadcasting

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

Strongly Recommend Articles: Welcome to Collection
Android Dry Goods Sharing

Read for five minutes, ten o'clock a day, and study with you for life. Here's Android, a programmer.

This article mainly introduces some knowledge points in Android development. By reading this article, you will gain the following contents:

  1. Introduction to Service
  2. One of the four components must be registered in Androidmainfest.xml
  3. Startup mode startup service
  4. Binding Mode Binding Service
  5. Front Office Service
  6. AIDL Remote Service

Service is one of the four components of Android (Activity Activity, Service Service Service, Content Provider Content Provider, Broadcast Receiver Broadcasting). Compared with Activity, Activity runs in the foreground, users can see, Service runs in the background, without user interface, users can not see.

Service is mainly used for interaction between components (e.g. interaction with Activity, ContentProvider, Broadcast Receiver), time-consuming background operations (e.g. downloading files, playing music, etc.), but service can not run longer than 20 seconds in the main thread, otherwise ANR will appear. Time-consuming operations are generally recommended in sub-threads. Operate.

1. Introduction to Service

Before we understand the life cycle of Service, let's first understand the inheritance relationship of Service, so that we can better understand Service.

Service inheritance is as follows:

java.lang.Object
   ↳    android.content.Context
        ↳    android.content.ContextWrapper
             ↳    android.app.Service

Two Startup Modes of Service

Service has two different startup modes, and different startup modes correspond to different life cycles.
Service startup mode is divided into two main types: 1. Startup mode. 2. Binding mode.

1. Startup mode

This mode is started by the startService() method, which can run in the background all the time and will not die with the death of the startup component. It can only perform a single operation, and can not return the result to the caller. It is often used for downloading, uploading files, playing music and so on.

2. Binding mode

This pattern is initiated by calling bindService() from a binding component (Activity, etc.), which is unbounded with the death of the binding component.

If no other startService() is started at this time, the service will die with the death of the binding component.
Multiple components can not only bind a Service at the same time, but also perform cross-process operations through interprocess communication (IPC).

3. Two services can run simultaneously

The Service in startup mode and binding mode can run at the same time. When the Service is destroyed, the Service can only be destroyed if both modes do not use Service, otherwise it will cause an exception.

4. Life Cycle of Two Service Patterns

The life cycles of the two Service modes are as follows:

2. One of the four components must be registered in Androidmainfest.xml

Service registration method is as follows:

<manifest ... >
  ...
  <application ... >
      <service android:name=".ServiceMethods" />
      ...
  </application>
</manifest>

Be careful:

If service is not registered, it will not cause App Crash like Activity. Service will not report abnormal information without registering, but the service will not come up, and it is easy to be confused if it does not pay attention to it.

3. Startup mode

Service started by boot mode, if not actively shut down, the service will always be.

How to Start Services in Startup Mode

        Intent  mBindIntent = new Intent(ServiceMethods.this, BindServiceMethods.class);
        startService(mStartIntent);

Start Mode Starts the Life Cycle of Services

Here is a way to validate the lifecycle of service startup in startup mode. For a detailed lifecycle, see the lifecycle diagram of Service above.

01-03 17:16:36.147 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onCreate----
01-03 17:16:36.223 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onStartCommand----
01-03 17:16:38.174 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onDestroy----

Startup mode startup service case

This case function: Start the service and create notifications in the service

    // Service Creation Method
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "----onCreate----");
    }
    // Service Startup Method
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "----onStartCommand----");
        // Get Notification Manager instance
        notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Instantiate NotificationCompat.Builder and set related properties
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this)
        // Setting small icons
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(
                        BitmapFactory.decodeResource(getResources(),
                                R.drawable.ic_launcher))
                // Setting Notification Title
                .setContentTitle("I passed StartService Notification of service startup")
                // Setting notification cannot be automatically cancelled
                .setAutoCancel(false).setOngoing(true)
                // Set the notification time, default to the time when the system notifies, usually not set
                // .setWhen(System.currentTimeMillis())
                // Setting Notification Content
                .setContentText("Please use StopService Method Stop Service");

        // Generate Notification object through builder.build() method and send notification, id=1
        notifyManager.notify(1, builder.build());

        return super.onStartCommand(intent, flags, startId);
    }
    // Service Destruction Method
    @Override
    public void onDestroy() {
        Log.i(TAG, "----onDestroy----");
        notifyManager.cancelAll();
        super.onDestroy();
    }

4. Binding Mode Starts Binding Service

The Service started in binding mode will be unbound as the binding gradually disappears. If the Service is not started in startup mode at this time, the Service will be destroyed.

The Method of Starting Binding Service in Binding Mode

Binding mode is a Service that is started through other components.

How to Start Binding Mode Service

    // Start Binding Service Processing Method
    public void BtnStartBindService(View view) {
        // Start Binding Service Processing Method
        bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        isBindService = true;
        Toast.makeText(ServiceMethod.this, "start-up " + mBindCount + " Sub-Binding Service",
                Toast.LENGTH_SHORT).show();
    }

    
    public void BtnSopBindService(View view) {
        if (isBindService) {
            // Unbound Service Processing Method
            unbindService(serviceConnection);
            Toast.makeText(ServiceMethod.this, "Relieve " + mUnBindCount + " Sub-Binding Service",
                    Toast.LENGTH_SHORT).show();
            isBindService = false;
        }

    }

Binding services die with the death of binding components

The lifecycle callback code for the binding pattern is as follows:

    // Service Creation Method
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "----onCreate----");
    }

    // Service binding method
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "----onBind----");

        MyBinder myBinder = new MyBinder();
        return myBinder;
    }

    // Service unbinding method
    @Override
    public boolean onUnbind(Intent intent) {

        Log.i(TAG, "----onUnbind----");
        return super.onUnbind(intent);

    }

    // Service Destruction Method
    @Override
    public void onDestroy() {
        Log.i(TAG, "----onDestroy----");
        super.onDestroy();
    }

The life cycle code of the binding service prints the Log information as follows:

01-03 20:32:59.422 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onCreate----
01-03 20:32:59.423 13306-13306/com.android.program.programandroid I/BindService wjwj:: -----onBind-----
01-03 20:33:09.265 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onUnbind----
01-03 20:33:09.266 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onDestroy----

Binding service case

Function: Get the number of times the binding mode starts the binding service and unbounds the service

Binding service classes

package com.android.program.programandroid.component.Service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BindServiceMethods extends Service {
    private static final String TAG = "BindService wjwj:";

    public BindServiceMethods() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "----onCreate----");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "----onBind----");

        MyBinder myBinder = new MyBinder();
        return myBinder;
    }


    @Override
    public boolean onUnbind(Intent intent) {

        Log.i(TAG, "----onUnbind----");
        return super.onUnbind(intent);

    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "----onDestroy----");
        super.onDestroy();
    }
}
  • Interaction between components and binding service classes
 //    Start Binding Service Processing Method
    public void BtnStartBindService(View view) {

        bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        isBindService = true;
        Toast.makeText(ServiceMethods.this,"start-up "+mBindCount+" Sub-Binding Service",Toast.LENGTH_SHORT).show();
    }

    //    Unbound Service Processing Method
    public void BtnSopBindService(View view) {
        if (isBindService) {
            unbindService(serviceConnection);
            Toast.makeText(ServiceMethods.this,"Relieve "+mUnBindCount+" Sub-Binding Service",Toast.LENGTH_SHORT).show();
            isBindService=false;
        }

    }
  • Binder interface class required for interaction between components
/**
* This class provides the interface between the binding component and the binding service provider
* */
public class MyBinder extends Binder {
   private int count = 0;

    public int getBindCount() {
        return ++count;
    }
    public int getUnBindCount() {
        return count> 0 ? count-- : 0;
    }
}

5. Improving the Priority of Services

The default way to start a service is backstage service, but by setting the service as the front service, the priority of the service can be increased, thus avoiding the service process being killed when the memory of the mobile phone is tight.

Two Methods of Setting up Front Office Service

1. Set up as Front Desk Service

//Set up as Front Desk Service
startForeground(int, Notification)

2. Cancellation of Front Desk Service

//Cancel Front Desk Service
stopForeground(true);

Start Foreground Front Office Service Case

Function: Front-end service binding notification information, improve the priority of service process, otherwise cancel notification information

package com.android.program.programandroid.component.Service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.android.program.programandroid.R;

public class MyStartForcegroundService extends Service {

    public MyStartForcegroundService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("start_forceground_service")) {

//        Get Notification Manager instance
            NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        Instantiate NotificationCompat.Builder and set related properties
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
//                Setting small icons
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//                Setting Notification Title
                    .setContentTitle("I passed startForeground Start the Front Desk Service Notice")
//                Setting notification cannot be automatically cancelled
                    .setAutoCancel(false)
                    .setOngoing(true)
//                Set the notification time, default to the time when the system notifies, usually not set
//                .setWhen(System.currentTimeMillis())
//               Setting Notification Content
                    .setContentText("Please use stopForeground Method Changed to Backstage Service");

            //Generate Notification object through builder.build() method and send notification, id=1
//        Set up as Front Desk Service
            startForeground(1, builder.build());

        } else if (intent.getAction().equals("stop_forceground_service")) {
            
            stopForeground(true);
        }

        return super.onStartCommand(intent, flags, startId);
    }
}

6. Using AIDL Interface to Realize Remote Binding

As there are many contents, a detailed introduction will be given in the following section.

So far, this article is over. If there are any mistakes, you are welcome to make suggestions and corrections. At the same time look forward to your attention, thank you for reading, thank you!

Topics: Android xml Java encoding