程序员

Android 开发学习笔记(二)—— Service

2018-04-08  本文已影响0人  isletn

Service 能在后台长期运行而不提供用户界面。由其他组件启动,且可以做到不依赖当前应用运行。组件能绑定 Service,进行交互、执行进程间通信。

Tips
  1. 一个Service如果被调用startService()启动多次,onCreate()方法也只执行一次
  2. 对于启动服务,除onStartCommand()方法外,其他生命周期方法只会被调用一次
  3. onStartCommand()调用次数 == startService()调用次数
  4. 在服务中启动Activity必须加下面这行代码
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Service
Service.png
Service 生命周期
service_lifecycle.png
Service 的两种形式:

Service 既可以是启动服务,也可以与其他组件进行绑定。这取决于你是否实现Service的回调方法:onStartCommand()(允许组件启动服务)、onBind()(允许绑定服务)。

创建启动 Service:

应用场景:假设某Activity 需要上传数据到服务器,则可以启动一个协同服务,通过startService()传递一个Intent ,为该服务提供上传的数据。服务通过onStartCommand()接收Intent,进行上传操作。

PS:需要注意的是,默认情况,Service 运行在主线程,因此,如果有耗时操作交给 Service 应该在 Service中启动新的子线程执行该操作。

  1. 首先,与其他 Android 组件一样,需要在 AndroidManifest.xml 文件里面声明你要用的服务;
...
<application>
  <service android:name="xxxx" />
</application>
...
  1. 使用扩展类创建 Service
/**
  *  使用 IntentService 只需要提供一个构造函数跟实现onHandleIntent()方法就行了
  */
public class HelloIntentService extends IntentService {

  public HelloIntentService() {
      super("HelloIntentService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
      // ...
  }
}
  1. 启动 Service
/**
  *  Intent可以指定要启动的服务,通过将Intent传给 startService(),
  *  从Activity或其他组件中启动Service
  */
Intent intent = new Intent(this, HelloService.class);
startService(intent);
  1. 停止 Service
在前台运行服务

应用场景:应该将通过服务播放音乐的音乐播放器设置为在前台运行,这是因为用户明确意识到其操作。 状态栏中的通知可能表示正在播放的歌曲,并允许用户启动 Activity 来与音乐播放器进行交互。

前台服务特点:
  1. 在内存不足时,系统也不会考虑将其终止
  2. 前台服务必须为状态栏提供通知,放在“正在进行”标题下方,这意味着除非服务停止或从前台移除,否则不能清除通知。
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);
// 第一个参数不能为 0 
startForeground(ONGOING_NOTIFICATION_ID, notification);
// true 或 false 代表是否也移除状态栏通知
stopForeground(true);

参考自官方文档
https://developer.android.com/guide/components/services.html?hl=zh-cn

上一篇 下一篇

猜你喜欢

热点阅读