Service的完整解读

今天为大家奉上的是四大组件之一的service服务 

官方给出的解释是A Service is an application component that can performlong-running operations in the background and does not provide a user interface. Anotherapplication component can start a service and it will continue to run in the background even if theuser switches to another application. Additionally, a component can bind to a service tointeract with it and even perform interprocess communication (IPC). For example, a service mighthandle network transactions, play music, perform file I/O, or interact with a content provider, allfrom the background.

服务是一个应用程序组件,可以在后台执行长期运行操作,不提供用户界面,另一个应用程序组件可以启动一个服务,它将继续在后台运行,即使用户切换到另一个应用程序。此外,一个组件可以绑定到一个服务与它交互,甚至执行进程间通信(IPC)。例如,一个服务可能处理网络交易,播放音乐,执行文件I / O,或与内容提供者交互,所有的后台。

通俗一点讲service就是一个没有界面的activity他有自己的生命周期 具有与activity 相同的功能

启动服务有两种形式 一种是startService 另外一种是bindservice 

startService

Once started, a servicecan run in the background indefinitely, even if the component that started it is destroyed. Usually,a started service performs a single operation and does not return a result to the caller.For example, it might download or upload a file over the network. When the operation is done, theservice should stop itself.

一旦开始,一个服务可以无限期地在后台运行,即使组件开始被摧毁。通常,开始服务执行一个操作,不向调用者返回一个结果。例如,它可能通过网络下载或上传文件。操作完成后,服务应该停止本身。

可以通过调用stopservice();或者stopself();来停止服务。

starService 中onstarcommand()方法返回值有四个分别是

	START_STICKY_COMPATIBILITY,(不常用)
	START_STICKY,当服务杀死时会自动重启 但需要几秒钟的时间
	START_NOT_STICKY,当服务杀死时不会重新启动
	START_REDELIVER_INTENT 会重新发送数据 intent中传递的数据会更新 

bindservice

A bound service offers a client-serverinterface that allows components to interact with the service, send requests, get results, and evendo so across processes with interprocess communication (IPC). A bound service runs only as long asanother application component is bound to it. Multiple components can bind to the service at once,but when all of them unbind, the service is destroyed

绑定服务提供了一个客户端-服务器接口,允许组件与服务交互,发送请求,得到结果,甚至跨进程与进程间通信(IPC)。

绑定服务只要运行另一个应用程序组件绑定到它。多个组件可以绑定到服务,但是当他们解开,服务被摧毁 具有同生共死的感觉。 当服务执行完毕该服务直接被销毁

当通过bindservice绑定一个服务时  必须实现OnBind()方法 会返回一个Ibinder对象OnBind()方法必须实现 如果不想返回数据  可以return null 

使用的时候必须在清单文件中对服务进行注册  <serviceandroid:name=".ExampleService"/> 

服务的生命周期

    

使服务前台运行  starforeground ()

private static final Class<?>[] mSetForegroundSignature = new Class[] {
    boolean.class};
private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mSetForeground;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mSetForegroundArgs = new Object[1];
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

void invokeMethod(Method method, Object[] args) {
    try {
        method.invoke(this, args);
    } catch (InvocationTargetException e) {
        // Should not happen.
        Log.w("ApiDemos", "Unable to invoke method", e);
    } catch (IllegalAccessException e) {
        // Should not happen.
        Log.w("ApiDemos", "Unable to invoke method", e);
    }
}

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        invokeMethod(mStartForeground, mStartForegroundArgs);
        return;
    }

    // Fall back on the old API.
    mSetForegroundArgs[0] = Boolean.TRUE;
    invokeMethod(mSetForeground, mSetForegroundArgs);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        invokeMethod(mStopForeground, mStopForegroundArgs);
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    mSetForegroundArgs[0] = Boolean.FALSE;
    invokeMethod(mSetForeground, mSetForegroundArgs);
}

@Override
public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
        return;
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
    try {
        mSetForeground = getClass().getMethod("setForeground",
                mSetForegroundSignature);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(
                "OS doesn't have Service.startForeground OR Service.setForeground!");
    }
}

@Override
public void onDestroy() {
    handleDestroy();
    // Make sure our notification is gone.
    stopForegroundCompat(R.string.foreground_service_started);
}
Laziness
The quality that makes you go to great effort to reduce overall energy expenditure. 
It makes you write labor-saving programs that other people will find useful,
and document what you wrote so you don't have to answer so many questions about it.
Hence, the first great virtue of a programmer, Also hence, this book.
懒惰:
是这样一种品质,它使得你花大力气去避免消耗过多的精力。它敦促你写出节省体力的程序,
同时别人也能利用它们。为此你会写出完善的文档,以免别人问你太多问题。
Impatience
The anger you feel when the computer is being lazy. 
This makes you write programs that don't just react to your needs, 
but actually anticipate them. Or at least pretend to. Hence, the second great virtue of a programmer.
急躁:
是这样一种愤怒——当你发现计算机懒洋洋地不给出结果。于是你写出更优秀的代码,能尽快真正的解决问题。至少看上去是这样。
Hubris
Excessive pride, the sort of thing Zeus zaps you for.
Also the quality that makes you write (and maintain) programs that
other people won't want to say bad things about. Hence, the third great virtue of a programmer.
傲慢:
极度的自信,使你有信心写出(或维护)别人挑不出毛病的程序。







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值