1.定义
无界面的控件,用来在后台处理耗时的操作,或者执行某些长期运行的任务。
2.使用
启动:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
停止:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
3.生命周期
- onCreate
特点:只在创建的时候执行一次 - onStartCommand
- onDestroy
特点:销毁的时候执行一次
4.与Activity之间的通信
采用startService()来启动服务,服务开启后,与开启它的组件是没有什么关联的。
复写onBind()方法完成组件的交互
public class MyService extends Service {
private MyBinder mBinder = new MyBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class MyBinder extends Binder {
public void startDownload() {
// 执行具体的下载任务
}
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private MyService.MyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder = (MyService.MyBinder) service;
myBinder.startDownload();
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
//这里传入BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建Service,这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
default:
break;
}
}
}
注意:
1.任何一个Service在整个应用程序范围内都是通用的,即可以和应用内的任何一个Activity建立连接,而且在建立连接的时候可以拿到相同的MyBind实例
2.stopService只会让Service停止,unbindService按钮只会让Service和Activity解除关联,一个Service必须要在既没有和任何Activity关联又处理停止状态的时候才会被销毁
3.Service运行在主线程中
5.前台Service
背景:默认的Service的优先级较低,在系统内存不足时很容易被回收
Notification notification = new Notification(R.drawable.ic_launcher,
"有通知到来", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",
pendingIntent);
startForeground(1, notification);
Log.d(TAG, "onCreate() executed");
6.远程Service
背景:因为Service是运行在主线程的,所以执行耗时操作的时候会发生ANR异常。
解决方案:
1.在service中开一个子线程
2.将默认Service改为远程Service(远程Service在新的进程中,因此不会阻塞当前进程)
不建议使用,由于调用的Activity与Service不在一个进程中,所以在bindService会导致程序崩溃
<service
android:name="com.example.servicetest.MyService"
android:process=":remote" >
</service>
3.使用AIDL建立远程Service与Activity的连接,实现多个应用程序共用一个Service
3.1 新建aidl文件
package com.example.admin.testapplication;
interface ServiceAidl {
int plus(int a, int b);
String toUpperCase(String str);
}
3.2 Activity中使用
public class MainActivity extends Activity {
private ServiceAidl myAIDLService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myAIDLService = ServiceAidl.Stub.asInterface(service);
try {
int result = myAIDLService.plus(50, 50);
String upperStr = myAIDLService.toUpperCase("comes from ClientTest");
Log.d("TAG", "result is " + result);
Log.d("TAG", "upperStr is " + upperStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bindService = (Button) findViewById(R.id.bind_service);
bindService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.admin.testapplication.ServiceAidl");
bindService(intent, connection, BIND_AUTO_CREATE);
}
});
}
}