package com.jiuqi.testservice01;
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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button
btn1;
private Button btn2;
private Button btn3;
private Button btn4;
private MyService myservice ;
public ServiceConnection serviceconnection = new
ServiceConnection(){
@Override
public void onServiceDisconnected(ComponentName name){
myservice = null;
Toast.makeText(MainActivity.this, "MyService failed",
Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceConnected(ComponentName name, IBinder
service){
myservice = ((MyService.MyBinder)service).getService();
Toast.makeText(MainActivity.this, "MyService connected",
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener btnClickListener = new
OnClickListener(){
@Override
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(MainActivity.this,MyService.class);
switch(v.getId()){
case R.id.button1:
startService(intent);
break;
case R.id.button2:
stopService(intent);
break;
case R.id.button3:
bindService(intent, serviceconnection,
Context.BIND_AUTO_CREATE);
break;
case R.id.button4:
unbindService(serviceconnection);
break;
default:
break;
}
}
};
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
btn4 = (Button)findViewById(R.id.button4);
btn1.setOnClickListener(btnClickListener);
btn2.setOnClickListener(btnClickListener);
btn3.setOnClickListener(btnClickListener);
btn4.setOnClickListener(btnClickListener);
}
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,
menu);
return true;
}
@Override
protected void
onDestroy(){
super.onDestroy();
unbindService(serviceconnection);
}
}