bind service可以使得 Activity和Service 共同生死
package com.example.testservice;
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.text.format.Time;
import android.util.Log;
import android.view.Menu;
import com.example.testservice.MyService.MyBinder;
public class MainActivity extends Activity {
private MyConn myConn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myConn = new MyConn();
setContentView(R.layout.activity_main);
Intent service = new Intent(this, MyService.class);
bindService(service, myConn, Context.BIND_AUTO_CREATE);
}
public class MyConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
Log.i(this.getClass().toString(),
"servic has been created,and i an from activity");
MyBinder myBinder = (MyBinder) service;
Log.i(this.getClass().toString(), myBinder.getCounts()
+ ": result has been invoked");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(this.getClass().toString(),
"servic has been disconnect,and i an from activity");
}
}
/**
* unbind it when destroy unBindService() is recommended
*/
protected void onDestroy() {
super.onDestroy();
unbindService(myConn);
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
package com.example.testservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
int result = 0;
private MyBinder myBinder;
public boolean run = true;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
myBinder = new MyBinder();
Log.i(this.getClass().toString(),
"some service has been created and started ");
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
if (!run) {
return;
}
result++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(this.getClass().toString(), result
+ "=======change from service");
}
}
}).start();
}
/**
* set run = false to stop the count thread
*/
@Override
public boolean onUnbind(Intent intent) {
Log.e("Service", "The Activity has been quit");
run = false;
return super.onUnbind(intent);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return myBinder;
}
/**
* activity can get the "result" through the binder
* @author sfshine
*
*/
public class MyBinder extends Binder {
public int getCounts() {
return result;
}
}
}