Android Service的基本用法

Service

1.什么是Service,Service的作用

Service是Android四大组件之一,顾名思义Service就是运行在后台的一种服务,很少使用和用户交互,因此没有可是画界面,但Service在一个程序中起着至关重要的作用。Service一般在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务。必要的时候我们甚至可以在程序退出的情况下,让Service在后台继续保持运行状态。

2.Service的基本用法

创建一个Service类比较简单,只要定一个类继承Service类,是先其生命周期中的方法就可以了,注意一个定义好的Service必须在AndroidManifest.xml配置文件中通过<service>元素声明才能使用.

子标签的语法:

<service android:enabled=[“true”|”false”]
android:exported=[“true”|”false”]
android:icon=”drawable resource”
android:label=”string resource”
android:name=”string” 
android:permission=”string”
android:process=”string”>
....
</service>

  • android:enabled=[“true”|”false”]

表示服务能否被实例化,true为可以,false表示不可以,默认为true<application>标签也有自己的enabled属性,用于包括服务的全部应用程序组件.<application><service>两个enabled的属性都为true才能让服务可用,任何一个是false,服务被禁用并且不能实例化.

  • android:exported=[“true”|”false”]

其他应用程序组件能否调用服务或者与其交互,true为可以,false反之,当该值是false,只有同一个应用程序的组件或者具有相同用户ID的应用程序才可以启动或者绑定到服务.默认值依赖于文件是否包含Intent过滤器.若没有过滤器,说明服务仅能通过精确类名调用,这意味着服务仅用于应用程序内部(因为其他程序不可能知道类名).此时,默认值是false;若存在至少一个过滤器,暗示服务可以用于外部,因此默认值是true.

该属性不是限制其他应用程序使用服务的唯一方式.还可以使用permission属性来限制外部实体与程序交互.

  • android:icon=”drawable resource”

代表服务图标

  • android:label=”string resource”

显示给用户的服务名称 没有的话用应用程序标签替代

  • android:name=”string” 

实现服务的Service子类的名称,是一个完整的类名或者用mainfest标签中定义的报名

  • android:permission=”string”

实体必须包含的权限名称,以便启动或者绑定到服务

  • android:process=”string”

服务运行的进程名称.通常,应用程序的全部组件运行在应用程序创建的默认进程.进程名称与应用包的程序包名相同<application>标签的process属性能为全部组件设置一个相同的默认值.但是组件能用自己的process属性重写默认值,从而允许应用程序跨越多个进程.如果分配给该属性的名称以冒号开头,仅属于应用程序的新进程会在需要时创建,服务能在该进程中运行;如果进程名称以小写字母开头,服务会运行在以此为名的全局进程,但需要提供相应的权限.这允许不同应用程序组件共享进程,减少资源的使用.

public class MyService extends Service{
	@Override
	public IBinder onBind(Intent intent){
		return null;
	}
}
一个最简单的Service只需要实现onBind()方法就可以实现,onBind()方法是Service中唯一一个抽象的方法,必须要在子类中实现。

当然为了Service有自己的声明周期,下面方法中定义了一系列和Service声明周期相关的方法:

  • onBind()是Service中唯一一个抽象的方法,必须要在子类中实现
  • onCreate()服务创建时候调用
  •  onStartCommand((Intent intent, int flags,int startId) 每次在服务启动时调用
  •  onDestroy()服务销毁的时候调用
public class MyService extends Service {

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(msg, "onCreate() executed");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(msg, "onStartCommand() executed");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(msg, "onDestroy() executed");
	}

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

}

之后我们设置主布局文件

<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:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="启动服务" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭服务" />
</LinearLayout>

在当中添加两个按钮用来启动和关闭服务

启动服务是由其他组件调用startService()方法启动的,这会调用服务的onStartCommand()方法被调用.

