做个记录
1、启动一个简单的服务
启动和停止服务
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务
停止服务还可以在继承Service的类里面调用stopself方法来停止
至于MyService类,继承Service并重写onBind(必须要的),onCreate,onDestroy,onStartCommand(执行逻辑)方法,并在Androidmanifest文件注册就可以使用
2、启动一个Bind服务
绑定活动与服务,增加联系,例子:下载任务
服务后台下载,活动获取服务中的下载进度
思路:在MyService中新建一个内部类,继承Binder,利用onBind方法返回对象并调用内部类的方法
绑定服务与活动:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE); // 绑定服务
unbindService(connection); // 解绑服务
其中connection是ServiceConnection对象
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
}
};
模拟下载的内部类:
class DownloadBinder extends Binder {
public void startDownload() {
Log.d(TAG, "startDownload executed");
synchronized ((Object) progress){
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<100; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
Log.d(TAG, "run: error");
}
progress++;
}
}
}).start();
}
}
public int getProgress() {
Log.d(TAG, "Progress:"+progress);
return progress;
}
}
3、前台服务
前台服务可以防止因为系统内存不足被回收
只需在继承Service的类中的onCreate方法中加入下面的代码即可
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.build();
startForeground(1, notification);