这里我的要求是,我需要通过使用Retrofit从URL下载位图,并需要设置为Notification Icon.I尝试但我得到空指针异常。我不想将其下载到任何文件或文件夹。直接我想使用返回位图来通知图标。请帮助我错了
我的代码:
if (photourl != null) {
if ((photourl.endsWith(".jpg") || photourl.endsWith(".png") || photourl.endsWith(".jpeg") )) {
if(messageType!=6 && messageType!=7){
RoundCornerImg RCIMG = new RoundCornerImg();
bm = RCIMG.getRoundedRectBitmap(getImageBitmap(photourl), 10);
}else{
bm = getImageBitmap(photourl);
}
photo_flag = true;
}
}
获取图像位图方法:
private Bitmap getImageBitmap(String url) {
Call<ResponseBody> call=RetroApiCall.getNotificationImage(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
bitmap =BitmapFactory.decodeStream(response.body().byteStream());
}else{
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
if (Build.VERSION.SDK_INT >= 20) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.notification);
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
return bitmap;
}
谢谢!
答案 0 :(得分:1)
这里的方法 getImageBitmap 位图被错误地转换了。我通过以下代码解决了它
private void getImageBitmap(String url) {
Call<ResponseBody> request = RetroApiCall.getNotificationImage(url);
try {
downloadFile(request.execute().body());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void downloadFile(ResponseBody body) throws IOException {
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
setBitmap(bitmap);
}
我终于得到了答案!!!
答案 1 :(得分:-1)
private Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
private void someMethod() {
Picasso.with(this).load("url").into(target);
}
@Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}