关于初次使用Android的Service

首先了解什么是service(服务)?

service个人理解就是一个没有界面的activity,在你的手机后台去运行一些不用展示给用户的事件,比如:你把app明明已经退出了,但是任然有些app会给你弹出一些信息;这其实就是activity注销了,但是app的服务没有进行销毁;

这也只是作者本人简单的理解,因为并不是专门干app开发的,只是迫于无奈;-_-//

废话不多说上正片:

服务的两种形式:

直接启用和绑定启用

上案例:

第一件事在AndroidManifest.xml进行配置

    <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" >
        <activity android:name=".MainActivity"
            android:theme="@style/AppTheme"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name=".MyService"/>
    </application>

然后做一个小demo:

<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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button_1"
        android:layout_width="170dp"
        android:layout_height="70dp"
        android:text="开启服务"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />
    <Button
        android:id="@+id/button_2"
        android:layout_width="170dp"
        android:layout_height="70dp"
        android:text="停止服务"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_1"
        android:layout_marginTop="20dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button startService, stopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        uiInit();
        clickInit();
    }

    private void uiInit(){
        startService = findViewById(R.id.button_1);
        stopService = findViewById(R.id.button_2);
    }

    private void clickInit(){
        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: startClick is Click");
                Intent startIntent = new Intent(MainActivity.this, MyService.class);
                startService(startIntent);
            }
        });
        stopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: stopClick is click");
                Intent stopIntent = new Intent(MainActivity.this, MyService.class);
                stopService(stopIntent);
            }
        });
    }
}

不要问为什么没有用onclick的接口,问就是懒^_^||


/**
 * @Author zihaoWang
 * @Data 2023/11/11 14:47
 * @Other Write a comment, write a comment!!!
 * be sure to write a comment and type log!!!
 */
public class MyService extends Service {

    private static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: onCreate executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: is executed");
        return super.onStartCommand(intent, flags, startId);
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: is executed");
    }
}

这个时候就可以用log的方式去看服务运行的特点,当第一次打开app时然后点击开启服务就会有两个log:

一个就是onCreate:就是服务第一次使用的时候会被调用

另一个就是onStartCommand:在每次点击开启服务的button的时候就会调用一次;

记住:停止服务的按钮只能点一次,否则会出错,可以试试;

是不是很简单===但是越简单的东西就会有问题,不能进行通讯,要想进行通讯呢就要使用绑定服务喽👇👇👇

要使用绑定服务肯定就是想要进行通讯,那么先做点准备写一个demo

前面的什么.xml都不要动,使用修改MyService和MainActivity就行

/**
 * @Author zihaoWang
 * @Data 2023/11/11 14:47
 * @Other Write a comment, write a comment!!!
 * be sure to write a comment and type log!!!
 */
public class MyService extends Service {

    private OtherThing thing = new OtherThing();

    class OtherThing extends Binder{
        public void start(){
            Log.d(TAG, "start: start something executed");
        }
        public int getThing(){
            Log.d(TAG, "getThing: get something executed");
            return 0;
        }
    }


    private static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: onCreate executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: is executed");
        return super.onStartCommand(intent, flags, startId);
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: is executed");
    }
}

注意在onBind中的返回;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private MyService.OtherThing otherThing;

    private Button startService, stopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        uiInit();
        clickInit();
    }

    private ServiceConnection connection = new ServiceConnection() {

        //处理绑定成功的方法
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            if (iBinder instanceof MyService.OtherThing){
                Log.d(TAG, "onServiceConnected: is bind");
                otherThing = (MyService.OtherThing) iBinder;
                otherThing.start();
                otherThing.getThing();
            }
        }

        //处理绑定失败的方法
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(TAG, "onServiceDisconnected: is not bind");
        }
    };

    private void uiInit(){
        startService = findViewById(R.id.button_1);
        stopService = findViewById(R.id.button_2);
    }

    private void clickInit(){
        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: startClick is Click");
                Intent bindIntent = new Intent(MainActivity.this, MyService.class);
                bindService(bindIntent, connection, BIND_AUTO_CREATE);//开始绑定
            }
        });
        stopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: stopClick is click");
                unbindService(connection);
            }
        });
    }
}

然后开始运行:

点击开启服务会有三个log:

然后一直点击开启服务都不会有log

停止服务的时候:

同样停止服务的时候只能点一次;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值