Service

一。Serivce的启动方式分两种

1.startService。用这种方式启动的话,负责启动这个service的Activity或者其他组件即使被销毁了,Service也会继续在后台运行,必须得Serivce自己做完任务区去调用stopSelf或者stopService去停止这个Serice。这种方式是Start方式

2.bindService。这种方式要组件去调用BindService去绑定一个Service,这种方式Service的生命周期是知道所有绑定这个service的组件unbind之后才会销毁。这种方式称之为 Bound

startService调用后会自动调用startCommand,你需要做的工作可以在这里写,例如启动新线程去执行任务之类的。

bindService之后会调用Onbind函数,功能同上,需要自己去重写,还有就是通信就是通过这个onbind函数返回的IBinder

以上两种方式可以一起使用,不是一定要分开。。

二.实现Service需要重写的方法

一般来说,实现Service,实现以下几个方法就好:

onStartCommand()

onBind()

onCreate()

onDestroy()

函数名字还是非常清楚的,具体作用就不说了。

三.在manifest里面加入Service

跟Activity一样,要使用你自己写的Service,必须得在manifest里面注册

例如

<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>

Service的名字一旦确定,就不要更改了,因为其他地方会利用这个名字去访问Service,

值得注意的是,一个service可以被其他应用程序去访问,如果你不想被其他应用程序访问,就在文件里面加入属性android:exported,然后设置为False。

四.实现Service的两种方法

实现Service主要有两种方式:

1.Service

要重写几个函数,而且一般工程来说,都要自己创建新线程来执行任务,这些工作都要我们自己去编写来做。

代码如下:

public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler; // Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
} @Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start(); // Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); // For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg); // If we get killed, after returning from here, restart
return START_STICKY;
} @Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
} @Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}

2.IntentService

如果只是启动一个线程做一个单独任务,这个是首选,系统帮你实现好了几个必须重写的函数,你只需要做的是事情就是实现一个函数就行:onHandleIntent(intent) 参数是startCommand那里传过来的。

看代码:

public class HelloIntentService extends IntentService {

