Android-Service

来源:互联网 发布:加盟农村淘宝要多少钱 编辑:程序博客网 时间:2024/06/08 14:48

Android提供了两种Service的方式 startService 和bindService

区别:bindService和组件关联 如果对应的组件关闭 Service destroy

绑定服务调用的函数是bindService 启动服务调用的是onStartcommand  onCreate方法只在创建的时候调用 如果服务正在运行 onCreate不会调用

onStartCommand 有返回值 

START_NOT_STICKY  不会重新创建
START_STICKY  总是重新创建 过一段时间后 由系统决定
START_REDELIVER_INTENT  适用于下载 马上恢复


声明一个Servic

<manifest ... >  ...  <application ... >      <service android:name=".ExampleService" />      ...  </application></manifest>
以后AIDL中有一个很重要的属性那就是exported 如果为true才能被其他应用程序调用


1.StartService(启动服务)

这个比较简单 继承Service 或者intentService(这个基本没人用 Android为了方便我们封装了一个Service的子类给我们使用) 然后重写里面的方法

启动服务

Intent intent = new Intent(this, HelloService.class);startService(intent);

这样启动一般是没有结果回传的 但是官网好像说可以通过为一个Broadcast创建PendingIntent 然后用intent传过去 

也就是Service想和组件通信 就必须用Broadcast


启动服务 然后可以发送Toast Notifications orStatus Bar Notifications

这个两个到底是什么鬼呢?就是说你可以通过Toast和Notification来提示用户 说服务启动了 


可以声明一个前台进程 然后你的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);

2.绑定服务bindService

这个直接上来就是AIDL

服务器:1)定义aidl接口 2)然后定义Service 3)返回这个aidl

  1. Create the .aidl file

    This file defines the programming interface with method signatures.

  2. Implement the interface

    The Android SDK tools generate an interface in the Java programming language, based on your.aidl file. This interface has an inner abstract class namedStub that extendsBinder and implements methods from your AIDL interface. You must extend theStub class and implement the methods.

  3. Expose the interface to clients

    Implement a Service and overrideonBind() to return your implementation of theStubclass.


哈哈 终于把今天那个问题解决了都不知道是怎么回事





0 0
原创粉丝点击