从firebase数据库设置图像的墙纸按钮

时间:2018-11-06 01:20:15

标签: java android firebase firebase-realtime-database

我正在尝试向我的应用程序添加一个设置墙纸按钮,以便在我从Firebase数据库中提取图像时设置墙纸。到目前为止,这就是我所拥有的。我将按钮设置为自动显示在每个墙纸快照上。我过去曾在图片存储在手机上时设置过墙纸,但似乎无法弄清楚如何从Firebase中提取图片时如何设置墙纸。

public class WallpapersAdapter extends RecyclerView.Adapter<WallpapersAdapter.WallpaperViewHolder> {


private Context mCtx;
private List<Wallpaper> wallpaperList;




public WallpapersAdapter(Context mCtx, List<Wallpaper> wallpaperList) {
    this.mCtx = mCtx;
    this.wallpaperList = wallpaperList;

}

@NonNull
@Override
public WallpaperViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_wallpapers, parent, false);
    return new WallpaperViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull WallpaperViewHolder holder, int position) {

    Wallpaper w = wallpaperList.get(position);
    holder.textView.setText(w.title);
    Glide.with(mCtx)
            .load(w.url)
            .into(holder.imageView);
    if(w.isFavorite){
        holder.checkBoxFav.setChecked(true);
    }
}

@Override
public int getItemCount() {
    return wallpaperList.size();
}

class WallpaperViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, CompoundButton.OnCheckedChangeListener{

    TextView textView;
    ImageView imageView;
    CheckBox checkBoxFav;
    ImageButton buttonShare, buttonDownload;
    Button setWallpaper;



    public WallpaperViewHolder(View itemView) {
        super(itemView);

        textView = itemView.findViewById(R.id.text_view_title);
        imageView = itemView.findViewById(R.id.image_view);
        checkBoxFav = itemView.findViewById(R.id.checkbox_favorite);
        buttonShare = itemView.findViewById(R.id.button_share);
        buttonDownload = itemView.findViewById(R.id.button_download);
        setWallpaper = itemView.findViewById(R.id.set_wallpaper);
        setWallpaper.setOnClickListener(this);
        checkBoxFav.setOnCheckedChangeListener(this);
        /*buttonShare.setOnClickListener(this);*/
        /*buttonDownload.setOnClickListener(this);*/





    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.button_share:

                shareWallpaper(wallpaperList.get(getAdapterPosition()));
                break;
            case R.id.button_download:

                downloadWallpaper(wallpaperList.get(getAdapterPosition()));

                break;

            case R.id.set_wallpaper:

                setWallpaper(wallpaperList.get(getAdapterPosition()));

                break;


        }





    }






    private void shareWallpaper(Wallpaper w){
        ((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);

        Glide.with(mCtx)
                .asBitmap()
                .load(w.url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        ((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);

                        Intent intent = new Intent(Intent.ACTION_SEND);
                        intent.setType("image/*");
                        intent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(resource));
                        mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
                    }



                });


    }

    private Uri getLocalBitmapUri(Bitmap bmp){
        Uri bmpUri = null;


        try {
            File file = new File(mCtx.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
                    "the_wallpaper_app_" + System.currentTimeMillis() + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            bmpUri = Uri.fromFile(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }


    private void downloadWallpaper(final Wallpaper wallpaper){
        ((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);

        Glide.with(mCtx)
                .asBitmap()
                .load(wallpaper.url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        ((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);

                        Intent intent = new Intent(Intent.ACTION_VIEW);

                        Uri uri = saveWallpaperAndGetUri(resource, wallpaper.id);
                        if(uri != null){
                            intent.setDataAndType(uri, "image/*");
                            mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
                        }
                    }

                });
    }

    private Uri saveWallpaperAndGetUri(Bitmap bitmap, String id){
        if(ContextCompat.checkSelfPermission(mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){

            if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

                Uri uri = Uri.fromParts("package", mCtx.getPackageName(), null);
                intent.setData(uri);

                mCtx.startActivity(intent);

            }else{
                ActivityCompat.requestPermissions((Activity) mCtx, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100 );
            }
            return null;

        }

        File folder = new File(Environment.getExternalStorageDirectory().toString() + "/the_wallpaper_app" );
        folder.mkdirs();

        File file = new File(folder, id + ".jpg" );

        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();

            return Uri.fromFile(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;


    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        if(FirebaseAuth.getInstance().getCurrentUser() == null){

            Toast.makeText(mCtx, "Please login first", Toast.LENGTH_LONG).show();
            compoundButton.setChecked(false);
            return;
        }



        int position = getAdapterPosition();
        Wallpaper w = wallpaperList.get(position);

        DatabaseReference dbFavs = FirebaseDatabase.getInstance().getReference("users")
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .child("favorites")
                .child(w.category);



        if(b){
            dbFavs.child(w.id).setValue(w);
        }else{
            dbFavs.child(w.id).setValue(null);
        }

    }


}

private void setWallpaper(Wallpaper set) {




    };



}

}

1 个答案:

答案 0 :(得分:0)

您不能直接从数据库中将图像设置为Android设备上的墙纸,为此首先必须将图像下载到设备上,然后才能将其设置为背景墙纸。

您可以使用createTempFile(String prefix, String suffix)在默认的临时文件目录中创建一个空文件,并使用给定的前缀和后缀生成其名称。

Read more about this here.

如果您希望将文件存储在应用目录中,则可以使用如下代码:

File dir = new File(Environment.getExternalStorageDirectory(), "dir_name");
// Create dir if not exists
if(!dir.exists()) dir.mkdirs();

File mFile = new File(dir, "file_name");

也可以从文件中获取位图并将其用作墙纸,您可以使用类似于以下代码:

Bitmap bitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());

//after converting it to bitmapDrawable you can set it as background using this

getWindow().setBackgroundDrawable

您也可以像这样使用WallpaperManager

WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);