service的基本用法

本文深入讲解了Android中服务(service)的使用方法,包括创建、启动、停止及绑定服务的流程。通过示例代码展示了如何在MainActivity中控制服务的生命周期,并解释了服务与Activity之间的数据交互方式。

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

service的基本用法:创建,启动和停止,绑定等。
示例代码如下:
(1)activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="开始服务"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:onClick="start"/>
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="停止服务"
    android:onClick="stop"/>\
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/bind"
    android:text="绑定服务"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    android:onClick="bind"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/unbind"
    android:text="解绑服务"
    app:layout_constraintTop_toBottomOf="@+id/button1"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    android:onClick="unBind"/>
</android.support.constraint.ConstraintLayout>

(2) MainActivity.java

public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private MyService.DownloadBinder downloadBinder;

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

@Override
protected void onDestroy() {
    super.onDestroy();

}

public void start(View view){
     Log.i("MainActivity","--启动服务");
     Intent i = new Intent(this,MyService.class);
     startService(i);
}

public void stop(View view){
    Log.i("MainActivity","--停止服务");
    Intent i = new Intent(this,MyService.class);
    stopService(i);
}

//绑定服务的桥梁
private ServiceConnection connection = new ServiceConnection() {
   @Override
   public void onServiceConnected(ComponentName name, IBinder service) {
       downloadBinder = (MyService.DownloadBinder) service;
       downloadBinder.startDownload();
       downloadBinder.getProgress();
   }

   @Override
   public void onServiceDisconnected(ComponentName name) {

   }
 };

public void bind(View view){
    Log.i("MainActivity","--绑定服务");
    Intent bindIntent = new Intent(this,MyService.class);
    bindService(bindIntent,connection,BIND_AUTO_CREATE);    //第三个参数表示,活动和服务绑定后会自动创建服务(如果服务没有创建)
}

public void unBind(View view){
    Log.i("MainActivity","--解绑服务");
    unbindService(connection);
 }
}

(3) MyService.java

public class MyService extends Service {
private DownloadBinder downloadBinder = new DownloadBinder();

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

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

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

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

class DownloadBinder extends Binder {
    public void startDownload(){
        Log.d("Myservice","开始下载");
    }

    public int getProgress(){
        Log.d("Myservice","进度变化");
        return 0;
    }
 }
}

(4) manifest.xml文件中注册service
<service android:name=".MyService"/>
(5)如果不绑定服务,服务就不能实时告诉activity数据的变化。比如下载进度。通过绑定自动创建的服务会执行MyService中的onCreate() , 但是不会执行onStartCommand() 方法。
一个服务创建后都只有一个实例,不管调用多少次startService(), 只需要执行一次stopService()或者 stopSelf() 即可销毁。
任何服务都可以和应用内的任何activity进行绑定,且拿到的都是相同的实例。
如果既调用了startService()又调用了 bindService(),则需要同时调用unbindService()和stopService(),才能进行销毁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值