【问题标题】:Loading bitmap in background with AsyncTask使用 AsyncTask 在后台加载位图
【发布时间】:2017-04-04 10:52:15
【问题描述】:

您好,开发人员,我是新来的,我真的需要帮助或建议我创建了音乐应用程序,我在专辑封面视图中有歌曲,但加载速度很慢我想使用 asyncTask 加载位图谢谢帮助.....

这是我的代码

public class SongFragment extends Fragment {


private Context context;
private SongsAdapter songAdt;
private ListView songView;
private ArrayList<Songs> songsList;
//Binder
private boolean musicBound = false;
//Service
private MusicService musicSrv;
private Intent playIntent;
//activity and playback pause flags
private boolean playbackPaused = false;
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.MusicBinder binder = (com.example.android.materialmusic.MusicService.MusicBinder) service;
        //get service
        musicSrv = binder.getService();
        //pass list
        musicSrv.setList(songsList);
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        musicBound = false;
    }
};

public SongFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_song, container, false);

    songView = (ListView) rootView.findViewById(R.id.songs);
    //instantiate list
    songsList = new ArrayList<>();
    //get songs from device
    getSongList();
    //sort alphabetically by title
    Collections.sort(songsList, new Comparator<Songs>() {
        public int compare(Songs a, Songs b) {
            return a.getTitle().compareTo(b.getTitle());
        }
    });

    //create and set adapter
    songAdt = new SongsAdapter(getActivity(), songsList);
    songView.setAdapter(songAdt);

    songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
            musicSrv.playSong();
            if (playbackPaused) {
                playbackPaused = false;
            }
        }
    });
    return rootView;
}

//start and bind the service when the activity starts
@Override
public void onStart() {
    super.onStart();
    if (playIntent == null) {
        playIntent = new Intent(getActivity(), MusicService.class);
        this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        this.getActivity().startService(playIntent);
    }
}

//method to retrieve song_item info from device
public void getSongList() {
    //query external audio
    ContentResolver musicResolver = getActivity().getContentResolver();
    Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    @SuppressLint("Recycle")
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

    if (musicCursor != null && musicCursor.moveToFirst()) {
        //get columns
        int titleColumn = musicCursor.getColumnIndex
                (MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (MediaStore.Audio.Media.ARTIST);
        int albumColumn = musicCursor.getColumnIndexOrThrow
                (MediaStore.Audio.Media.ALBUM_ID);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);

            long thisAlbum = musicCursor.getLong(albumColumn);
            Uri sArtworkUri = Uri
                    .parse("content://media/external/audio/albumart");
            Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisAlbum);

            Bitmap artWork = null;
            try {
                artWork = MediaStore.Images.Media.getBitmap(
                        musicResolver, albumArtUri);
                artWork = Bitmap.createScaledBitmap(artWork, 150, 150, true);

            } catch (FileNotFoundException exception) {
                exception.printStackTrace();
                artWork = BitmapFactory.decodeResource(getResources(),
                        R.drawable.no_cover);
            } catch (IOException e) {
                e.printStackTrace();
            }

            songsList.add(new Songs(thisId, thisTitle, thisArtist, artWork));
        }
        while (musicCursor.moveToNext());
    }
}

private class LoadingBitmap extends AsyncTask<Void, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(Void... params) {
        return bitmap;
    }
}

}

【问题讨论】:

  • 如果您从 url 加载,请不要使用 AsyncTask 使用 Picasso

标签: android bitmap android-asynctask


【解决方案1】:

我建议您使用Glide 来满足您的目的,它提供了您当前需要的所有工具,例如获取图像以及调整图像大小和缓存。

最好是你自己阅读,否则我需要实现整个解决方案。

【讨论】:

  • 谢谢你的回答,我想问一下我们不需要在 glide 库中使用 AsyncTask
【解决方案2】:

您可以在代码中像这样使用Glide library

ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("your image url").into(imageView);

它使用起来简单方便,有助于在您的应用中更好地执行。

【讨论】:

  • 如何在我的片段活动中添加滑翔库
  • 使用上面提到的代码或者库中有一个可用的演示。您可以在这里与我分享您的代码,我可以帮助您。
  • 我在我的适配器中使用此代码。 Glide.with(contrxt).load(songs.getArtWork).asBitmap().into(imageView)。图像字段中没有显示任何内容
  • 只需使用此代码并确保图像链接正常工作,并且您已在清单文件中授予 Internet 权限。 Glide.with(context).load("你的图片网址").into(holder.imageView);
  • 我使用了这个,但它没有从 ALBUM_ID 检索图像
【解决方案3】:

我找到了获取专辑封面的最佳方法

        Glide.with(mContext)
            .load(getAlbumArtUri(song.getArtWork()))
            .placeholder(R.drawable.no_cover)
            .override(120,120)
            .into(holder.albumArt);

private static Uri getAlbumArtUri(long albumId) {
  return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
}

【讨论】:

    猜你喜欢
    • 2012-07-20
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多