Eine der vier Hauptkomponenten von Android – die einfachste Schreibweise für das Starten, Binden, Aufheben und Beenden von Diensten

1. Dienstregistrierung

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ServiceDemo"
        tools:targetApi="31">

        <!--服务注册-->
        <service
            android:name="com.soface.servicedemo.service.MyService"
            android:enabled="true"
            android:exported="true"></service>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Zweitens die grundlegende Schreibmethode des Dienstes

package com.soface.servicedemo.service;

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

import androidx.annotation.NonNull;

import com.soface.servicedemo.Interface.ActionCallback;

public class MyService extends Service {
    
    

    private MyBinder binder=new MyBinder();
    public class MyBinder extends Binder{
    
    
        public MyService getService(){
    
    
            return MyService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
    
    
        Log.d("fxHou","onBind");
        return binder;
    }

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        Log.d("fxHou","onCreate");
        startCycle();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
    
        Log.d("fxHou","onStartCommand");
        return START_NOT_STICKY;//非粘性服务
    }

    @Override
    public boolean onUnbind(Intent intent) {
    
    
        Log.d("fxHou","onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
    
    
        super.onDestroy();
        Log.d("fxHou","onDestroy");
        stopCycle();
    }

    ActionCallback<String,Integer> actionCallback;
    public void getAction(ActionCallback<String,Integer> actionCallback){
    
    
        this.actionCallback=actionCallback;
    }

    //==================================Handler模拟一个循环打印任务=====================================

    private int MESSAGE_WHAT=0xFFFF;
    private int progress=0;
    private Handler handler=new Handler(Looper.getMainLooper()){
    
    
        @Override
        public void handleMessage(@NonNull Message msg) {
    
    
            super.handleMessage(msg);
            if (msg.what==MESSAGE_WHAT){
    
    
                if (actionCallback!=null)actionCallback.actionDo("Progress",msg.arg1);
                startCycle();
            }
        }
    };

    //开始循环
    private void startCycle(){
    
    
        progress=progress+1;
        Message message=new Message();
        message.what=MESSAGE_WHAT;
        message.arg1=progress;
        handler.sendMessageDelayed(message,1000);
    }

    //停止循环
    private void stopCycle(){
    
    
        handler.removeMessages(MESSAGE_WHAT);
    }

}

3. Betriebsdienst in Aktivität

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="@color/black"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/start_service"
            android:text="启动"
            android:textSize="20dp"
            android:backgroundTint="@color/white"
            android:textColor="@color/black"
            android:layout_width="100dp"
            android:layout_height="100dp"/>

        <Button
            android:id="@+id/bind_service"
            android:text="绑定"
            android:textSize="20dp"
            android:backgroundTint="@color/white"
            android:textColor="@color/black"
            android:layout_width="100dp"
            android:layout_height="100dp"/>

        <Button
            android:id="@+id/unbind_service"
            android:text="解绑"
            android:textSize="20dp"
            android:backgroundTint="@color/white"
            android:textColor="@color/black"
            android:layout_width="100dp"
            android:layout_height="100dp"/>

        <Button
            android:id="@+id/stop_service"
            android:text="停止"
            android:textSize="20dp"
            android:backgroundTint="@color/white"
            android:textColor="@color/black"
            android:layout_width="100dp"
            android:layout_height="100dp"/>

        <SeekBar
            android:id="@+id/progress"
            android:background="@color/white"
            android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:layout_height="40dp"/>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
package com.soface.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
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;
import android.widget.Button;
import android.widget.SeekBar;

import com.soface.servicedemo.Interface.ActionCallback;
import com.soface.servicedemo.service.MyService;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    

    private Intent myServiceIntent;
    private SeekBar progress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button start=(Button) findViewById(R.id.start_service);
        Button bind=(Button) findViewById(R.id.bind_service);
        Button unbind=(Button) findViewById(R.id.unbind_service);
        Button stop=(Button) findViewById(R.id.stop_service);
        progress=(SeekBar)findViewById(R.id.progress);
        progress.setMax(100);

        start.setOnClickListener(this::onClick);
        unbind.setOnClickListener(this::onClick);
        bind.setOnClickListener(this::onClick);
        stop.setOnClickListener(this::onClick);

        myServiceIntent=new Intent(this, MyService.class);
    }

    private ServiceConnection connection=new ServiceConnection() {
    
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
    
    
            Log.d("fxHou","绑定="+name);
            MyService.MyBinder myBinder= (MyService.MyBinder) service;
            myBinder.getService().getAction(new ActionCallback<String, Integer>() {
    
    
                @Override
                public void actionDo(String key, Integer value) {
    
    
                    Log.d("fxHou",key+"="+value);
                    progress.setProgress(value);
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
    
    
            Log.d("fxHou","断开绑定="+name);
        }
    };

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.start_service:
                startService(myServiceIntent);
                break;
            case R.id.bind_service:
                bindService(myServiceIntent,connection, Service.BIND_AUTO_CREATE);
                break;
            case R.id.unbind_service:
                unbindService(connection);
                break;
            case R.id.stop_service:
                stopService(myServiceIntent);
                break;
            default:
                break;
        }
    }
}

Auxiliary: Die Schnittstelle, die zum Abrufen von Daten verwendet wird

package com.soface.servicedemo.Interface;

/**
 * 回调接口
 * @param <K>
 * @param <V>
 */
public interface ActionCallback<K,V> {
    
    

    void actionDo(K key, V value);

}

Hinweis: Hinweise für den persönlichen Gebrauch, nur als Referenz

おすすめ

転載: blog.csdn.net/qq_41008818/article/details/129222107