Java 如何使用服务在SD卡中存储图像?

Java 如何使用服务在SD卡中存储图像?,java,android,android-intent,Java,Android,Android Intent,我正在获取图像URL并在GridView中设置该URL。它在GridView中成功显示了我。但我还想使用服务将该图像存储在SD卡中。如何操作。请有人帮助我解决此问题。谢谢 public class MainActivity extends Activity { ListView list; GridView gv; String TAG = "GRIDVIEW"; LazyAdapter adapter; Bitmap bitmap; @Override public void onCrea

我正在获取图像URL并在GridView中设置该URL。它在GridView中成功显示了我。但我还想使用服务将该图像存储在SD卡中。如何操作。请有人帮助我解决此问题。谢谢

public class MainActivity extends Activity {

ListView list;
GridView gv;
String TAG = "GRIDVIEW";
LazyAdapter adapter;
Bitmap bitmap;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this, MyService.class));
    new loading().execute();
    // gv = (GridView) findViewById(R.id.grid_view);
    // startService(new Intent(MainActivity.this, MyService.class));
    // gv = (GridView) findViewById(R.id.grid_view);
    // gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
    // gv.setHorizontalSpacing(10);
    // gv.setVerticalSpacing(40);

    // gv.setGravity(200);

}

ProgressDialog mprogress;

private class loading extends AsyncTask<String, Void, String> {

    protected void onPreExecute() {
        mprogress = new ProgressDialog(MainActivity.this);
        mprogress.setMessage("Loading...");
        mprogress.show();

        super.onPreExecute();

    }

    protected String doInBackground(String... params) {
        // startService(new Intent(MainActivity.this, MyService.class));
        return null;
    }

    protected void onPostExecute(String result) {
        getGirdview();
        mprogress.dismiss();
        super.onPostExecute(result);
    }

    private void getGirdview() {
        gv = (GridView) findViewById(R.id.grid_view);
        gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
        gv.setHorizontalSpacing(10);
        gv.setVerticalSpacing(40);
    }

}

public String[] mStrings = {

        "http://a1.twimg.com/profile_images/97470808/icon_normal.png",
        "http://a3.twimg.com/profile_images/511790713/AG.png",
        };
    }

public class MyService extends Service {

String TAG = "GRIDVIEW";
Bitmap bitmap;
MainActivity mclass = new MainActivity();

public void onStart(Intent intent, int startId) {

    for (int i = 0; i < mclass.mStrings.length; i++) {

        String str = mclass.mStrings[i];
        bitmap = DownloadImage(str);
        // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
        // R.drawable.ic_launcher);
        // File sd = Environment.getExternalStorageDirectory();
        File storagePath = new File(
                Environment.getExternalStorageDirectory(), "Wallpaper");
        storagePath.mkdirs();

        String fileName = "test" + i + ".png";
        File dest = new File(storagePath, fileName);
        try {
            FileOutputStream out;
            out = new FileOutputStream(dest);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    super.onStart(intent, startId);

}

public int onStartCommand(Intent intent, int flags, int startId) {

    // for (int i = 0; i < mStrings.length; i++) {
    //
    // String str = mStrings[i];
    // bitmap = DownloadImage(str);
    // // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
    // // R.drawable.ic_launcher);
    // // File sd = Environment.getExternalStorageDirectory();
    // File storagePath = new File(
    // Environment.getExternalStorageDirectory(), "Wallpaper");
    // storagePath.mkdirs();
    //
    // String fileName = "test" + i + ".png";
    // File dest = new File(storagePath, fileName);
    // try {
    // FileOutputStream out;
    // out = new FileOutputStream(dest);
    // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    // out.flush();
    // out.close();
    // } catch (FileNotFoundException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }

    return super.onStartCommand(intent, flags, startId);
}

public IBinder onBind(Intent intent) {

    return null;
}

// public void onStart(Intent intent, int startId) {
//
// for (int i = 0; i < mStrings.length; i++) {
//
// String str = mStrings[i];
// bitmap = DownloadImage(str);
// // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// // R.drawable.ic_launcher);
// // File sd = Environment.getExternalStorageDirectory();
// File storagePath = new File(
// Environment.getExternalStorageDirectory(), "Wallpaper");
// storagePath.mkdirs();
//
// String fileName = "test" + i + ".png";
// File dest = new File(storagePath, fileName);
// try {
// FileOutputStream out;
// out = new FileOutputStream(dest);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// out.flush();
// out.close();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// super.onStart(intent, startId);
// }

private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Toast.makeText(MyService.this, "Image is Downloaded",
            Toast.LENGTH_SHORT).show();
    return bitmap;
}

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
        .synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;

public ImageLoader(Context context) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.ic_launcher;

public void DisplayImage(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}



private void queuePhoto(String url, ImageView imageView) {
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    // from web
    try {
        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl
                .openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        FileInputStream stream1 = new FileInputStream(f);
        BitmapFactory.decodeStream(stream1, null, o);
        stream1.close();

        // Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE = 70;
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
                    || height_tmp / 2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        FileInputStream stream2 = new FileInputStream(f);
        Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
        stream2.close();
        return bitmap;
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;

    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;

    PhotosLoader(PhotoToLoad photoToLoad) {
        this.photoToLoad = photoToLoad;
    }

    @Override
    public void run() {
        try {
            if (imageViewReused(photoToLoad))
                return;
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            Activity a = (Activity) photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag = imageViews.get(photoToLoad.imageView);
    if (tag == null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
        bitmap = b;
        photoToLoad = p;
    }

    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        if (bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}

环境。getExternalStorage()将返回sd卡位置。获得位置后,可以根据需要创建目录。看起来你正在这么做……那么你遇到了什么问题


另外,使用IntentService而不是服务……它为您解决了大部分管道工程。

可能重复的是,我得到了它。但我想通过使用服务来实现。如何实现。我想使用服务将图像存储在SD卡中。我尝试了很多。但仍然没有得到它。请帮助我实现这一点。
public class LazyAdapter extends BaseAdapter {

private Context mContext;
String TAG = "GridView";
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
Bitmap bitmap;

public LazyAdapter(Activity a, String[] d) {
    activity = a;
    data = d;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader = new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.length;
}

public Object getItem(int position) {
    return data;
}

public long getItemId(int position) {
    return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.item, null);
    }

    // TextView txt_name = (TextView) convertView.findViewById(R.id.text);
    // txt_name.setText("item" + position);

    ImageView image = (ImageView) convertView.findViewById(R.id.image);
    // image.setTag(data[position]);

    imageLoader.DisplayImage(data[position], image);

    return convertView;
}