Service总结(二)

来源:互联网 发布:淘宝标着极有家可信吗 编辑:程序博客网 时间:2024/06/09 15:49

在上一篇中介绍了用startService启动Service,用stopService停止服务的方法,至此主要介绍第二种方式:bindService启动,也是用的最多方式,方便service与activity的交互。

1.首先布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/LinearLayout1"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <Button android:id="@+id/registButton"           android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="注册"        />      <Button android:id="@+id/unregistButton"           android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="注销"        />      <Button           android:id="@+id/qidongService_btn"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="启动service"          />        <Button android:id="@+id/changeButton"           android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="测试"        />        <TextView            android:id="@+id/ceshiText"            android:layout_width="match_parent"            android:layout_height="wrap_content"            />      <Button android:id="@+id/stopButton"           android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="解绑Service"        /></LinearLayout>
2.继承service:

import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class TestService extends Service{private int i=0;private boolean isStop;public TestService() {// TODO Auto-generated constructor stub} public void onCreate() {   //只创建一次System.out.println("TestService->onCreate");new Thread(new DownThread()).start();//启动线程super.onCreate();}//每个一秒发一个通知    class DownThread implements Runnable{         public void run() {while(!isStop){i++;            try {Thread.sleep(1000);System.out.println("i->"+i);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}} }   }    public IBinder onBind(Intent intent) {//        System.out.println("onBind");return echoBinder;   }   private CountBinder echoBinder = new CountBinder();    public class CountBinder extends Binder{  //继承binder      public TestService getService(){ //获取该服务,在bind方式时使用    return TestService.this;      }    }    public boolean isStop() {return isStop;}public void setStop(boolean isStop) {this.isStop = isStop;}public int getI() {return i;}public void setI(int i) {this.i = i;}public void onDestroy() {System.out.println("TestService->onDestroy");super.onDestroy();}public boolean onUnbind(Intent intent) { //调用unbindService解绑service时,先执行这个方法,再执行Destroy方法System.out.println("TestService->onUnbind");isStop=true; //结束线程return super.onUnbind(intent);}    }

3.activity:

import android.app.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.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {Button bindBtn,unbindBtn,getBtn;TextView textView;private Intent intent;private TestService testService;TestServiceConnection connection = new TestServiceConnection();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);    intent = new Intent();intent.setClass(MainActivity.this, TestService.class);bindBtn = (Button) findViewById(R.id.bindService);unbindBtn = (Button) findViewById(R.id.unbindService);getBtn = (Button) findViewById(R.id.get_i);textView = (TextView) findViewById(R.id.show_i);       initEvent();}private void initEvent() {bindBtn.setOnClickListener(new OnClickListener() {public void onClick(View v) {bindService(intent, connection, Context.BIND_AUTO_CREATE);//绑定Service}});unbindBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubunbindService(connection);  //解绑service}});getBtn.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubint i= testService.getI();  //取出当前的i;textView.setText(i+"");  //}});} //链接service,实现ServiceConnection接口  class TestServiceConnection implements ServiceConnection{//这个方法在Service的onCreate方法之后立即执行!public void onServiceConnected(ComponentName name, IBinder service) {//得到servicetestService = ((TestService.CountBinder) service).getService();System.out.println("downServiceConnection..连接");}        //断开时调用的方法!public void onServiceDisconnected(ComponentName name) {System.out.println("service连接断开..");}}}

4.最后不要忘了在Manifest.xml文件中加上:

<service android:name=".TestService"></service>

截图:

   



5.至此大功告成,取得了service就可以与service尽心和交互啦,如果想更详尽的了解交互的方法,可以看前几篇博文:

http://blog.csdn.net/jycboy/article/details/46040189


0 0