Service的简单使用

本文详细介绍了在Android应用中如何通过代码实现服务的启动与停止操作,包括服务类的创建、生命周期方法的使用及在Activity中触发服务的方法。

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

package demo.lxiangjian.com.android_service;

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

public class MainActivity extends AppCompatActivity {

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

    //开启服务
    public void start(View view) {
        Intent intent = new Intent(MainActivity.this,MyService.class);
        intent.putExtra("data","key");
        //启动服务
        startService(intent);
    }
    //停止服务
    public void stop(View view) {
        Intent intent = new Intent(MainActivity.this,MyService.class);
        stopService(intent);
    }
}


<pre name="code" class="java">package demo.lxiangjian.com.android_service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("TAG", "-------onBind-----------");
        return null;
    }

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

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
>
    <Button
        android:onClick="start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动服务" />

    <Button
        android:onClick="stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务" />
</LinearLayout>


在清单文件注册服务:
 </activity><service android:name=".MyService"></service>

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

奋斗年轻人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值