一、Service简单示例:
Service类:
public class DummyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
}
@Override
public void onStart(Intent intent,int startId){
super.onStart(intent,startId);
Log.i("Service-start", "服务开始了");
Toast.makeText(this, "i am server", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("Service-stop", "服务被销毁了");
}
}
Activity类:
public class ServerDemoActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1=(Button)findViewById(R.id.btn1);
btn1.setText("this is my activity");
btn1.setOnClickListener(this);
Button btn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btn1:{
doStart();
break;
}
case R.id.btn2:{
doStop();
break;
}
}
}
public void doStart(){
Intent starServer=new Intent(this,DummyService.class);
this.startService(starServer);
}
public void doStop(){
Intent starServer=new Intent(this,DummyService.class);
this.stopService(starServer);
}
}