Android 四大组件之——Service启动、绑定、解绑、停止的最基本写法

文章展示了如何在Android中注册并实现一个服务。服务名为MyService,它包含一个Binder用于交互,并使用Handler模拟了一个循环打印任务。在Activity中,通过按钮控制服务的启动、绑定、解绑和停止,并通过接口回调更新UI。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、服务注册
<?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>
二、服务的基本写法
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);
    }

}
三、Activity中操作服务
<?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;
        }
    }
}
辅助:用来回调数据的接口
package com.soface.servicedemo.Interface;

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

    void actionDo(K key, V value);

}

注:自用笔记,仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绝命三郎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值