万书网 > 文学作品 > Android从入门到精通 > 第147页

第147页





super.onCreate(savedInstanceState);



setContentView(R.layout.main);



}



@Override



protected  void  onStart()  {



super.onStart();



Button  button  =  (Button)  findViewById(R.id.current_time);



button.setOnClickListener(new  View.OnClickListener()  {



public  void  onClick(View  v)  {



Intent  intent  =  new  Intent(CurrentTimeActivity.this,  CurrentTimeService.class);



bindService(intent,  sc,  BIND_AUTO_CREATE);  //绑定服务



if  (bound)  {  //如果绑定则显示当前时间



Toast.makeText(CurrentTimeActivity.this,  cts.getCurrentTime(),



Toast.LENGTH_LONG).show();



}



}



});



}



@Override



protected  void  onStop()  {



super.onStop();



if  (bound)  {



bound  =  false;



unbindService(sc);  //解绑定



}



}



private  ServiceConnection  sc  =  new  ServiceConnection()  {



public  void  onServiceDisconnected(ComponentName  name)  {



bound  =  false;



}



public  void  onServiceConnected(ComponentName  name,  IBinder  service)  {



LocalBinder  binder  =  (LocalBinder)  service;  //获得自定义的LocalBinder对象



cts  =  binder.getService();  //获得CurrentTimeService对象



bound  =  true;



}



};



}

(4)修改AndroidManifest.xml文件,增加Activity和Service配置,其代码如下:








package="com.mingrisoft"



android:versionCode="1"



android:versionName="1.0"  >










android:icon="@drawable/ic_launcher"



android:label="@string/app_name"  >





































(5)启动应用程序,界面如图13.6所示。单击“当前时间”按钮,会显示格式化的当前时间,如图13.7所示。





图13.6 应用程序主界面  图13.7 显示当前时间

13.3.5 实例2:使用Messenger类绑定服务显示时间

例13.4   在Eclipse中创建Android项目,名称为13.4,实现使用Messenger类绑定服务并显示当前时间。(实例位置:光盘\TM\sl\13\13.4)

(1)修改res\layout目录中的main.xml布局文件,设置背景图片并添加一个按钮,然后设置按钮文字的内容、颜色和大小,其代码如下:








android:layout_width="fill_parent"



android:layout_height="fill_parent"



android:background="@drawable/background"



android:orientation="vertical"  >






android:id="@+id/current_time"



android:layout_width="wrap_content"



android:layout_height="wrap_content"



android:text="@string/current_time"



android:textColor="@android:color/black"



android:textSize="25dp"  />





(2)创建CurrentTimeService类,它继承了Service类。内部类IncomingHanlder继承了Handler类,重写其handleMessage()方法来显示当前时间,其代码如下:

public  class  CurrentTimeService  extends  Service  {



public  static  final  int  CURRENT_TIME  =  0;



private  class  IncomingHandler  extends  Handler  {



@Override



public  void  handleMessage(Message  msg)  {



if  (msg.what  ==  CURRENT_TIME)  {



Time  time  =  new  Time();  //创建Time对象



time.setToNow();  //设置时间为当前时间