Android Basic Learning Day11 | Common Components-Broadcast and Service

Words written in the front

1. Main reference from: https://b23.tv/Flmxaa
2. If there is something wrong in the content, I hope to point out or add.
3. New knowledge.

1. Broadcast

(1) Broadcast receiver

① Overview

Broadcast Receiver (BroadcastReceiver): There are many broadcasts built into the Android system. For example, a broadcast will be sent when the phone is turned on and the battery is low. In order to monitor broadcast events from the system or applications, the Android system provides a broadcast receiver component (one of the four major components). 当Android系统产生一个广播事件时,可以有多个对应的广播接收者接收并进行处理. It is equivalent to a radio that receives radio messages.

Features: One -to-many (for example, the frequency sent by a radio station can be received by multiple radios), and the message is one-way (for example, the radio can only receive messages).

② Test

1 Create a broadcast receiver.
Insert picture description here
Insert picture description here
2 Dynamically register broadcast receivers-create

Static registration: Generally, the system will automatically create it in the project manifest file.

The characteristics of dynamic registration: Only when the component that registers the broadcast receiver is alive (exists), the corresponding broadcast receiver will receive the broadcast, which is also the difference from static registration.
Insert picture description here
3 Test-Intercept call

① Layout
Insert picture description here
② Code part
Insert picture description here
Insert picture description here
③ Operation effect

The project list file is
Insert picture description here
as follows:
Insert picture description here

(2) Sending and receiving of custom broadcasts

① Overview

When the broadcast provided by the system cannot meet the needs, you can customize the broadcast (send messages), and you need to write the corresponding broadcast receivers (monitor messages).

当自定义广播发送消息时,会存储到公共消息区中,而公共消息区中如果存在对应的广播接收者,就会及时的接收这条消息

② Test

1 Layout and MainActivity.java content
Insert picture description here
Insert picture description here
2 Test effect

The same reason as the above test, processing the project manifest file (declaring the intention of the custom broadcast event)
Insert picture description here
running results:
Insert picture description here

(3) Orderly broadcast and disorderly broadcast

① Overview

The Android system provides two types of broadcasting, ordered broadcasting and unordered broadcasting. Developers can set different broadcasting types for the program according to their needs.

Orderly broadcast: Receive according to the priority of the receiver, and only one broadcast receiver can receive the message 此广播接收者中逻辑执行完毕后,才会继续传递.

Out-of-order broadcast: It is complete 异步执行. All broadcast receivers who listen to the broadcast will receive this message when sending the broadcast, but the order of reception is uncertain.

有序广播可以被拦截;无序广播所有的广播接收者都可以接收到消息

② Test-orderly broadcast

Need to create three new broadcast receivers for better testing. The settings of these three broadcast receivers are similar, such as:
Insert picture description here
1 Layout slightly

2 running effect

The
Insert picture description here
effect of the project list file is as follows:
Insert picture description here
Note: If the value of priority is the same (the same priority), then it is declared first in the project list file (position in the front) to receive the message first. If the high-priority broadcast is interrupted (written in the broadcast receiver 拦截有序广播:abortBroadcast();), the lower priority will no longer receive the message, but there are methods (as shown below-written in the send method) to force the broadcast receiver Message received.
Insert picture description here

2. Service

Day12 content.
Service (Service) is also one of the four major components, which can be regarded as an activity without an interface (usually used for background operations, such as playing music after the phone screen is off).
The biggest feature: It can run in the background for a long time.

(1) Basic knowledge

Creation: similar to the creation of broadcast receivers (right-click on the package name and select [New] → [Service] → [Service] → enter the service name or default in the pop-up window); if you use self-created Java class To create a service by inheriting the Service class, you need to manually register it in the project manifest file.

Life cycle: that is, a process from startup to shutdown. Turn ↓
Insert picture description here
start method:

① Through the startService() method: the service will run in the background for a long time, and the status of the service has nothing to do with the status of the opener, that is, even if the component that started the service has been destroyed, the service will still run. 需要自身调用stopSelf()方法或其他组件调用stopService()方法时服务才能停止.

② Through the bindService() method: the service will be bound to the component. 需要调用onUnbind()方法解除绑定之后才会被销毁. Note: If you want to exist for a long time, you need to start the service with startService (combined use) before binding.

(Two) test

① startService starts Service

1 Layout
Insert picture description here
2 Service class
Insert picture description here
3 Summary of display results
Insert picture description here
: onCreate() means that it is executed when the service is created (it will no longer have any effect after the creation is successful), only called once; execute multiple times to start the service (as long as the service is still started) ) Will call onStartCommand() multiple times and only reuse the service object generated before, and will not create a new service object; onDestroy() means to close the service, the same as onCreate(), only called once.

② bindService starts Service

1 The layout is omitted (same as the layout setting of ①)

2 code

① MyService.java

In the OnBind() method, an IBinder instance needs to be returned, otherwise the method for monitoring the connection status will not be called.

package com.example.testservice;

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

public class MyService extends Service {
    
    
    public MyService() {
    
     }

    //定义onBinder方法所返回的对象实例
    //创建服务代理 调用服务中的方法
    class MyBinder extends Binder{
    
    
        //可以间接调用到service里面的相关方法
        public void callTestInService(){
    
    
            testInService();
        }
    }
    public void testInService(){
    
    
        Log.i("MyService","自定义方法,testInService()");
    }

    @Override
    //IBinder是一个接口  可进行跨进程访问(远程调用)
    public IBinder onBind(Intent intent) {
    
    
        Log.i("MyService","绑定服务,调用onBind()");
        return new MyBinder();
    }

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        Log.i("MyService","创建服务,调用onCreate()");
    }

    @Override
    //解绑
    public boolean onUnbind(Intent intent) {
    
    
        Log.i("MyService","解绑服务,调用onUnbind()");
        return super.onUnbind(intent);
    }
}

② MainActivity.java

package com.example.testservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    
    
    private MyService.MyBinder myBinder;
    private MyTest mytest;

    @Override
    //自带
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //绑定(开启)服务
    public void btnBind(View view){
    
    
        if(mytest == null){
    
    
            mytest = new MyTest();
        }
        Intent intent = new Intent(this,MyService.class);
        //参数1:用于指定要启动的service,参数2:监听调用者与service间的连接状态,
        // 参数3:指定绑定时是否自动创建service
        bindService(intent,mytest,BIND_AUTO_CREATE);
    }

    //服务连接时执行
    private class MyTest implements ServiceConnection{
    
    
        @Override
        //当成功绑定服务时调用,返回MyService里面的Ibinder对象
        public void onServiceConnected(ComponentName name, IBinder service) {
    
    
            myBinder = (MyService.MyBinder) service;
            Log.i("MainActivity","服务成功绑定,内存地址为:"+myBinder.toString());
        }
        //当服务失去连接时,调用的方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
    
    
            Log.i("MainActivity","服务失去连接");
        }
    }

    //调用服务中的方法
    public void btnCall(View view){
    
    
        //访问到MyService里的callTestInService()方法
        myBinder.callTestInService();
    }

    //解绑服务
    public void btnUnbind(View view){
    
    
        //需要判断是因为:解除绑定时就需要接收ServiceConnection
        if(mytest != null){
    
    
            unbindService(mytest);
            mytest = null;
        }
    }
}

3 Summary of display results
Insert picture description here
: When the service is started multiple times, onBind() is only called once.

Three, supplement

1. As long as the four major components of Android are defined, they must be registered in AndroidManifest.xml (manifest file). Generally, the system will automatically register.

2. The intent error problem encountered

Guess you like

Origin blog.csdn.net/luck_ch09/article/details/112847532