当服务是started状态时,其生命周期与他启动他的组件无关,并且可以在后台无限期运行,即使启动服务的组件已经被销毁.因此服务需要在完成任务后调用stopSelf()方法停止,或者其他组件调用stopService()方法停止.

应用程序组件能通过调用startService()方法和传递Intent对象来启动服务,Intent对象中指定了服务并且包含服务需要使用的全部数据.服务使用onStartCommand()方法来接受Intent进行联入网络执行数据库等操作.失误完成时,服务停止自身并销毁.

Android提供了两个类供开发人员继承以创建启动服务

Service:这是所有服务的基类.当继承该类是,创建新线程来执行服务的全部工作是非常重要的.因此服务默认使用应用程序的主线程,这可能降低应用程序Activity的运行性能.

Intent:这是Service类的子类,他每次使用一个工作线程来处理全部的启动请求.在不需要同时处理多个请求时,这是最佳选择.开发人员仅需要实现onHandleIntent()方法,该方法接收每次启动请求的Intent以便完成后台任务.

IntentService可完成如下任务:

创建区别于应用程序主线程默认工作线程来执行发送到onStartCommand()方法的全部Intent.

创建工作队列,每次传递到一个IntentonHandleIntent()方法实现,这样就不必担心多线程.

所有启动请求处理完毕后停止服务,这样就不必调用stopSelf()方法.

提供onBind()方法默认实现,其返回值是 null.
提供onStartCommand()方法的默认实现方法,它先发送到Intent到工作队列,然后到onHandleIntent()方法实现

如上所示,我们使用时值需要实现onHandleIntent方法()来完成客户端提供的任务.犹豫IntentService类没有提供空参数的构造方法,因此需要一个构造方法.

public class MyIntentService extends IntentService {
 
public MyIntentService() {
super("MyIntentService");
}
 
@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
}
 
}


如果想要重写其他回调方法需要调用父类来进行实现

当启动一个Service的时候,会调用该Service中的onCreate()onStartCommand()方法,

当再次点击启动Service的按钮时只会执行onStartCommand(),事实说明onCreate()方法只有在第一次调用时候才会执行生成.当点击停止Service按钮时执行onDestroy()方法停止服务.

ServiceActivity通信

我们通过使用onBind()方法来和Activity建立关联.

 
public class MyService extends Service {
public final static int NOTIFICATION_ID=1;
public static final int MAX_PROGRESS=100;
private int progress=0;
private Handler handler;
private boolean flag=true;
private DownloadBinder mBinder = new DownloadBinder();
 
class DownloadBinder extends Binder {
public void startDownload() {
new Thread(new Runnable() {
@Override
public void run() {
while(progress<MAX_PROGRESS&&flag){
Message m = handler.obtainMessage();
m.what = 0x101;
progress+=5;
handler.sendMessage(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
 
public int getProgress() {
return progress;
}
 
}
 
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
 
@Override
public void onCreate() {
super.onCreate();
final Notification notification = new Notification(R.drawable.ic_launcher,
"Notification", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, "Notification", "download",
pendingIntent);
RemoteViews remoteviews=new RemoteViews(getPackageName(), R.layout.content_view);
notification.contentView=remoteviews;
startForeground(NOTIFICATION_ID, notification);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
remoteviews.setProgressBar(R.id.content_view_progress, MAX_PROGRESS,progress, false);
manager.notify(NOTIFICATION_ID, notification);
handler = new Handler() {
public void handleMessage(Message msg) {
int temp = 0;
if (msg.what == 0x101) {
RemoteViews remoteviews=new RemoteViews(getPackageName(), R.layout.content_view);
notification.contentView=remoteviews;
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
remoteviews.setTextViewText(R.id.content_view_text1, progress+"%");
remoteviews.setProgressBar(R.id.content_view_progress, MAX_PROGRESS,progress, false);
manager.notify(NOTIFICATION_ID, notification);
}
super.handleMessage(msg);
}
};
}
 
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {  
        @Override  
        public void run() {
while(progress<MAX_PROGRESS&&flag){
Message m = handler.obtainMessage();
m.what = 0x101;
progress+=5;
handler.sendMessage(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}  
    }).start();
return super.onStartCommand(intent, flags, startId);
}
 
@Override
public void onDestroy() {
flag=false;
super.onDestroy();
}
 
}


这里我们新增了一个DownloadBinder类继承自Binder类,然后在DownloadBinder中添加了一个startDownload()方法用于在后台执行下载任务,这里我只是模拟了一个下载的进度条变化刷新。

 

public class MainActivity extends Activity implements OnClickListener {
 
private Button startService;
 
private Button stopService;
 
private Button bindService;
 
private Button unbindService;
 
 
private MyService.DownloadBinder downloadBinder;
 
private ServiceConnection connection = new ServiceConnection() {
 
@Override
public void onServiceDisconnected(ComponentName name) {
}
 
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start_service);
stopService = (Button) findViewById(R.id.stop_service);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
 
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
default:
break;
}
}
 
}


首先我创建了一个ServiceConnection的匿名类,重写了onServiceConnected()方法和onServiceDisconnected()方法,这两个方法分别会在ActivityService建立关联和解除关联的时候调用.onServiceConnected()方法中,我们又通过向下转型得到了Binder的实例,有了实例,ActivityService之间的关系就变得非常紧密了.然后我们就可以在Activity调用MyBinder中的public方法,实现了Activityservice之间的通信.

这里可以看出我的代码逻辑我们构建出了一个Intent对象,然后调用bindService()方法将ActivityService进行绑定.bindService()方法接收三个参数,第一个参数是Intent对象,第二个参数是前面创建出的ServiceConnection的实例,第三个参数是一个标志位,这里传入BIND_AUTO_CREATE表示在ActivityService建立关联后自动创建Service,这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行。

 

销毁Service

之前已经说过了销毁Service最简单的方法点击Start Service按钮启动Service,再点击Stop Service按钮停止Service,这样MyService就被销毁了,但如果我们点击的是bind_service,由于在绑定Service的时候指定的标志位是BIND_AUTO_CREATE,说明点击bind_service按钮的时候Service也会被创建,所以我们销毁Service的时候只要讲Activityservice解绑就可以了。

如果我们既点击了Start Service按钮,又点击了bind_service按钮,必需要将两个按钮都点击一下,Service才会被销毁。也就是说,点击Stop Service按钮只会让Service停止,点击unbind_service按钮只会让ServiceActivity解除关联,一个Service必须要在既没有和任何Activity关联又处理停止状态的时候才会被销毁。

 

=================================注意===================================

1、你应当知道在调用 bindService 绑定到Service的时候,你就应当保证在某处调用 unbindService 解除绑定(尽管 Activity 被 finish 的时候绑定会自动解除,并且Service会自动停止);

 

2、你应当注意 使用 startService 启动服务之后,一定要使用 stopService停止服务,不管你是否使用bindService; 

 

3、同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindServicestopService同时调用,才能终止 Service,不管 startService 与 bindService 的调用顺序,如果先调用 unbindService 此时服务不会自动终止,再调用 stopService 之后服务才会停止,如果先调用 stopService 此时服务也不会终止,而再调用 unbindService 或者 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候)之后服务才会自动停止;

 

4、当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 Activity 如果会自动旋转的话,旋转其实是 Activity 的重新创建,因此旋转之前的使用 bindService 建立的连接便会断开(Context 不存在了),对应服务的生命周期与上述相同。

 

 

1). Local 服务绑定:Local 服务的绑定较简单,首先在 Service 中我们需要实现 Service 的抽象方法 onBind,并返回一个实现 IBinder 接口的对象。

