1、DemoService.java編寫
代碼如下:
public class DemoService extends Service {
/**
*
*
*
*/
public IBinder onBind(Intent intent) {
return new MyBinder();//由于返回值是接口類型的IBinder,所以要新建一個類
}
/**
* MyBinder類既是onBind方法的返回值
*
*/
public class MyBinder extends Binder{
/**
*
*
*/
public void callMethodInService(int money){
if(money>500){
methodInService();
}else{
Toast.makeText(DemoService.this, "這點錢還想辦事呀?", 0).show();
}
}
}
/**
* 服務里面的方法
*/
public void methodInService(){
Toast.makeText(this, "哈哈,我是服務的方法,被你調用了。", 0).show();
}
@Override
public void onCreate() {
System.out.println("服務被創建了");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("服務被銷毀了。");
super.onDestroy();
}
}
2、MainActivity.java 編寫
代碼如下:
public class MainActivity extends Activity {
MyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 綁定服務,獲取服務里面的小蜜,間接的調用服務里面的方法。
*
/**
* 服務連接成功的通訊頻道
/
public void bind(View view){
Intent intent = new Intent(this,DemoService.class);
//intent 意圖
//conn 服務的通訊頻道
//1 服務如果在綁定的時候不存在,會自動創建
bindService(intent, new MyConn(), BIND_AUTO_CREATE);
}*
*/
private class MyConn implements ServiceConnection{
//當服務被成功連接的時候調用的方法
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder = (MyBinder) service;
}
//當服務失去連接的時候調用的方法
public void onServiceDisconnected(ComponentName name) {
}
}
/**
* 調用服務里面的方法。
* @param view
*/
public void call(View view){
myBinder.callMethodInService(3000);
}
}