一、Service(服务)
Service是Android程序中四大基础组件之一,它和Activity一样都是Context的子类,区别在于它没有UI界面,是在后台运行的组件。
public abstract class Service extends ContextWrapper implements ComponentCallbacks java.lang.Object ↳ android.content.Context ↳ android.content.ContextWrapper ↳ android.app.Service
二、Service启动方法+相应的生命周期
Service的生命周期并不是固定的,而是要看启动Service的方式。
而启动Service的方式又分为两种startService和bindService
1、 StartService(启动运行在后台的服务,所谓后台即没有界页;作为四大组件之一,其是运行在主线程中的)
启动时:
Context.startService(intent)-->onCreate()àonStartCommand ()
停止时:
Context_stopService(intent)-->onDestroy()
使用方法:
(1)、创建一个自定义服务类继承Service,实现抽象方法
(2)、清单文件中注册自定义的服务类
(3)、在activity中通过startService和 stopService()
看一个Demo
1 package com.example.demo01; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.util.Log; 7 import android.view.View; 8 9 public class MainActivity extends Activity { 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 // TODO Auto-generated method stub 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 16 } 17 18 public void btn_startService(View view) 19 { 20 Intent intent = new Intent(this,MyService.class); 21 intent.putExtra("info", "这里是传送的数据"); 22 startService(intent); 23 Log.i("activity", "开启服务"); 24 25 } 26 public void btn_closeService(View view) 27 { 28 Intent intent = new Intent(this,MyService.class); 29 Log.i("activity", "关闭服务"); 30 stopService(intent); 31 } 32 }