安卓学习笔记——服务(Service)

安卓实验(Service)

在Android Studio创建计时服务,并使用两个按钮进行控制

1. 创建两个按钮控件

在activity_main.xml中添加如下代码新建两个按钮控件,也可在Design窗口中拖动控件进行添加

<Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:text="@string/start_button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

<Button
        android:id="@+id/stop_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="350dp"
        android:text="@string/stop_button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

开始计时和停止计时按钮

2. 创建用于计时的服务(Service)

新建java文件TimerService.java,用于实现计时服务类。在文件中新建TimerService类并重写onCreate()、onBind()、onStartCommand()、onDestroy()。
我们在onStartCommand()方法中实现后台计时功能,并在控制台进行输出,为了防止Service卡死Activity导致界面无法点击,我们需要在该方法中创建一个线程来完成计时。返回START_STICKY保证服务在后台运行

public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("TimerService","onStartCommand");
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run(){
                while(!threadDisable){
                    Log.v("TimerService","Timer is " + timer);
                    timer++;
                    try{
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                    }
                }
            }
        }).start();

        return START_STICKY;
    }

TimerService.java完整代码

加上自己的包名

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

import androidx.annotation.RequiresApi;

public class TimerService extends Service {
    private boolean threadDisable;
    private int timer;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.v("TimerService","oncreat");
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("TimerService","onStartCommand");
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run(){
                while(!threadDisable){
                    Log.v("TimerService","Timer is " + timer);
                    timer++;
                    try{
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                    }
                }
            }
        }).start();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("TimerService","onDestroy");
    }
}

3. 注册TimerService服务

创建完TimerServer服务类后需要在AndroidMainfest.xml中注册才能使用
在AndroidMainfest.xml中的<application>添加

<service android:name=".TimerService"/>

4. 按钮功能实现

在MainActivity中实现按钮的功能,创建Intent对象,使用Intent对象来控制服务的开启和关闭。

实现代码

        Button start_button = findViewById(R.id.start_button);
        Button stop_button = findViewById(R.id.stop_button);

        start_button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                final Intent intent = new Intent(MainActivity.this, TimerService.class);
                startService(intent);
            }
        });

        stop_button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                final Intent intent = new Intent(MainActivity.this, TimerService.class);
                stopService(intent);
            }
        });

5. 进行调试运行

在debug下运行app,点击开始计时按钮后在控制台可查看当前计时时间,点击停止计时可将服务停止,再次点击开始计时会重新进行计时。
调试运行结果

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值