安卓-启动服务并让服务自己结束

本文介绍了一个简单的Android服务自终止示例。通过一个按钮触发服务启动,服务内部运行一个计数循环,并在计数值达到500时调用stopSelf()方法主动结束自身。文章提供了完整的代码实现。

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

让服务自己结束主要用到一个API就是stopSelf();

下面写一个demo来演示下:

1)主界面中一个按钮,点击启动服务

2)服务中开始服务时开启一个线程执行一个for循环打印日志

3)当执行到500时停止服务

先看下打印的日志:

I/StopService: run: i=499
I/StopService: run: i=500
I/StopService: onDestroy: 
I/StopService: run: i=501
I/StopService: run: i=502

只看下日志中的关键的部分,可以看到i=500下面打印出了onDestroy,说明服务已停止了。

下面看下演示代码:

activity_stop_service.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_stop_service"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mobile.cdtx.blog.main.activity.StopServiceActivity">
    <Button
        android:id="@+id/id_btn_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="启动服务"/>

</RelativeLayout>

主Activity代码

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.mobile.cdtx.blog.R;
import com.mobile.cdtx.blog.main.service.StopService;

import static com.mobile.cdtx.blog.R.id.id_btn_start;

public class StopServiceActivity extends AppCompatActivity {
    Button btnStart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stop_service);

        btnStart = (Button)findViewById(id_btn_start);
        btnStart.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                onStartService();
            }
        });
    }

    //启动服务
    private void onStartService(){
        Intent intent = new Intent(StopServiceActivity.this,StopService.class);
        startService(intent);
    }
}
服务相关的代码:

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

public class StopService extends Service {
    private static final String TAG = "StopService";
    public StopService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

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

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

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

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "onRebind: ");
        super.onRebind(intent);
    }

    //开启一个计数线程
    private void onCount(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 1000; ++i){
                    Log.i(TAG, "run: i="+i);
                    if(i == 500){
                        stopSelf();//结束服务
                    }
                }
            }
        }).start();
    }
}

注意服务需要在AndroidManifest.xml中注册

<service
            android:name=".main.service.StopService"
            android:enabled="true"
            android:exported="true">


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值