Service的常见使用及代码示例
在Android中,Service是一种可以在后台运行的组件,即使用户没有正在交互的Activity,它也可以运行。
Service常见的使用场景包括执行后台任务、监听网络变化、播放音乐等。
下面是一个简单的Service的使用示例:
1. 创建一个继承于Service的类:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 服务被启动时调用
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
// 服务被销毁时调用
}
}
2. 在AndroidManifest.xml文件中注册这个Service:
<application
...>
<service
android:name=".MyService"
android:exported="true" >
</service>
...
</application>
3. 启动Service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
4. 停止Service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
注意,Service默认是运行在主线程的,如果你需要在Service中处理一些耗时的操作,你需要创建新的线程,否则可能会导致主线程阻塞。
如果需要让Service与Activity进行交互,你需要使用Bound Service,这时候Service需要实现onBind方法并返回一个IBinder对象。
下面是一个简单的Bound Service的示例:
1. 创建一个继承于Service的类:
public class MyBoundService extends Service {
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyBoundService getService() {
return MyBoundService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public int add(int x, int y) {
return x + y;
}
}
2. 在AndroidManifest.xml文件中注册这个Service:
<application
...>
<service
android:name=".MyBoundService"
android:exported="true" >
</service>
...
</application>
3. 在Activity中绑定Service:
MyBoundService myService;
boolean isBound = false;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder iBinder) {
MyBoundService.LocalBinder binder = (MyBoundService.LocalBinder) iBinder;
myService = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (isBound) {
unbindService(connection);
isBound = false;
}
}
当你需要使用Service的方法时,可以直接调用,如:myService.add(1, 2);