  /**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
} /**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}

注意,startCommand返回的值是有用的,决定这个service被系统干掉后要不要重新启动,这个值有三个枚举START_NOT_STICKYSTART_STICKYSTART_REDELIVER_INTENT

五.通过intent来开启Service

启动Service就是创建一个intent对象,参数传进去需要启动的Service名称,就可以啦,调用startService啦,

如果需要Service传回来一些消息,可以 用PendingIntent,然后传给startService用的intent,然后可以用getBroadcast来得到消息。

六.startForeground()来让service在前端显示

类似播放器一样,你想通知栏里面看到在放什么歌曲,还有点击放下一首时,需要调用startForeground()让service运行在前端

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

具体Service的其他方面可以去看下官方文档

android 笔记(Service)的更多相关文章

  1. Android笔记二十七.Service组件入门(一).什么是Service?

    转载请表明出处:http://blog.csdn.net/u012637501(嵌入式_小J的天空) 一.Service 1.Service简单介绍     Service为Android四大组件之中 ...

  2. Android 学习笔记 Service服务与远程通信...(AIDL)

    PS:这一章节看的我有几分迷茫,不是很容易理解...不过还好总算是明白了一大半了...基本的迷惑是解决了... 学习内容: 1.跨应用启动服务... 2.跨应用绑定服务... 3.跨应用实现通信... ...

  3. Android 学习笔记 Service

    PS:前几篇的内容光是上代码了,也没有细细的讲解..感觉这样写很不好..因此还是多一些讲解吧... 学习内容: 1.了解Service... 2.Service的启动与停止.. 3.绑定与取消绑定Se ...

  4. android笔记:Service

    服务:在后台运行,没有界面的组件. 服务生命周期如下: 两种启动方式: 1.startService(): onCreate()-->onStartCommand()-->onDestro ...

  5. Android笔记三十四.Service综合实例二

    综合实例2:client訪问远程Service服务 实现:通过一个button来获取远程Service的状态,并显示在两个文本框中. 思路:如果A应用须要与B应用进行通信,调用B应用中的getName ...

  6. Android笔记(五十九)Android总结:四大组件——Service篇

    什么是服务? 服务(service)是Android中实现程序后台运行的解决方案,适用于去执行那些不需要和用户交互并且还需要长期运行的任务.服务的运行不依赖于任何用户界面. 服务运行在主线程中,所以在 ...

  7. Android笔记(十七) Android中的Service

    定义和用途 Service是Android的四大组件之一,一直在后台运行,没有用户界面.Service组件通常用于为其他组件提供后台服务或者监控其他组件的运行状态,例如播放音乐.记录地理位置,监听用户 ...

  8. android服务Service(上)- IntentService

    Android学习笔记(五一):服务Service(上)- IntentService 对于需要长期运行,例如播放音乐.长期和服务器的连接,即使已不是屏幕当前的activity仍需要运行的情况,采用服 ...

  9. Android:Service

    Android Service: http://www.apkbus.com/android-15649-1-1.html android service 的各种用法(IPC.AIDL): http: ...

  10. android 远程Service以及AIDL的跨进程通信

    在Android中,Service是运行在主线程中的,如果在Service中处理一些耗时的操作,就会导致程序出现ANR. 但如果将本地的Service转换成一个远程的Service,就不会出现这样的问 ...

随机推荐

  1. matplotlib绘图股票走势图实践

    导入模块 import pandas as pdimport numpy as npfrom pandas import Series,DataFrameimport matplotlib.pyplo ...

  2. C语言中sizeof的用法

    今天同学问我sizeof可不可以计算结构体的大小,我竟然忘了C语言还有sizeof这个函数,我是多久没有写程序了啊!!!惭愧,上研究生后写嵌入式方面的程序就特别少了,看来以后还要经常来练练手才行.现在 ...

  3. python 监控日志

    #需求: #1.每分钟监控服务器日志,ip请求超过200次的,加入黑名单 #1.读文件,获取到每行的内容 open readlines # 178.210.90.90 - - [04/Jun/2017 ...

  4. Linux网络配置指令

    版权声明:本文为博主原创文章,未经博主允许不得转载. 原文地址: https://www.cnblogs.com/poterliu/p/6686799.html 重启网卡service network ...

  5. nginx静态资源web服务

    静态资源:非服务器动态运行生成的文件 浏览器端渲染:html ,css,js 图片:jpeg,gif,png 视频:flv ,mpeg 文件:txt,等任意下载文件 静态资源服务场景:CDN 文件读取 ...

  6. Hessian知识学习总结(二)——Hessian的helloworld

    一.下载Hessian 可在hessian官网http://hessian.caucho.com/ 或者http://download.csdn.net/detail/wodediqizhang/95 ...

  7. 汇编语言 Part 2——寄存器

    处理器操作主要涉及处理数据.这些数据可以存储在内存中并从中访问.但是,读取数据并将其存储到内存中会减慢处理器的速度,因为它涉及将数据请求通过控制总线发送到内存存储单元并通过同一通道获取数据的复杂过程. ...

  8. Linux学习-逻辑滚动条管理员 (Logical Volume Manager)

    LVM 可以整合多个实体 partition 在一起, 让这些 partitions 看起来就像是一个磁盘一样!而且,还可以在未来新增或移除其他的实 体 partition 到这个 LVM 管理的磁盘 ...

  9. BZOJ 2465: [中山市选2009]小球

    难度在于读题 #include<cstdio> #include<algorithm> using namespace std; int a[1000005]; struct ...

  10. JS实现——计算两日期之差

    在网上找了个js实现的,根据相差天数计算日期和根据两个日期计算相差多少天的示例和代码: 根据相差天数计算日期: 距离: 年 月 日 相差: 天 (输入负数则往前计算) 日期是:   根据日期计算相差天 ...