使用AsyncTask中的Activity中的变量

时间:2017-07-16 11:19:59

标签: android android-asynctask

我做了一个AsyncTask,它使用文件中的位图来更改设备壁纸,但我有多个不同的按钮需要做同样的事情(从文件中更改壁纸)但每个文件夹的文件名不同(用作每个按钮的壁纸。

所以可以在启动AsyncTask的代码中包含一些东西,告诉它要查找哪个文件对于每个按钮都不同。

我对此很陌生,所以感谢任何帮助。

其中一个按钮:

    Button setwallpaper1button = (Button) myView.findViewById(R.id.setwallpaper1button);
    setwallpaper1button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!new File(Environment.getExternalStorageDirectory().toString() + "/Directory/Wallpaper_1.jpg").exists()) {
                Snackbar.make(myView, "Please Download Wallpaper First.", Snackbar.LENGTH_LONG).show();
            }
            else {
                new SetWallpaperTask(getActivity()).execute( // I think something needs to go here // );
            }
        }
    });

来自AsyncTask:

    @Override
protected String doInBackground(String... args) {
        bmImg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + "/Directory/" + "// This is where the variable thats different for each button needs to go //");
    return null;
    }

1 个答案:

答案 0 :(得分:1)

首先,您需要将资源映射到屏幕上的按钮。让我们假设您在屏幕上有三个按钮。

button1.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) {
     String imageName = "Wallpaper_1.jpg";
        if(!new File(Environment.getExternalStorageDirectory().toString() + "/Directory/"+imageName ).exists()) {
            Snackbar.make(myView, "Please Download Wallpaper First.", Snackbar.LENGTH_LONG).show(); 
        } 
        else { 
            new SetWallpaperTask(getActivity()).execute( imageName  ); 
        } 
    } 
}); 

 button2.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) {
     String imageName = "Wallpaper_2.jpg";
        if(!new File(Environment.getExternalStorageDirectory().toString() + "/Directory/"+imageName).exists()) {
            Snackbar.make(myView, "Please Download Wallpaper First.", Snackbar.LENGTH_LONG).show(); 
        } 
        else { 
            new SetWallpaperTask(getActivity()).execute( imageName  ); 
        } 
    } 
}); 

然后在你的asynctask的doInBackground

@Override 
protected String doInBackground(String... args) {
    bmImg = 
 BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + "/Directory/" + args[0]);
return null; 
}