Service 生命周期基础

来源:互联网 发布:青少年编程创业 编辑:程序博客网 时间:2024/05/01 01:02
import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class MyService extends Service {private static final String TAG = "MyService";@Overridepublic IBinder onBind(Intent arg0) {Log.i(TAG,"onBind called.");//要想实现绑定操作,必须返回一个实现了IBinder接口类型的实例,//该接口描述了与远程对象进行交互的抽象协议,有了它我们才能与服务进行交互//返回了一个Binder的实例,而这个Binder恰恰是实现了IBinder接口,所以这样就可以实现绑定服务的操作了return new MyBinder();}public class MyBinder extends Binder {public void greet(String name) {Log.i(TAG,"hello,"+name);}}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();Log.d(TAG,"onCreate called...");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubLog.d(TAG,"onDestroy called...");super.onDestroy();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.d(TAG,"onStartCommand called...");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);Log.d(TAG,"onStart called...");}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubLog.d(TAG,"onUnbind called...");return super.onUnbind(intent);}}


Activity


import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.support.v7.app.ActionBarActivity;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends ActionBarActivity {private static final String TAG = "MyService";private Button startBtn;private Button stopBtn;private Button bindBtn;private Button unbindBtn;private Button testBinderBtn;private boolean binded = false;private MyService.MyBinder binder;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName arg0) {}@Overridepublic void onServiceConnected(ComponentName arg0, IBinder serviceBinder) {binded = true;Log.d(TAG, "onServiceConnected called");//一旦绑定了服务后, 就可以使用binder来和服务通信//在这一刻我们绑定服务,下一刻我们去操作binder对象,也许它还为null,//这就容易引起空指针异常,正确的做法是把这些操作放到绑定成功之后binder = (MyService.MyBinder)serviceBinder;//binder.greet("Lucy from Activity..");}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startBtn = (Button) findViewById(R.id.start);stopBtn = (Button) findViewById(R.id.stop);bindBtn = (Button) findViewById(R.id.bind);unbindBtn = (Button) findViewById(R.id.unbind);testBinderBtn = (Button) findViewById(R.id.testBinder);MyOnClickListener clickListener = new MyOnClickListener();startBtn.setOnClickListener(clickListener);stopBtn.setOnClickListener(clickListener);bindBtn.setOnClickListener(clickListener);unbindBtn.setOnClickListener(clickListener);testBinderBtn.setOnClickListener(clickListener);}@Overridepublic void unbindService(ServiceConnection conn) {if (this.binded) {super.unbindService(conn);binded = false;}}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(conn);}protected void testBinder(){if(binded && this.binder != null) {binder.greet("calling function from MyService binder , and this is arg string..");}else {Log.i(TAG,"service not bound or binder is null.");}}// 点击一次start启动按钮, 调用onCreate, onStartCommand(onStartCommand中又调用了onStart方法)// 第二次点击时,onCreate方法就不再被调用了,而是直接调用了onStartCommand(onStartCommand中又调用了onStart方法)// Settings->Applications->Running services”就会发现我们刚刚启动的服务// 点击stop停止按钮onDestroy方法被调用了,此时服务停止运行。我们再次查看“Running// services”,就会发现MyService这个服务已不存在了// onBind方法和onUnbind方法始终没被调用// 如果点击start启动了服务后,直接退出应用程序, 而没有点击stop的话, 服务还会在后台继续运行// 也就是说这种没有绑定的模式下启动服务后服务不会随着应用程序退出而退出// 使用bindService启动服务后调用者和服务绑定到了一起,当调用者被销毁,服务也立即结终止。// 如果starService和bindService 混合使用的话 starService -> bindService -> unbindService// 第一次都是正常调用 service (onCreate-onStartCommand-onStart)=> (onBind -> onServiceConnected) => onUnbind// 一旦unBind后, service还是处于运行状态, 这时再去bind就不会调用onBind, 而是直接调用onServiceConnected, 既然bind失败那么unbind自然也不会调用了// 也就是说bind, unbind 启动服务后(调用startService后)只能绑定一次, 只要unbind后  再次bind就不会调用onBind方法class MyOnClickListener implements OnClickListener {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.start:Log.d(TAG, "you clicked Start");Intent startIntent = new Intent(MainActivity.this,MyService.class);startService(startIntent);break;case R.id.stop:Log.d(TAG, "stop clicked");Intent stopIntent = new Intent(MainActivity.this,MyService.class);stopService(stopIntent);break;case R.id.bind:Log.d(TAG, "bind clicked");Intent bindIntent = new Intent(MainActivity.this,MyService.class);bindService(bindIntent, conn, Context.BIND_AUTO_CREATE);break;case R.id.unbind:Log.d(TAG, "unbind clicked");unbindService(conn);break;case R.id.testBinder:Log.d(TAG,"testBinder clicked");testBinder();break;default:break;}}}}




0 0