package com.demo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ACDemoActivity extends Activity {
private Button button;
private TextView textView;
private ICountService countService;
Handler hLoc;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
countService = (ICountService) service;
countService.setHandler(hLoc);
Log.v( "CountService" , "on serivce connected, count is "
+ countService.getCount());
}
@Override
public void onServiceDisconnected(ComponentName name) {
countService = null ;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button) findViewById(R.id.btn);
textView=(TextView) findViewById(R.id.show);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("数据显示为:"+countService.getCount());
}
});
hLoc = new Handler(){
@Override
public void handleMessage(Message msg) {
textView.setText("数据显示为:" + msg.obj);
super.handleMessage(msg);
}};
this.bindService( new Intent( "com.demo.CountService" ),serviceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
this.unbindService(serviceConnection);
super.onDestroy(); //注意先后
}
}
评论1
最新资源