1. local service
LocalService.java
package com.android.networks;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class LocalService extends Service {
final static String TAG = "LocalService";
public class LocalBinder extends Binder {
public LocalService getService() {
return (LocalService.this);
}
}
private LocalBinder binder = new LocalBinder();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return binder;
}
public void testPrint() {
Log.v(TAG, "test print");
}
}
Client.java
package com.android.root;
import com.android.networks.LocalService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
public class RootActivity extends Activity {
protected boolean bBond = false;
protected LocalService appService = null;
protected ServiceConnection onSerivce = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
appService = ((LocalService.LocalBinder)arg1).getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
appService = null;
}
};
protected void doBindService() {
if (!bBond) {
bindService(new Intent("android.intent.action.remote.localservice"),
onSerivce, Context.BIND_AUTO_CREATE);
bBond = true;
}
}
protected void doUnBindService() {
if (bBond) {
unbindService(onSerivce);
bBond = false;
}
}
@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
doBindService();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
doBindService();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
doUnBindService();
}
}