相关知识:
[转]Android 中的 Service 全面总结
Android Service完全解析,关于服务你所需知道的一切(上)
Android Notification全面解析
Service
创建与调用
新建一个类,继承service
重写
- onCreate——第一次启动Service时调用,而且只调用一次,系统只有该服务的一个实例。也因此终止一次。
- onBind——通过bindService()启动时调用
- onUnbind——通过unbindService()启动时调用
- onStartCommand——通过startService()调用
onDestroy——销毁时调用
stopSelf()终止自己
Activity的操作:
- 通过startService()开启的服务,需要通过stopService()终止服务,即调用onDestroy();
- 通过bingService()开启的服务,需要通过unbingService()终止服务,即onDestroy();
- 同时使用两者开启的服务,需要通过stopService和unbindService两者分别调用后,才能终止服务,即才能调用onDestroy();
- 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候),与调用 unbindService 的处理效果一样;
Service的通信
未完待续……
DEMO:创建Service进行上传下载,并使用Notification在通知栏显示进度
相关知识:
【封装】使用okHttp进行网络请求及上传下载进度监听
http://blog.csdn.net/u013806583/article/details/69944279
执行上传下载的功能,由此部分实现
主体:主要包含了Notification的使用
package com.example.guan.testapp.sevice;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import com.example.guan.testapp.R;
import com.example.guan.testapp.common.AppCommon;
import com.example.guan.testapp.model.GuanFile;
import com.example.guan.testapp.utils.OkHttpManager;
import java.util.ArrayList;
public class DownloadUploadService extends Service {
NotificationManager notificationManager;
int ID_NOTIFICATION_DOWNLOAD = 0;
int ID_NOTIFICATION_UPLOAD = 1;
String TAG = "DownloadUploadService";
public DownloadUploadService() {
}
@Override
public void onCreate() {
super.onCreate();
//获取NotificationManager
notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
AppCommon.ServiceOperation operation = (AppCommon.ServiceOperation) intent.getSerializableExtra("operation");
if (operation == AppCommon.ServiceOperation.DOWNLOAD) {
ArrayList<GuanFile> guanFiles = intent.getParcelableArrayListExtra("guanfiles");
doDownload(guanFiles.get(0));
} else if (operation == AppCommon.ServiceOperation.UPLOAD) {
doUpload();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Download and Upload Service has stopped");
}
private void doDownload(GuanFile guanFile) {
//创建NotificationCompat.Builder
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.mipmap.ic_file_download_white_24dp);
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
mBuilder.setContentTitle(guanFile.FileName);//设置标题
mBuilder.setContentText("详细内容:正在下载……");//设置详细内容
mBuilder.setTicker("this is ticker");//首先弹出来的,用于提醒的一行小字
mBuilder.setOngoing(true)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
mBuilder.setWhen(System.currentTimeMillis());//设置时间
mBuilder.setProgress(0, 0, false);//设置进度条,true为不确定(持续活动)的进度条
final Notification notification = mBuilder.build();
//创建通知栏之后通过给他添加.flags属性赋值
notification.flags |= Notification.FLAG_NO_CLEAR;//不自动清除
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;//前台服务标记
//notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;//标记声音或者震动一次
notification.flags |= Notification.FLAG_AUTO_CANCEL;//点击通知之后,取消状态栏图标
/*这里的标识位有很多,根据情况选择*/
notificationManager.notify(ID_NOTIFICATION_DOWNLOAD, notification);//显示notification
/**
* 知识点:|=,位或. a|=b 等价于 a=a|b. a|b即ab都转换为二进制,然后按位做“或”运算
*/
//开始下载
Log.d(TAG, guanFile.FilePath);
OkHttpManager.download(AppCommon.downloadURL, guanFile.FilePath, guanFile.FileName,
new OkHttpManager.ProgressListener() {
@Override
public void onProgress(long totalSize, long currSize, boolean done, int id) {
//Log.v(TAG, "totalSize:" + totalSize + "\tcurrSize:" + currSize);
mBuilder.setProgress((int) totalSize, (int) currSize, false);//false:显示下载的百分比;true:不显示百分比,只表示当前正在运行
notificationManager.notify(ID_NOTIFICATION_DOWNLOAD, mBuilder.build());//不断的更新进度条
}
},
new OkHttpManager.ResultCallback() {
@Override
public void onCallBack(OkHttpManager.State state, String result) {
Log.e(TAG, state + "\t" + result);
notificationManager.cancel(ID_NOTIFICATION_DOWNLOAD);//下载成功,销毁Notification
}
});
}
private void doUpload() {
//下载的实现了,上传的模仿着写就好了。
}
}
调用
//点击开始按钮,启动Service
startservice_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*
*补充:GuanFile是自己写的一个model
*/
ArrayList<GuanFile> guanFiles=new ArrayList<GuanFile>();
guanFiles.add(new GuanFile("tmpname",AppCommon.downloadURL,filePath));
Intent intent=new Intent(mContext, DownloadUploadService.class);
intent.putExtra("operation", AppCommon.ServiceOperation.DOWNLOAD);
intent.putExtra("guanfiles",guanFiles);
MainActivity.this.startService(intent);
}
});
//点击结束按钮,停止Service
stopservice_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext, DownloadUploadService.class);
MainActivity.this.stopService(intent);
}
});