爬了某网站的图片,放到自己App上观赏一波。发现自己写的App中的一个获取本地的相片功能直接崩了。然后就想优化优化。废话不多说,上图。
The application may be doing too much work on its main thread.
这个坑应该是最容易去填的,但是还是要说。因为有这个坑,然后会升级成另一个坑。还是要说,这个坑是什么。怎么造成的。怎么解决。
这个坑是什么?
The application may be doing too much work on its main thread,就是提示你在主线程里面干了太多事情了。简单,就像网络请求一样把耗时间的任务放在异步线程去做。
为什么会造成这个坑?
造成这个坑是因为,你在主线程里面做了太多的事情了。而我这里在主线程里面做的耗时任务就是如下代码:
public static Map<String, List<Picture>> getPicturs(Context context) {
Map<String, List<Picture>> maps = new HashMap<>();
Cursor mCursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projections,
MediaStore.Images.Media.MIME_TYPE + " = ? or " + MediaStore.Images.Media.MIME_TYPE + " = ?",
new String[]{IMAGE_JPEG, IMAGE_PNG},
MediaStore.Images.Media.DATE_ADDED + " desc");
if (mCursor == null) return maps;
try {
mCursor.moveToFirst();
while (mCursor.moveToNext()) {
int pictureID = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID));
String picturePath = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
String thumbPath = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
Picture picture = new Picture(pictureID, picturePath, thumbPath);
String floderName = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
List<Picture> datas = maps.get(floderName);
if (datas == null) {
datas = new ArrayList<>();
maps.put(floderName, datas);
}
datas.add(picture);
maps.put(floderName, datas);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
mCursor.close();
}
return maps;
}
这个方法是使用ContentProvider将手机中的图片扫描出来。然后放到Map里面。因为手机里面的图片比较多。所以扫描的时间比较慢。所以就造成这个warning。
怎么解决这个坑。
简单,直接在子线程里面去处理不就好了吗?OK 改造一下在子线程里面去处理一下。然后用Handler来试试看。
new Thread(new Runnable() {
@Override
public void run() {
maps = PictruesResolver.getPicturs(PicturesActivity.this);
handler.sendEmptyMessage(1);
}
}).start();
这个时候The application may be doing too much work on its main thread是解决了,但是如果你不断的切换界面,在进去图片展示的界面。这样重复操作。Leakcanary就会提示内存泄露。这也就是刚才说的,另一个坑升级版的坑。内存泄露介绍比较给力的文章http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1123/2047.html
就像文章里面所说的,在onDestroy中清理掉所有Messages,这样就可以解决内存泄露.
下面提供一下我所处理的一种方案:使用IntentService进行异步操作,操作成功就发一个广播出来给自定义广播。然后广播在回调自己的业务逻辑.
IntentService代码:
public class PictureService extends IntentService {
public PictureService(String name) {
super(name);
}
public PictureService() {
this(PictureService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
HashMap<String, List<Picture>> maps = (HashMap<String, List<Picture>>) PictruesResolver.getPicturs(getApplicationContext());
broadcastIntent.setAction(PictureReceiver.PictureReceiver_ACTION);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
SPUtils.put(getApplicationContext(),"picturs",new Gson().toJson(maps));
sendBroadcast(broadcastIntent);
}
}
广播代码:
public class PictureReceiver extends BroadcastReceiver {
public static final String PictureReceiver_ACTION = "PICTUREACTION";
private PictureProxy.PictureCallBack callBack;
public PictureReceiver(PictureProxy.PictureCallBack callBack) {
this.callBack = callBack;
}
@Override
public void onReceive(Context context, Intent intent) {
try {
String datas = (String) SPUtils.get(context, "picturs", "");
SPUtils.put(context, "picturs", "");
if (TextUtils.isEmpty(datas)) {
callBack.onFail("图片获取失败");
} else {
Map<String, List<Picture>> maps = new Gson().fromJson(datas, new TypeToken<Map<String, List<Picture>>>() {
}.getType());
callBack.onSuccess(maps);
}
} catch (Exception e) {
e.printStackTrace();
callBack.onFail("图片获取失败");
} finally {
}
}
}
核心代理类
public class PictureProxy {
private Context context;
private PictureReceiver receiver;
private boolean isRegister = false;
public PictureProxy(Context context) {
this.context = context;
}
/**
* 开始获取图片
**/
public void startPictureProxy(PictureCallBack callBack) {
Intent intent = new Intent(context, PictureService.class);
context.startService(intent);
//接受者
receiver = new PictureReceiver(callBack);
IntentFilter filter = new IntentFilter(PictureReceiver.PictureReceiver_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
context.registerReceiver(receiver, filter);
isRegister = true;
}
public interface PictureCallBack {
void onSuccess(Map<String, List<Picture>> maps);
void onFail(String meesage);
}
public void destroyProxy() {
if (receiver == null || !isRegister) return;
context.unregisterReceiver(receiver);
}
}
在这里踩了一个坑:
FAILED BINDER TRANSACTION !!! (parcel size = 9655008)
本来是直接用intent传输数据的,但是又踩了一个地雷。因为Intent里面不能存放数据量>1M。然后实在没办法。代码中会有一些序列化和反序列的代码(别打脸)
SPUtils.put(getApplicationContext(),"picturs",new Gson().toJson(maps));
Map<String, List<Picture>> maps = new Gson().fromJson(datas, new TypeToken<Map<String, List<Picture>>>() { }.getType());
后来,上了个厕所,想了一下。感觉自己有点小题大做了。其实我只要控制线程在Activity结束的时候。把它给cancel掉不就OK了吗?于是又有了下面的方案。
compositeSubscription = new CompositeSubscription();
Subscription subscription = Observable.create(new Observable.OnSubscribe<Map<String, List<Picture>>>() {
@Override
public void call(Subscriber<? super Map<String, List<Picture>>> subscriber) {
subscriber.onNext(PictruesResolver.getPicturs(context));
}
}).compose(RxUtils.<Map<String, List<Picture>>>transformerShedule())
.subscribe(new Action1<Map<String, List<Picture>>>() {
@Override
public void call(Map<String, List<Picture>> maps) {
onSuccess(maps);
}
});
compositeSubscription.add(subscription);
记得在onDestory中调用compositeSubscription.unsubscribe()停止异步操作。
@Override
protected void onDestroy() {
super.onDestroy();
// pictureProxy.destroyProxy();
if (compositeSubscription != null) {
compositeSubscription.unsubscribe();
}
RefWatcher refWatcher = BaseApplication.getRefWatcher(this);
refWatcher.watch(this);
}
附上git链接:https://github.com/BelongsH/Pictures
写完的时候,突然听到了by2的歌。真棒!!!
当我 紧握你的手
你是耀眼的星火
就让梦想编织王者世界
照亮整个宇宙
当你 握紧我的手
我变勇敢的星火
和你一起闪耀 到世界尽头
和你一起到永远 不分手