Android Service初解

Service是什么呢?

他同Activity相比,最大的不同就是他没有专门的Layout展示界面,他默默的工作在App的后台

虽然除了少数几种情况,我们不需要使用Service,但我们也有必要了解一下Service的使用方法

我们知道Activity由于其自有缺陷,如果Activity产生了跳转,那么当前Activity的工作就会被完全停止。

但是有时候我们希望在听歌、打接电话、下载文件的过程中继续别的活动,这时候我们就应该使用Service,不论前端的Activity如何变幻,只要Service没有被停止,Service就会继续他的工作。

Service的工作流程图如下:



使用Service首先需要新建一个继承自Service的类

package com.example.testservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class ServiceTest extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "已经绑定好了", Toast.LENGTH_SHORT).show();
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Toast.makeText(getApplicationContext(), "服务解除", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Toast.makeText(getApplicationContext(), "已经绑定好了", Toast.LENGTH_SHORT).show();
	}

}


接着我们需要在AndroidManifest.xml文件中对Service进行一次注册


<service android:name="ServiceTest"></service>

下面我们来看看调用Service服务的两种方案:

一、startService

Intent startService = new Intent(MainActivity.this,ServiceTest.class);
startService(startService);

二、bindService

Intent startService = new Intent(MainActivity.this,ServiceTest.class);
ServiceConnection serviceConnect = null;
bindService(startService,serviceConnect,Context.BIND_AUTO_CREATE);

这两种方法最大的不同在于 bindService会在APP程序退出时自动解除对于Service的绑定,而startService则需要手动终止服务,所以我们需要根据自己的需要选择合适的方法调用Service



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值