Android Learning Service Foundation

Android Service

Service (service)

It is one of the four components in Android. It can run in the background for a long time. The service does not need to provide a user interface. Even if the user switches to another application, the service can still run in the background.

1.Service Creation of

1.Service Creation of
Service creation is to create a new java class, let it inherit the service and add the unimplemented methods

	@Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

2. Configure in the manifest file
In fact, this is similar to Java Web in web.xml The configuration of the filter is the same as that of the AndroidManifest.xml Configuration under the application node in the file, the same level as activity;
Post all application nodes for easy understanding

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".RandomService">
            <intent-filter>
                <action android:name="www.lyd.random"/>
            </intent-filter>
        </service>
    </application>

Main code:

		<service android:name=".RandomService">//Service class, you can directly copy the qualified name
            <intent-filter>
                <action android:name="www.lyd.random"/>//Corresponding action
            </intent-filter>
        </service>

2. Service life cycle

  • onCreate: create service
  • onStart: start service( Two Below, abandoned)
  • onStartCommand start service( Two And use on)

1. Direct start service
When startService(intent); / / starts service
The startup service can be run multiple times, but oncreate only executes once

The service will execute onCreate()  onStartCommand() method, and the service will run until it stops when it calls stopSelf() method or other components call stopService() method, and finally it is destroyed by the system.
The service will run in the background for a long time, and the state of the service has nothing to do with the state of the initiator.

When the service is started, the

Look at the code again

Intent intent = new Intent();//Add action intent
intent.setAction("www.lyd.random");

This is android5.0 To add

intent.setPackage(MainActivity.this.getPackageName());//Android compatible Five

The first thing to run is

@Override
    public void onCreate() {
        Log.i("onCreate","Service started");//It will only start once. Before the service is stopped, no matter how many times the service is started, it will only run once
        super.onCreate();
    }

secondly

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int num = (int) (Math.random()*10);
        Log.i("random","num=" + num);
        return super.onStartCommand(intent, flags, startId);
    }


Multiple clicks

stopService(intent); / / destroy the service. It will not be destroyed if it is not opened

2. Use binding service




The service will execute oncreate() - > onbind() method. The service is in binding state. The client will close the connection through unbindService() method. When unbinding, the system will destroy the service directly.
The service is related to the state of the initiator. When the caller destroys the service, it will also be destroyed.

The binding service can only run once, that is, the binding service cannot continue after binding
Don't paste the code here. Put the total code at last

Binding service will first execute onCreate(), then onBind method, and finally execute the callback method onServiceConnected of ServiceConnection;
Run binding service

Found no output from onServiceConnected


		@Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("MainActivity","Service connected delivery information");
        }

The reason is that what is returned in onBind is null, and an IBinder should be returned, which can be called in onServiceConnected.

Multiple runs of the binding service will only run once

After clicking start service, only onStartCommand will run

Last unbind





3. Service communication

  • In Android system, there are two modes of service communication, one is local service communication, the other is remote service communication.

  • Local service communication refers to the communication within the application, while remote service communication refers to the communication between two applications. When using these two ways to communicate, we must meet the premise that the service must be opened in binding mode

Paste a class ppt

Here is the introduction. If you have any questions, please help me to prove them. Thank you!

Next, paste the code

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".RandomService">
            <intent-filter>
                <action android:name="www.lyd.random"/>
            </intent-filter>
        </service>
    </application>

</manifest>

activity.layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/start_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Start service"/>
        <Button
            android:id="@+id/stop_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Out of Service"/>
        <Button
            android:id="@+id/upBind_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Binding services"/>
        <Button
            android:id="@+id/outBind_Service"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Unbind service"/>

    </LinearLayout>
</LinearLayout>

MainActivity.java

package com.example.myservice;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
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 onClickListener listener = new onClickListener();
    private ReceiveServiceMessage conn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.start_Service).setOnClickListener(listener);
        findViewById(R.id.stop_Service).setOnClickListener(listener);
        findViewById(R.id.upBind_Service).setOnClickListener(listener);
        findViewById(R.id.outBind_Service).setOnClickListener(listener);
        conn = new ReceiveServiceMessage();
    }

    class ReceiveServiceMessage implements ServiceConnection{

        //Bind callback method
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RandomService.myBinder Binder = (RandomService.myBinder)service;
            Log.i("MainActivity","Service connected delivery information" + Binder.getNumber());

        }

        //Unbind callback method
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("MainActivity","Service disconnect");
        }
    }


    class onClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();//Add action intent
            intent.setAction("www.lyd.random");
            intent.setPackage(MainActivity.this.getPackageName());//Android compatible Five
            switch (v.getId()){
                case R.id.start_Service:
                    //Show intention to start Service
                    /**
                     * Intent intent = new Intent(com.example.myservice.RandomService.class);
                     * context.startService(intent);
                     **/
                    startService(intent);//Start service
                    break;
                case R.id.stop_Service:
                    stopService(intent);//Destroy service. It will not be destroyed if it is not opened
                    break;
                case R.id.upBind_Service:
                    bindService(intent,conn, Service.BIND_AUTO_CREATE);//Binding service is only executed once
                    break;
                case R.id.outBind_Service:
                    Boolean isBind = bindService(intent, conn, Context.BIND_AUTO_CREATE);
                    if(isBind){
                        unbindService(conn);
                        isBind = false;
                    }
                    break;
            }
        }
    }
}

RandomService.java

package com.example.myservice;

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

import androidx.annotation.Nullable;

public class RandomService extends Service {

    class myBinder extends Binder{
        int number;

        public int getNumber() {
            return number;
        }

        public void setNumber(int number) {
            this.number = number;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        myBinder MyBinder = new myBinder();
        int number = (int) (Math.random()*100) + 1;
        String str = "onBind Communication, random information:" + number;
        Log.i("onBind","Service bound "+str);
        MyBinder.setNumber(number);
        return MyBinder;//To return a Binder and null, onServiceConnected will not proceed
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("onUnBind","Unbind service");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        Log.i("onCreate","Service started");//It will only start once. Before the service is stopped, no matter how many times the service is started, it will only run once
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int num = (int) (Math.random()*10);
        Log.i("random","num=" + num);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i("onDestroy","Service destroyed");
        super.onDestroy();
    }
}

Thank you for reading!

Tags: Android xml Java encoding

Posted on Tue, 19 May 2020 04:29:48 -0700 by George W. Bush