 Local Service 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。

 

bindService有三个参数,第一个是用于区分 Service Intent 与 startService 中的 Intent 一致,第二个是实现了 ServiceConnection 接口的对象,最后一个是 flag 标志位。有两个flagBIND_DEBUG_UNBIND 与 BIND_AUTO_CREATE,前者用于调试(详细内容可以查看javadoc 上面描述的很清楚),后者默认使用。unbindService 解除绑定,参数则为之前创建的 ServiceConnection 接口对象。另外,多次调用 unbindService 来释放相同的连接会抛出异常,因此我创建了一个 boolean 变量来判断是否 unbindService 已经被调用过。

 

========================================================================

1Service.onBind如果返回null,则调用 bindService 会启动 Service,但不会连接上 Service,因此 ServiceConnection.onServiceConnected 不会被调用,但你任然需要使用 unbindService 函数断开它,这样 Service 才会停止。

 

 

 

在什么情况下使用 startService 或 bindService 或 同时使用startService 和 bindService

 

如果你只是想要启动一个后台服务长期进行某项任务那么使用 startService 便可以了。如果你想要与正在运行的 Service 取得联系,那么有两种方法,一种是使用 broadcast ,另外是使用 bindService ,前者的缺点是如果交流较为频繁,容易造成性能上的问题,并且 BroadcastReceiver 本身执行代码的时间是很短的(也许执行到一半,后面的代码便不会执行),而后者则没有这些问题,因此我们肯定选择使用 bindService(这个时候你便同时在使用 startService 和 bindService 了,这在 Activity 中更新 Service 的某些运行状态是相当有用的)。另外如果你的服务只是公开一个远程接口,供连接上的客服端(android 的 Service C/S架构)远程调用执行方法。这个时候你可以不让服务一开始就运行,而只用 bindService ,这样在第一次 bindService 的时候才会创建服务的实例运行它,这会节约很多系统资源,特别是如果你的服务是Remote Service,那么该效果会越明显(当然在 Service 创建的时候会花去一定时间,你应当注意到这点)。

ServiceThread

Activity很难对Thread进行控制,当Activity被销毁之后,就没有任何其它的办法可以再重新获取到之前创建的子线程的实例。而且在一个Activity中创建的子线程,另一个Activity无法对其进行操作。但是Service就不同了,所有的Activity都可以与Service进行关联,然后可以很方便地操作其中的方法,即使Activity被销毁了,之后只要重新与Service建立关联,就又能够获取到原有的ServiceBinder的实例。因此,使用Service来处理后台任务,Activity就可以放心地finish,完全不需要担心无法对后台任务进行控制的情况。

 

service与延迟任务

Service通常也会用来实现延迟任务

延迟任务有两种实现方式一个是使用Java API里提供的Timer 

但是不适合需要长期执行在后台的任务,手机长时间不操作CPU进入睡眠,会导致Timer任务无法正常运行。所以我们通常情况下是用Alarm

Alarm在这种情况也能唤醒CPU

Alarm机制的用法接住了AlarmManager类来实现.这个类和NotificationManager类似

调用ContextgetSystemService()方法来获取实例,只是传入参数是Context.AlARM_SERVICE

AlarmManager manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);


调用set方法可以设置定时任务(延迟10秒钟)

long triggerAtTime=SystemClock.elapsedRealtime()+10*1000;
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);


三个参数

AlarmManager.ELAPSED_REALTIME

第一个参数表示让定时触发任务的时间从系统开机开始算起,但是并不会唤醒CPU

AlarmManager.ELAPSED_REALTIME_WAKEUP

第一个参数表示让定时触发任务的时间从系统开机开始算起,但是会唤醒CPU

RTC

表示从1970110点开始算起,但是不后悔唤醒CPU

RTC_WAKEUP

.....

SystemClock.elapsedRealtime()方法可以获取到系统开机到现在经历的毫秒数

System.currentTimeMillis()1970。。。。到现在经历的毫秒数

第二个参数

定时任务触发的时间,以毫秒为单位,第一个参数到延迟的时间

第三个参数是一个PendingIntent.




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值