onBind()
方法Activity
可以决定何时开始下载,以及随时查看下载的进度。public class MyService extends Service {
public MyService() {
}
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "startDownload executed");
}
public void getProgress(){
Log.d("MyService", "getProgress execute");
}
}
//一个Binder对象来对下载功能进行管理
private DownloadBinder mBinder = new DownloadBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
bindService
进行服务和Activity之间的绑定。public class MainActivity extends AppCompatActivity {
//1.获取Binder
private MyService.DownloadBinder downloadBinder;
//2.获取connection
private ServiceConnection connection = new ServiceConnection() {
//这两个方法会在活动与服务成功绑定以及解除绑定前后调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//向下转型获得mBinder
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this , MyService.class);
bindService(intent , connection , BIND_AUTO_CREATE);
unbindService(connection);
}
}
IBinder
bindService()
Intent(第一个参数)
ServiceConnection(第二个参数)
绑定选项的标记(第三个参数)
Binder
类,并从onBind()
返回该类的实例。具体流程(代码见1.1)
1. 在Service中自定义一个Binder类,并创建可执行以下某种操作的Binder实例:
2.从onBind()方法返回此Binder实例
3. 在客户端中,在ServiceConnection的onServiceConnected()回调方法中接收Binder,并使用提供的方法调用绑定Service。
代码2
public class LocalService extends Service {
private final IBinder binder = new LocalBinder();
private final Random mGenerator = new Random();
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
// 绑定服务
Intent intent = new Intent(this, LocalService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
//解绑服务
unbindService(connection);
mBound = false;
}
public void onButtonClick(View v) {
if (mBound) {
int num = mService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
//连接,监听Service
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className , IBinder service) {
//向下转型获取Binder
//获取Service
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Ning", "onStartCommand: ");
Intent newIntent = new Intent();
newIntent.putExtra("key" , "text");
newIntent.setAction("location.report");
sendBroadcast(newIntent);
return super.onStartCommand(intent, flags, startId);
}
//内部类,实现BroadcastReceiver,创建内部类作为广播接收器
public class LocationReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if(intentAction.equals("location.report")){
Log.d("Ning", "onReceive: 111111111");
}
}
}
LocationReceiver locationReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationReceiver = new LocationReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("location.report");
registerReceiver(locationReceiver , intentFilter);
Log.d("Ning", "onReceive: 11111");
Intent intent = new Intent(this , MyService.class);
startService(intent);
}
@Override
protected void onDestroy() {
unregisterReceiver(locationReceiver);
super.onDestroy();
}
public class MessengerService extends Service {
static final int MSG_SAY_HELLO = 1;
//1.实现IncomingHandler来接收客户端的每个回调
static class IncomingHandler extends Handler{
private Context applicationContext;
IncomingHandler(Context context){
applicationContext = context.getApplicationContext();
}
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case MSG_SAY_HELLO:
Toast.makeText(applicationContext, "hello", Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
}
Messenger mMessenger;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
//2.使用Handler创建Messenger对象,
mMessenger = new Messenger(new IncomingHandler(this));
//3.Messenger创建一个IBinder
return mMessenger.getBinder();
}
}
public class ActivityMessenger extends Activity {
Messenger mService = null;
boolean bound;
//连接
//这里用和服务端一样的IBinder创建一个Messenger
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
bound = true;
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
bound = false;
}
};
//通过这个Messenger发送Message
public void sayHello(View v) {
if (!bound) return;
Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
bindService(new Intent(this, MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (bound) {
unbindService(mConnection);
bound = false;
}
}
}