Android学习:Service使用

来源:互联网 发布:湖北卡五星麻将源码 编辑:程序博客网 时间:2024/06/05 13:22

一.基础知识

服务一般分为两种:

1:本地服务 Local Service 用于应用程序内部。在Service可以调用Context.startService()启动,调用Context.stopService()结束。在内部可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。无论调用了多少次startService(),都只需调用一次stopService()来停止。

2:远程服务, Remote Service 用于android系统内部的应用程序之间。可以定义接口并把接口暴露出来,以便其他应用进行操作。客户端建立到服务对象的连接,并通过那个连接来调用服务。调用Context.bindService()方法建立连接,并启动,以调用 Context.unbindService()关闭连接。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。
提供给可被其他应用复用,比如定义一个天气预报服务,提供与其他应用调用即可。

那么先来看Service的生命周期吧:如图:


context.startService() ->onCreate()- >onStart()->Service running--调用context.stopService() ->onDestroy()

context.bindService()->onCreate()->onBind()->Service running--调用>onUnbind() ->onDestroy()从上诉可以知道分别对应本地的,,以及远程的,也对应不同的方式启动这个服务。


MainActivity.java

package com.example.servicedemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Intent serviceIntent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button StartServiceButton = (Button)findViewById(R.id.buttonStartService);StartServiceButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubserviceIntent = new Intent(MainActivity.this, TestService.class);MainActivity.this.startService(serviceIntent);}});Button stopServiceButton = (Button)findViewById(R.id.buttonStopService);stopServiceButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubif(serviceIntent != null){Boolean returnResult = MainActivity.this.stopService(serviceIntent);Log.i("servicetest", "Service stoped:" + returnResult);}}});}}

TestService.java

package com.example.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class TestService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubnew Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor(int i=0; i<100; i++){try {Thread.sleep(1000);Log.i("servicetest", "print number:" +i);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {Log.i("servicetest", "Service destroy");super.onDestroy();}}

http://www.cnblogs.com/zhangdongzi/archive/2012/01/08/2316711.html