Android笔记三十一.Service综合实例(一)

<span style="font-family:Times New Roman;font-size:18px;">package com.example.servicetest1;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class MyBindService extends Service { private int count=0; private boolean threadFlag=true;//结束线程标志 MyIBinder bind = new MyIBinder();//实例化一个Binder对象,用于被onBind方法返回给访问者 /*0.Binder子类 * 其对象用于与访问者通信,访问者通过调用IBinder子类中的方法获取Service中的数据*/ public class MyIBinder extends Binder { //自定义成员方法,用于返回Service中的数据 public int getCount() { return count; } } /*1.onBind方法 * service用于返回一个IBinder对象给客户端方便通信 * 如果是访问者通过Context.startService启动该Service,则返回为空 */ @Override public IBinder onBind(Intent arg0) { System.out.println("—MyService’s onBind invoked!—"); return bind; } /*2.onCreate方法 * 当Service启动后,自动调用该方法,用于初始化 * */ public void onCreate() { System.out.println("—MyService’s onCreate invoked!—"); //创建一个线程,用于按一定时间间隔更新count的值 new Thread(){ public void run() {while(threadFlag)//默认为true{try{Thread.sleep(500);}catch (InterruptedException e){e.printStackTrace();}count++;} } }.start(); super.onCreate(); } /*3.onStartCommand方法 * 每次访问者调用startService方法启动该Service时都会回调该方法*/ public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("—MyService’s onStartCommand invoked!—"); return super.onStartCommand(intent, flags, startId); } /*4.onDestroy方法 * 当访问者调用Context.stopService方法后,调用该方法关闭Service服务 * */ public void onDestroy() { System.out.println("—MyService’s onDestory invoked!—"); threadFlag=false; super.onDestroy(); } /*5.onUnbind方法 * 当访问者调调用Context.unBind()方法后,,调用该方法与Service解除绑定*/ public boolean onUnbind(Intent intent) { System.out.println("—MyService’s onUnbind invoked!—"); return super.onUnbind(intent); } }</span>

世界上那些最容易的事情中,拖延时间最不费力。

Android笔记三十一.Service综合实例(一)

相关文章:

你感兴趣的文章:

标签云: