异步消息处理是什么?
异步消息处理解决了子线程无法进行UI操作的问题,如必须在子线程执行耗时操作,根据返回结果更新UI
Handler
修改activity_main,当点击按钮时,TextView的内容会改变:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/change"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="change text" />
<TextView
android:id="@+id/unChange_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello world" />
</LinearLayout>
修改MainActivity,通过Handler和Message实现在按钮点击事件中开启子线程更新UI:
public class MainActivity extends AppCompatActivity {
public static final int UPDATE_TEXT = 1;
private TextView textView;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_TEXT:
textView.setText("hello java");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.unChange_text);
Button change = findViewById(R.id.change);
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
}
});
}
}
- Message:在线程间传递消息,可携带少量信息
- Handler:利用sendMessage()发送信息,handleMessage()处理信息
- MessageQueue:存放所有Handler发送的消息,等待被处理,线程独有
- Looper:通过loop()方法将MessagesQueue中的Message取出传递到handleMessage()方法中,线程独有
Handler标准用法
上面的Handler会提示 This Handler class should be static or leaks might occur (anonymous android.os.Handler) ,原因为内部类含有外部类的引用造成内存泄漏
方式1
把Handler定义成static,然后用post方法把Runnable对象传送到主线程,但适用于只有一个消息要发送的情形
public class MainActivity extends AppCompatActivity {
private TextView textView;
private static Handler handler = new Handler();
private class MyRunnable implements Runnable {
@Override
public void run() {
textView.setText("hello java");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.unChange_text);
Button change = findViewById(R.id.change);
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handler.post(new MyRunnable());
}
});
}
}
方式2
定义一个static的内部类Handler,让它持有Activity的弱引用
public class MainActivity extends AppCompatActivity {
private TextView textView;
public static final int UPDATE_TEXT = 1;
private static class MyHandler extends Handler {
WeakReference<MainActivity> mActivity;
MyHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
switch (msg.what) {
case UPDATE_TEXT:
activity.textView.setText("hello java");
break;
}
}
}
MyHandler mHandler = new MyHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.unChange_text);
Button change = findViewById(R.id.change);
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.sendEmptyMessage(UPDATE_TEXT);
}
});
}
}
AsyncTask介绍
AsyncTask是基于异步消息处理机制的封装包,方便我们更容易进行子线程和主线程之间的切换。
通过继承AsyncTask,指定其3个泛型参数:
- Params:传入的参数
- Progress:用于显示当前进度的类型
- Result:用于指定返回值类型
重写其4个方法:
- onPreExecute():在后台任务执行前调用,用于初始化
- doInBackgroud(Params…):里面的代码会在子线程运行,在这里处理耗时操作,结束后通过return返回结果。方法中不可以进行UI操作,要更新UI调用publisProgress(Params…)传递参数
- onProgressUpdate(Params…):调用publisProgress(Params…)后,随后就会调用这个方法,其参数为publisProgress(Params…)中的Params,可在此方法中更新UI
- onPostExecute(Result):当后台任务执行完并通过return返回时,随后就会调用这个方法,其参数为doInBackgroud()返回值,可在此方法中更新UI并进行收尾工作
AsyncTask使用
接下来将实现一个下载例子,添加okhttp依赖:
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
添加权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
新建回调接口用于对下载过程监听:
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPaused();
void onCanceled();
}
新建DownloadTask继承AsyncTask:
- doInBackground()处理下载逻辑,需要判断文件是否存在,是否断点续传
- onProgressUpdate()中更新进度条
- onPostExecute()对下载结果回调
public class DownloadTask extends AsyncTask<String, Integer, Integer> {
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAILED = 1;
public static final int TYPE_PAUSED = 2;
public static final int TYPE_CANCELED = 3;
private DownloadListener listener;
private boolean isCanceled = false;
private boolean isPaused = false;
private int lastProgress;
public DownloadTask(DownloadListener listener) {
this.listener = listener;
}
@Override
protected Integer doInBackground(String... params) {
InputStream is = null;
RandomAccessFile saveFile = null;
File file = null;
try {
long downloadedLength = 0; //记录已下载的文件长度
String downloadUrl = params[0];
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
if(file.exists()){
downloadedLength = file.length();
}
long contentLength = getContentLength(downloadUrl); //文件总字节
if(contentLength == 0){
return TYPE_FAILED;
}else if(contentLength == downloadedLength){
return TYPE_SUCCESS;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("RANGE", "bytes=" + downloadedLength + "-")
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if(request != null){
is = response.body().byteStream();
saveFile = new RandomAccessFile(file, "rw");
saveFile.seek(downloadedLength);
byte[] b = new byte[1024];
int total = 0;
int len;
while((len = is.read(b)) != -1){
if(isCanceled){
return TYPE_CANCELED;
}else if(isPaused){
return TYPE_PAUSED;
}else {
total += len;
saveFile.write(b, 0, len);
int progress = (int) ((total + downloadedLength) * 100 / contentLength);
publishProgress(progress);
}
}
response.body().close();
return TYPE_SUCCESS;
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(is != null){
is.close();
}
if(saveFile != null){
saveFile.close();
}
if(isCanceled && file != null){
file.delete();
}
}catch (Exception e){
e.printStackTrace();
}
}
return TYPE_FAILED;
}
@Override
protected void onProgressUpdate(Integer... values) {
int progress = values[0];
if(progress > lastProgress){
listener.onProgress(progress);
lastProgress = progress;
}
}
@Override
protected void onPostExecute(Integer status) {
switch (status){
case TYPE_SUCCESS:
listener.onSuccess();
break;
case TYPE_FAILED:
listener.onFailed();
break;
case TYPE_PAUSED:
listener.onPaused();
break;
case TYPE_CANCELED:
listener.onCanceled();
break;
default:
break;
}
}
public void pauseDownload(){
isPaused = true;
}
public void cancelDownload(){
isCanceled = true;
}
private long getContentLength(String downloadUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if(response != null && response.isSuccessful()){
long contentLength = response.body().contentLength();
response.body().close();
return contentLength;
}
return 0;
}
}
新建DownloadService继承Service,在回调接口处理通知栏的显示,通过Binder暴露给Activity调用:
public class DownloadService extends Service {
private DownloadTask downloadTask;
private int mProgress;
private String downloadUrl;
private DownloadListener listener = new DownloadListener() {
@Override
public void onProgress(int progress) {
mProgress=progress;
getNotificationManager().notify(1, getNotification("Downloading...", progress));
}
@Override
public void onSuccess() {
downloadTask = null;
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Success", -1));
Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailed() {
downloadTask = null;
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Failed", -1));
Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onPaused() {
downloadTask = null;
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Pausing", mProgress));
Toast.makeText(DownloadService.this, "Paused", Toast.LENGTH_SHORT).show();
}
@Override
public void onCanceled() {
downloadTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
};
private DownloadBinder mBinder = new DownloadBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class DownloadBinder extends Binder {
public void startDownload(String url){
if(downloadTask == null){
downloadUrl = url;
downloadTask =new DownloadTask(listener);
downloadTask.execute(downloadUrl);
startForeground(1, getNotification("Downloading...",0));
Toast.makeText(DownloadService.this, "Downloading...", Toast.LENGTH_SHORT).show();
}
}
public void pauseDownload(){
if(downloadTask != null){
downloadTask.pauseDownload();
}
}
public void cancelDownload(){
if(downloadTask != null){
downloadTask.cancelDownload();
}
if(downloadUrl != null){
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
File file =new File(directory + fileName);
if(file.exists()){
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
}
}
private NotificationManager getNotificationManager() {
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private Notification getNotification(String title, int progress) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentIntent(pi);
builder.setContentTitle(title);
if (Build.VERSION.SDK_INT > 26) {
NotificationChannel notificationChannel = new NotificationChannel("1", "test", NotificationManager.IMPORTANCE_DEFAULT);
getNotificationManager().createNotificationChannel(notificationChannel);
builder.setChannelId("1");
}
if(progress>0){
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}
}
修改MainActivity,获取运行时权限,绑定Service通过按钮进行调用:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startDownload = (Button) findViewById(R.id.start);
Button pauseDownload = (Button) findViewById(R.id.pause);
Button cancelDownload = (Button) findViewById(R.id.cancel);
startDownload.setOnClickListener(this);
pauseDownload.setOnClickListener(this);
cancelDownload.setOnClickListener(this);
Intent intent = new Intent(this, DownloadService.class);
startService(intent);
bindService(intent, connection, BIND_AUTO_CREATE);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
@Override
public void onClick(View view) {
if (downloadBinder == null) {
return;
}
switch (view.getId()) {
case R.id.start:
String url = "https://redirector.gvt1.com/edgedl/android/studio/install/2020.3.1.22/android-studio-2020.3.1.22-windows.exe";
downloadBinder.startDownload(url);
break;
case R.id.pause:
downloadBinder.pauseDownload();
break;
case R.id.cancel:
downloadBinder.cancelDownload();
break;
default:
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You deny the permission", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
效果图: