我是android的初学者。我在 2 个 .java 文件中有 2 个类。第一个:Mainacivity 和第二个:ImageDownloader。imagedownloader 用它的函数 getBitmapFromURL(String url) 下载位图,我给这个函数提供了字符串,它运行良好,但我想一个接一个地下载超过 1 个位图。我的主要活动:
public class MainActivity extends Activity implements View.OnClickListener
{
private Button download, downloadBG, save;
private ImageView img;
private ProgressBar pb;
private EditText etUrl;
private TextView percent;
private ImageDownloader mDownloader;
private static Bitmap bmp;
private FileOutputStream fos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*--- initialize layout compinents ---*/
private void initViews() {
download = (Button) findViewById(R.id.btnDownload);
downloadBG = (Button) findViewById(R.id.btnDownloadBackground);
save = (Button) findViewById(R.id.btnSave);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
download.setOnClickListener(this);
downloadBG.setOnClickListener(this);
save.setOnClickListener(this);
save.setEnabled(false);
img = (ImageView) findViewById(R.id.image);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
etUrl = (EditText) findViewById(R.id.etUrl);
percent = (TextView) findViewById(R.id.tvPercent);
percent.setVisibility(View.INVISIBLE);
}
@Override
public void onClick(View v) {
/*--- determine which button was clicked ---*/
switch (v.getId())
{
case R.id.btnDownload:
{
/*--- we use trim() to remove whitespaces which could be entered ---*/
bmp = ImageDownloader.getBitmapFromURL(URLbuilder(0, 0, 0));
img.setImageBitmap(bmp);
save.setEnabled(true);
break;
}
case R.id.btnDownloadBackground:
for(int a = 0 ; a < 4 ; a++)
{
/*--- check whether there is some Text entered ---*/
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(URLbuilder(a, a, a), a,pb, save, img, percent, MainActivity.this, bmp, new ImageLoaderListener() {
@Override
public void onImageDownloaded(Bitmap bmp) {
MainActivity.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
break;
}
}
public String URLbuilder(int x , int y , int z)
{
String myurl = "http://khm0.google.com/kh/v=132&hl=EN&x={0}&y={1}&z={2}&s=";
String.format(myurl, x,y,z);
return String.format(myurl, x,y,z);
}
}
如果我点击 DownloadBackground 按钮,它应该从它的 url 下载 4 位图。我知道每次下载都需要一些时间,但在第一个位图下载之前我无法停止此功能。我的图片下载器:
public class ImageDownloader extends AsyncTask<Void, Integer, Void>
{
private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
FileOutputStream fos;
int Counter = 0;
/*--- constructor ---*/
public ImageDownloader(String url,int counter, ProgressBar pb, Button save,
ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
this.url = url;
this.pb = pb;
this.save = save;
this.c = c;
this.img = img;
this.percent = percent;
this.bmp = bmp;
this.listener = listener;
//this.Counter = Integer.toString(counter);
}
/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity.
* Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {
void onImageDownloaded(Bitmap bmp);
}
@Override
protected void onPreExecute() {
progress = 0;
pb.setVisibility(View.VISIBLE);
percent.setVisibility(View.VISIBLE);
Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
bmp = getBitmapFromURL(url);
while (progress < 100) {
progress += 1;
publishProgress(progress);
/*--- an image download usually happens very fast so you would not notice
* how the ProgressBar jumps from 0 to 100 percent. You can use the method below
* to visually "slow down" the download and see the progress bein updated ---*/
//SystemClock.sleep(200);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
/*--- show download progress on main UI thread---*/
pb.setProgress(values[0]);
percent.setText(values[0] + "%");
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onImageDownloaded(bmp);
}
img.setImageBitmap(bmp);
saveImageToSD();
save.setEnabled(true);
Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
public static Bitmap getBitmapFromURL(String link)
{
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("getBmpFromUrl error: ", e.getMessage().toString());
return null;
}
}
private void saveImageToSD()
{
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDownloadedImage" + Integer.toString(Counter) + ".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Counter++;
}
我需要在主要活动中的 onclick 方法中停止 for 循环,直到下载每个图像。我做了我知道的每一件事,但每次它都崩溃了。后来我必须把图像下载器放在一个线程中,但我不知道如何停止线程一段时间。请帮助我。泰