android 四大组件之Service两种调用方式使用详解

本文详细介绍了Android中的Service组件,包括Service的两种启动方式——startService()和bindService()。startService()用于执行一次性任务,而bindService()则允许与服务进行绑定并交互。文中通过代码示例展示了如何创建Service,重写关键生命周期方法,并通过Activity调用Service。此外,还解释了ServiceConnection接口在绑定服务过程中的作用。

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

一 概述

Service服务作为android中的四大组件之一,其作用和重要性也不用多说。service用于长期在后台处理任务,与Activity相反Service没有可见的用户界面,但Service能长时间在后台运行,Service是一个具有较长生命周期但没有用户界面的组件,和Activity一样的是Service也有自己的生命周期。下图是它的生命周期的过程。


service有2种基本的启动方式:
startService():使用这种方式,来进行单一的任务,不需要返回结果给调用者
bindService():使用这种方式,能和调用者进行绑定,是两者有关联。

二 Service的创建,并在AndroidManifest文件中进行配置。

创建自己的Service需继承android提供的Service类,并更具功能实现其中的方法。查看Service类中的方法。


下面对几个重要的方法进行讲解:

onCreate();当服务被创建时调用,只调用一次。
onStartCommand();它与startService()对应,当服务启动后调用。如果你重写了该方法,你就有责任自己去
当任务结束以后,调用stopSelf()或者stopService()来停止服务。如果你是绑定的服务,就不需重写该方法了。
onBind();它与bindService()对应,通过返回IBinder,来与service交流。如果你并不像绑定它,就直接返回null
onDestroy();当服务不再被使用时需要销毁时调用,你应该在这里用来停止线程,注销监听器,广播。
如果一个组件如activity使用的是 startService()来启动服务的话,就会触发 onStartCommand(),然后服务就会一直运行,直到任务结束;服务的停止需要
手动控制:在启动服务的组件中调用 stopService()或者在服务本类中调用stopSelf() 
如果一个组件使用的是bindService()来启动服务的话,该服务就会运行,直到组件不约束它。
三 代码示例

1. 创建自己的Service,并重写onStartCommand(对应startService启动方式)和onBind(对应bindService启动方式),实现每个一秒钟打印一些内容的功能。

package com.example.servicedemo;

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


/**
 * @author ZMC
 *创建自定义的service
 */
public class FirstService extends Service {
	
	private MyBinder myBinder = new MyBinder();
	//创建一个Binder类
	class MyBinder extends Binder{
		public void startJob(){
			new Thread(){
				public void run() {
					for (int i = 0; i < 51; i++) {
						System.out.println("startJob");
						try {
							sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				};
			}.start();
		}
	}
	//该方法给调用者返回一个IBinder对象,是和调用者经行数据交换的关键
	//该方法和bindService对应
	@Override
	public IBinder onBind(Intent intent) {
		Log.i("test", "onBind");
		return myBinder;
	}

	@Override
	public void onCreate() {
		System.out.println("Oncreate");
		super.onCreate();
	}

	private boolean flag = true;
	private int count = 1;
	//该方法是和startService对应的
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		new Thread() {
			@Override
			public void run() {
				while (flag) {
					System.out.println("count:" + count);
					count++;
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (count > 100) {
						flag = false;
					}
				}
			}
		}.start();
		Log.i("test","onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}
	//销毁方法
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		System.out.println("ondestory");
		super.onDestroy();
	}
}
说明:

onStartCommand方法是对应startService启动方式的方法,使用startService方式启动只需要将要实现的功能写在onStartCommand即可。

onBind方法,该方法给调用者返回一个IBinder对象,是和调用者经行数据交换的关键,该方法和bindService对应,其中IBinder对象一般是自己集成Binder类实现的,上面例子中是MyBinder,其中定义了实现功能的方法,这样在当调用者得到该对象时,就能通过该对象中的方法实现相对应的功能了。
2. 布局文件

定义了四个按钮


通过四个按钮实现启动服务,暂停服务。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.servicedemo.MainActivity" >

    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="start"
        
        android:text="启动服务"/>
     <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="stop"
        android:text="停用服务"/>
     
     <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="bind"
        
        android:text="绑定Activity"/>
     <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="unbind"
        android:text="解绑Activity"/>
     

</LinearLayout>
3. 创建调用者

这里我用了Activity作为服务的调用者,并通过一个ServiceConnection接口的实现类来实现和Service的绑定。

package com.example.servicedemo;

import com.example.servicedemo.FirstService.MyBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainActivity extends Activity {
	private Intent intent = null;
	private MyBinder myBinder;
	ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			myBinder = (MyBinder)service;
			myBinder.startJob();
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	public void start(View view){
		/*
		 * 这样开启的服务是不受activity生命周期的影响的
		 * 没有办法和其他的组件进行数据交互 它是一个单独的个体
		 * */
		
		intent = new Intent(this,FirstService.class);
		startService(intent);
	}
	
	public void stop(View view){
		if (intent!=null) {
			stopService(intent);

		}
	}
	
	public void bind(View view){
		intent = new Intent(this,FirstService.class);
		bindService(intent, serviceConnection, BIND_AUTO_CREATE);
	}
	
	public void unbind(View view){
		unbindService(serviceConnection);
	}
	
}
说明:

start和stop对应的是启动服务和停用服务两个按钮的事件,同时对应为startService的启动方式。

bind和unbind对应的是绑定Activity和解绑Activity两个按钮的事件,对应bindService方式启动的。

重点:ServiceConnection该接口是一个调用者和Service关联的接口,通过该接口的实现类即可实现两者的交互。上面的代码示例中通过匿名内部类来实现的,其中实现onServiceConnected方法,该方法就是用来接收Service中onBind返回的IBinder对象的。
四 结果:

点击启动服务按钮调用onCreate和onStartCommand方法


点击停用服务调用调用ondestory方法


点击绑定按钮调用onCreate和onBind方法


点击解绑按钮调用ondestory方法


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值