Android: take a 'screenshot' of a web page from a background service? - android

I have a URL for a web page, and I want to take a 'screenshot' of this web page in the background, eg. in a Service, and without showing a UI to the user.
I have tried to create a WebView in my Service, and then use the capturePicture() method to get the screenshot when the page has finished loading, but the created Picture (and the Bitmap I create from it ) is always empty. (This works perfectly in a normal Activity, but not in my background Service).
Any way to get this to work, or an alternative way to get a 'screenshot' of a webpage without having a UI ?

Note: This answer is old - the latest Android version I've tried this on is 4.4, YMMV on other Android versions or devices I did not test this on... This is also a super-kludgy hack - nowdays I'd recommend using a web service / API for this.
Figured it out, I have to set the 'size' of the WebView, so that the resulting 'Screenshot' is not 0 x 0 size. Then I have to get the bitmap directly from the WebView's drawing cache, as capturePicture() does not seem to work here.
package com.example.screenshot;
import android.app.*;
import android.content.*;
import android.widget.*;
import android.util.*;
import android.webkit.*;
import android.graphics.*;
import java.io.*;
import android.view.View.*;
import android.os.*;
import android.os.Process;
//this is an example of how to take a screenshot in a background service
//not very elegant, but it works (for me anyway)
public class ScreenshotService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private Message msg;
private WebView webview;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
webview = new WebView(ScreenshotService.this);
//without this toast message, screenshot will be blank, dont ask me why...
Toast.makeText(ScreenshotService.this, "Taking screenshot...", Toast.LENGTH_SHORT).show();
// This is the important code :)
webview.setDrawingCacheEnabled(true);
//width x height of your webview and the resulting screenshot
webview.measure(600, 400);
webview.layout(0, 0, 600, 400);
webview.loadUrl("http://stackoverflow.com");
webview.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//without this method, your app may crash...
}
#Override
public void onPageFinished(WebView view, String url) {
new takeScreenshotTask().execute();
stopSelf();
}
});
}
}
private class takeScreenshotTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void[] p1) {
//allow the webview to render
synchronized (this) {try {wait(350);} catch (InterruptedException e) {}}
//here I save the bitmap to file
Bitmap b = webview.getDrawingCache();
File file = new File("/sdcard/example-screenshot.png");
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
b.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (IOException e) {
Log.e("ScreenshotService", "IOException while trying to save thumbnail, Is /sdcard/ writable?");
e.printStackTrace();
}
Toast.makeText(ScreenshotService.this, "Screenshot taken", Toast.LENGTH_SHORT).show();
return null;
}
}
//service related stuff below, its probably easyer to use intentService...
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
#Override
public void onDestroy() {
}
}

Related

Android update UI from Thread (Handler maybe not an option?)

This is a common question, and I have read up on the various ways of handling it, but each on seems to fall short for what I am trying to do, which is essentially be a good OO-Citizen.
I have an Activity that invokes a CommunicationManager, which basically polls a TCP socket for data. When the CommunicationManager receives data, it throws a custom event (containing the string it just fetched), which is handled by the Activity. I am doing this, A) because other classes will depend on that data, not just the Activity, and B) because the polling is asynchronous, and should fire an event when it receives results.
My problem lies in that I need to surface those results into a TextView on the UI. I have the polling mechanism all set up, it fires every 1000ms, and invokes the event handler on the Activity. However, the UI never updates.
Assumedly this is a thread issue and the UI thread is not the one getting the change to the TextView, but how do I do this?? I have tried using a Handler, but am not sure where to put it, and when I did get it compiling it never updated the UI.
This seems relatively trivial if everything was done within the Activity, but adding in this other class (CommunicationManager) and the event is making it very confusing for me.
Here is what I have so far:
ACTIVITY (polling is invoked by clicking a button on the UI):
public void onClick(View v) {
if (v.getId() == R.id.testUDPBtn) {
statusText.setText("");
commMgr = new CommunicationManager();
commMgr.addEventListener(this);
MediaPositionPollThread poller = new MediaPositionPollThread(commMgr);
poller.startPolling();
}
}
#Override
public void handleMediaPositionFoundEvent(MediaPositionFoundEvent e) {
statusText.append(e.userData);
}
THREAD:
class MediaPositionPollThread extends Thread {
private CommunicationManager commManager;
private static final String TAG = "MediaPositionPollThread";
private boolean isPolling = false;
public MediaPositionPollThread(CommunicationManager cm) {
commManager = cm;
}
public void startPolling() {
isPolling = true;
this.run();
}
public void stopPolling() {
isPolling = false;
}
#Override
public void run() {
while (isPolling) {
try {
commManager.getCurrentMediaPosition();
Thread.sleep(1000);
}
catch (InterruptedException e) {
Log.d(TAG, "EXCEPTION: " + e.getMessage());
}
}
}
}
COMMUNUCATION MANAGER:
public void getCurrentMediaPosition() {
PrintWriter outStream;
BufferedReader inStream;
String resultString = "";
try {
outStream = new PrintWriter(tcpSocket.getOutputStream(), true);
outStream.println("GET?current_pts");
inStream = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
resultString = inStream.readLine();
fireEventWithData(resultString);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void addEventListener(MediaPositionFoundEventListener listener) {
_listeners.add(listener);
}
public synchronized void removeEventListener(MediaPositionFoundEventListener listener) {
_listeners.remove(listener);
}
private synchronized void fireEventWithData(String outputString) {
MediaPositionFoundEvent evt = new MediaPositionFoundEvent(this);
evt.userData = outputString;
Iterator<MediaPositionFoundEventListener> i = _listeners.iterator();
while(i.hasNext()) {
((MediaPositionFoundEventListener) i.next()).handleMediaPositionFoundEvent(evt);
}
}
So I have the Activity making a thread that gets executed every second, calling CommunicationManager >> getCurrentMediaPosition, which in turn fires the MediaPositionFoundEvent, which is handled by the Activity and updates the TextView (statusText) on the screen.
Everything works except the screen not updating. I have tried runOnUiThread, and a Handler, but am obviously not getting it right.
Thanks in advance for any insight or solutions!
In your Activity class, add a private Handler _handler,
Initialize it in your onCreate Activity method,
and change your handleMediaPositionFoundEvent method to
#Override public void handleMediaPositionFoundEvent(MediaPositionFoundEvent e) {
_handler.post(new Runnable(){
public void run(){
statusText.append(e.userData);
});
}
}
It looks like your blocking the UI thread with your custom Thread. Please update this method to call start() vs run().
public void startPolling() {
isPolling = true;
this.start();
}

How to kill a TimerTask created from an IntentService with a button

I'm making a Cloud Service that uses a standard HTTP get to get commands. I use a service (extending class IntentService as opposed to Service) to keep things in sync. I have the checking going on in a TimerTask firing off every 3 seconds. The problem is that when the user goes back to the activity to turn it off if they want, they press a toggle button. How do I tell the TimerTask (or the IntentService running a timer task) to stop and start it?
The service itself is getting destroyed after it handles the intent and creates the task, so would a Service be more appropriate for this than an IntentService? Even if thats the case, the question about stopping and starting the TimerTask remains.
Here's the code to the intentservice:
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.widget.*;
public class syncservice extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public syncservice() {
super("syncservice");
}
public static final String PREFS_NAME = "prefcs";
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String uid = intent.getExtras().get("uid").toString();
final String dvname = intent.getExtras().get("dvname").toString();
final long period = intent.getExtras().getLong("period");
final Context ctx = getApplicationContext();
final Toast toast = Toast.makeText(ctx,"An error occured with the service. It will automatically turn off.", 0);
final Handler handler = new Handler();
TimerTask timertask = new TimerTask () {
#Override
public void run() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("doservice", false)) {
String command = netread("url here");
//TODO Parse command from Pulling
if (command.contains("<")) {
//TODO what to do if an error occurred (exceptions already caught
Runnable showerrormessage = new Runnable() {
public void run() {
toast.makeText(ctx,"new text",0);
toast.show();
}
};
handler.post(showerrormessage);
}
}
}
};
Timer timer = new Timer();
timer.schedule(timertask,0,period);
return super.onStartCommand(intent,flags,startId);
}
public void onDestroy() {
Toast.makeText(getApplicationContext(), "The Service has died", Toast.LENGTH_SHORT).show();
return;
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "Intent Handled", 0).show();
}
public final String netread(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
return page;
} catch (ClientProtocolException e) {
//Toast.makeText(getApplicationContext(),"Client Protocol Exception! Try again.",0).show();
return "<";
} catch (IOException e) {
//Toast.makeText(getApplicationContext(),"IO Exception! Make sure you are connected to the internet and try again.", 0).show();
return "<";
}
}
}
Thanks a bunch for helping me out!
For what you're trying to do, Handler may be more useful. That link BTW shows also how to stop it from the UI.

Implementation of IntentService using LinkedBlockingQueue?

I'm trying to download multiple files using IntentService. The IntentService donwloads them okey as expected one at a time, the only problem is that when the Internet is down the intent service will not stop the donwload rather it will get stuck on the current thread. If I manage to stop the current thread it will continue running the other threads stored in its queue even though the internet connection is down.
It was suggested in another post that I use LinkedBlockingQueue and create my own Worker thread that constantly checks this queue for new threads. Now I know there are some increased overheads and thus performance issues when creating and destroying threads but that's not a concern in my case.
At this point, All I want to do is understand how IntentService works which as of yet I don't (and I have looked at the code) and then come up with my own implementation for it using LinkedBlockingQueue controlled by a Worker thread. Has anyone done this before ? Could provide a working example, if you feel uncomfortable providing the source code, pseudo code is fine by me. Thanks!
UPDATE: I eventually implemented my own Intent Service using a thread that has a looper which checks the queue which in turn stores the intents passed from the startService(intent).
public class MyIntentService extends Service {
private BlockingQueue<Download> queue = new LinkedBlockingQueue<Download>();
public MyIntentService(){
super();
}
#Override
public void onCreate() {
super.onCreate();
new Thread(queueController).start();
Log.e("onCreate","onCreate is running again");
}
boolean killed = false;
Runnable queueController = new Runnable() {
public void run() {
while (true) {
try {
Download d =queue.take();
if (killed) {
break;
}
else {
d.downloadFile();
Log.e("QueueInfo","queue size: " + queue.size());
}
}
catch (InterruptedException e) {
break;
}
}
Log.e("queueController", "queueController has finished processing");
Log.e("QueueInfo","queue size: " + queue.toString());
}
};
class Download {
String name;
//Download files process
void downloadFile() {
//Download code here
}
Log.e("Download","Download being processed is: " + name);
}
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
}
public void killService(){
killed = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Download d = new Download();
d.setName(intent.getStringExtra("VIDEOS"));
queue.add(d);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("stopSelf","stopSelf has been just called to stop the Service");
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm not so sure about the START_NOT_STICKY in the onStartCommand() method. If it's the right flag to return or not. Any clarification on that would be appreciated!
UPDATE: I eventually implemented my own Intent Service using a thread that has a looper which checks the queue which in turn stores the intents passed from the startService(intent).
public class MyIntentService extends Service {
private BlockingQueue<Download> queue = new LinkedBlockingQueue<Download>();
public MyIntentService(){
super();
}
#Override
public void onCreate() {
super.onCreate();
new Thread(queueController).start();
Log.e("onCreate","onCreate is running again");
}
boolean killed = false;
Runnable queueController = new Runnable() {
public void run() {
while (true) {
try {
Download d =queue.take();
if (killed) {
break;
}
else {
d.downloadFile();
Log.e("QueueInfo","queue size: " + queue.size());
}
}
catch (InterruptedException e) {
break;
}
}
Log.e("queueController", "queueController has finished processing");
Log.e("QueueInfo","queue size: " + queue.toString());
}
};
class Download {
String name;
//Download files process
void downloadFile() {
//Download code here
}
Log.e("Download","Download being processed is: " + name);
}
public void setName(String n){
name = n;
}

Need Help in Downloading in Background Images in Android?

I have an image view , i had written swiping , at that time of swiping,the images are downloading from Internet, so i thought i have to download the images in the background before swiping , for that which i need to use asynctask or Service or IntentService, all these will help in downloading and storing in data/data/mypackages , but still swiping gets slow in my case any idea, also convey me which one is best one, is it i'm calling in a right way
1. asynctask
2. services
3. Intent Service as shown below,
i m confused which one is right method because still my problem not solved
Here's asynctask code sample snippet
public class Demo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new FirstTask().execute(); // calling Asynctask here
}
}
Async Task code
private class FirstTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(Catalogue.this);
int temp = 0;
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
//this.dialog.show();
System.gc();
Toast.makeText(Catalogue.this, "My Async Created",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
Looper.prepare();
try {
myddownloadmethod();// calling my download method
} catch (Exception e) {
Util.trace("Error in Async"+e.getMessage());
}
Looper.loop();
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
Toast.makeText(Catalogue.this, "My Async destroyed",
Toast.LENGTH_LONG).show();
Toast.makeText(Catalogue.this, "count" + temp,
Toast.LENGTH_LONG).show();
this.dialog.dismiss();
}
}
}
Here's My Service sinppet
public class MyService extends Service implements Runnable
{ #Override
public void onCreate() {
super.onCreate();
Thread mythread = new Thread(this);
mythread.start();
}
public void run() {
Looper.prepare();
try {
myddownloadmethod();// calling my download method
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Looper.loop();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Invoking Service
public class ServicesDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
}
}
Here's IntentService Code
public class Downloader extends IntentService {
public Downloader() {
super("Downloader");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onHandleIntent(Intent i) {
try {
myddownloadmethod();// calling my download method
} catch (Exception e1) {
// TODO Auto-generated catch block
Log.d("Error",e1.getMessage());
}
}
}
Calling IntentService from MyActivity
public class ServicesDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i1=new Intent(this, Downloader.class);
startService(i1);
}
}
The best way to download it using the service like i have done to download the file from server and put in SD card also use the notification for it.
It is quite long code but i think the perfect one,if did not understand any thing then please go to android developer blog for services.
public class DownloadService extends Service{
SharedPreferences preferences;
private static final String DOCUMENT_VIEW_STATE_PREFERENCES = "DjvuDocumentViewState";
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private NotificationManager mNM;
String downloadUrl;
public static boolean serviceState=false;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
downloadFile();
showNotification(getResources().getString(R.string.notification_catalog_downloaded),"VVS");
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
serviceState=true;
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
HandlerThread thread = new HandlerThread("ServiceStartArguments",1);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SERVICE-ONCOMMAND","onStartCommand");
Bundle extra = intent.getExtras();
if(extra != null){
String downloadUrl = extra.getString("downloadUrl");
Log.d("URL",downloadUrl);
this.downloadUrl=downloadUrl;
}
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public void onDestroy() {
Log.d("SERVICE-DESTROY","DESTORY");
serviceState=false;
//Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
public void downloadFile(){
downloadFile(this.downloadUrl,fileName);
}
void showNotification(String message,String title) {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = message;
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.icon, "vvs",
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, HomeScreenActivity.class);
intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
//The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this.getBaseContext(), 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title,
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.app_name, notification);
}
public void downloadFile(String fileURL, String fileName) {
StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
double avail_sd_space = (double)stat_fs.getAvailableBlocks() *(double)stat_fs.getBlockSize();
//double GB_Available = (avail_sd_space / 1073741824);
double MB_Available = (avail_sd_space / 10485783);
//System.out.println("Available MB : " + MB_Available);
Log.d("MB",""+MB_Available);
try {
File root =new File(Environment.getExternalStorageDirectory()+"/vvveksperten");
if(root.exists() && root.isDirectory()) {
}else{
root.mkdir();
}
Log.d("CURRENT PATH",root.getPath());
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int fileSize = c.getContentLength()/1048576;
Log.d("FILESIZE",""+fileSize);
if(MB_Available <= fileSize ){
this.showNotification(getResources().getString(R.string.notification_no_memory),getResources().getString(R.string.notification_error));
c.disconnect();
return;
}
FileOutputStream f = new FileOutputStream(new File(root.getPath(), fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
File file = new File(root.getAbsolutePath() + "/" + "some.pdf");
if(file.exists()){
file.delete();
Log.d("FILE-DELETE","YES");
}else{
Log.d("FILE-DELETE","NO");
}
File from =new File(root.getAbsolutePath() + "/" + fileName);
File to = new File(root.getAbsolutePath() + "/" + "some.pdf");
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
For anyone running into this question later, take a look at the async download mechanism used in the android sample code for the project com.example.android.bitmapfun.ui.ImageGridActivity. It downloads images asynchronously and also caches them for offline display in an ImageView. Folks have wrapped their code around this one and made image loading libraries of their own. These libraries use an AsyncTask instead of a service. Async tasks are expected to wrap up their work within a couple of seconds.
If you are looking to download something larger, I'd recommend the DownloadManager that is available since API 9 instead of using services. There is a lot of code in there that adds resilience to the download.
The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots. Instances of this class should be obtained through getSystemService(String) by passing DOWNLOAD_SERVICE. Apps that request downloads through this API should register a broadcast receiver for ACTION_NOTIFICATION_CLICKED to appropriately handle when the user clicks on a running download in a notification or from the downloads UI. Note that the application must have the INTERNET permission to use this class.
You are probably over engineering this. I have implemented swiping with dynamically loading images and I just a use a simple utility class that does it all for me via static method call.
Try this class:
package com.beget.consumer.util;
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
public class DrawableLoader {
private final Map<String, Drawable> drawableMap;
private WeakReference<ImageView> imageViewReference;
public DrawableLoader() {
drawableMap = new HashMap<String, Drawable>();
}
public Drawable fetchDrawable(String urlString) {
if (drawableMap.containsKey(urlString)) {
return drawableMap.get(urlString);
}
Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawableMap.put(urlString, drawable);
Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
+ drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
+ drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
return drawable;
} catch (MalformedURLException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
}
}
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
if (drawableMap.containsKey(urlString)) {
imageViewReference.get().setImageDrawable(drawableMap.get(urlString));
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
imageViewReference.get().setImageDrawable((Drawable) message.obj);
}
};
Thread thread = new Thread() {
#Override
public void run() {
//TODO : set imageView to a "pending" image
Drawable drawable = fetchDrawable(urlString);
Message message = handler.obtainMessage(1, drawable);
handler.sendMessage(message);
}
};
thread.start();
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
This is all you need. Then when you need to load an image, you call:
fetchDrawableOnThread("http://path/to/your/image.jpg", yourImageViewReference);
That's it.
If you have an URL from a JSON object, parse the URL into your string so:
String url = jsonObj.getString("url");
Then call fetchDrawableOnThread(url, yourImageViewReference);
Use volley.
Using volley network image view you can do this
we use latest architecure components here.We make some observers with live data for some flag that represents download status.In service we download the image and completing we update the live data so that the observers method automatically called

Android Download Service [duplicate]

I have an image view , i had written swiping , at that time of swiping,the images are downloading from Internet, so i thought i have to download the images in the background before swiping , for that which i need to use asynctask or Service or IntentService, all these will help in downloading and storing in data/data/mypackages , but still swiping gets slow in my case any idea, also convey me which one is best one, is it i'm calling in a right way
1. asynctask
2. services
3. Intent Service as shown below,
i m confused which one is right method because still my problem not solved
Here's asynctask code sample snippet
public class Demo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new FirstTask().execute(); // calling Asynctask here
}
}
Async Task code
private class FirstTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(Catalogue.this);
int temp = 0;
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
//this.dialog.show();
System.gc();
Toast.makeText(Catalogue.this, "My Async Created",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
Looper.prepare();
try {
myddownloadmethod();// calling my download method
} catch (Exception e) {
Util.trace("Error in Async"+e.getMessage());
}
Looper.loop();
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
Toast.makeText(Catalogue.this, "My Async destroyed",
Toast.LENGTH_LONG).show();
Toast.makeText(Catalogue.this, "count" + temp,
Toast.LENGTH_LONG).show();
this.dialog.dismiss();
}
}
}
Here's My Service sinppet
public class MyService extends Service implements Runnable
{ #Override
public void onCreate() {
super.onCreate();
Thread mythread = new Thread(this);
mythread.start();
}
public void run() {
Looper.prepare();
try {
myddownloadmethod();// calling my download method
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Looper.loop();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Invoking Service
public class ServicesDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
}
}
Here's IntentService Code
public class Downloader extends IntentService {
public Downloader() {
super("Downloader");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onHandleIntent(Intent i) {
try {
myddownloadmethod();// calling my download method
} catch (Exception e1) {
// TODO Auto-generated catch block
Log.d("Error",e1.getMessage());
}
}
}
Calling IntentService from MyActivity
public class ServicesDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i1=new Intent(this, Downloader.class);
startService(i1);
}
}
The best way to download it using the service like i have done to download the file from server and put in SD card also use the notification for it.
It is quite long code but i think the perfect one,if did not understand any thing then please go to android developer blog for services.
public class DownloadService extends Service{
SharedPreferences preferences;
private static final String DOCUMENT_VIEW_STATE_PREFERENCES = "DjvuDocumentViewState";
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private NotificationManager mNM;
String downloadUrl;
public static boolean serviceState=false;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
downloadFile();
showNotification(getResources().getString(R.string.notification_catalog_downloaded),"VVS");
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
serviceState=true;
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
HandlerThread thread = new HandlerThread("ServiceStartArguments",1);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SERVICE-ONCOMMAND","onStartCommand");
Bundle extra = intent.getExtras();
if(extra != null){
String downloadUrl = extra.getString("downloadUrl");
Log.d("URL",downloadUrl);
this.downloadUrl=downloadUrl;
}
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
#Override
public void onDestroy() {
Log.d("SERVICE-DESTROY","DESTORY");
serviceState=false;
//Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
public void downloadFile(){
downloadFile(this.downloadUrl,fileName);
}
void showNotification(String message,String title) {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = message;
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.icon, "vvs",
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, HomeScreenActivity.class);
intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
//The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this.getBaseContext(), 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title,
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.app_name, notification);
}
public void downloadFile(String fileURL, String fileName) {
StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
double avail_sd_space = (double)stat_fs.getAvailableBlocks() *(double)stat_fs.getBlockSize();
//double GB_Available = (avail_sd_space / 1073741824);
double MB_Available = (avail_sd_space / 10485783);
//System.out.println("Available MB : " + MB_Available);
Log.d("MB",""+MB_Available);
try {
File root =new File(Environment.getExternalStorageDirectory()+"/vvveksperten");
if(root.exists() && root.isDirectory()) {
}else{
root.mkdir();
}
Log.d("CURRENT PATH",root.getPath());
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int fileSize = c.getContentLength()/1048576;
Log.d("FILESIZE",""+fileSize);
if(MB_Available <= fileSize ){
this.showNotification(getResources().getString(R.string.notification_no_memory),getResources().getString(R.string.notification_error));
c.disconnect();
return;
}
FileOutputStream f = new FileOutputStream(new File(root.getPath(), fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
File file = new File(root.getAbsolutePath() + "/" + "some.pdf");
if(file.exists()){
file.delete();
Log.d("FILE-DELETE","YES");
}else{
Log.d("FILE-DELETE","NO");
}
File from =new File(root.getAbsolutePath() + "/" + fileName);
File to = new File(root.getAbsolutePath() + "/" + "some.pdf");
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
For anyone running into this question later, take a look at the async download mechanism used in the android sample code for the project com.example.android.bitmapfun.ui.ImageGridActivity. It downloads images asynchronously and also caches them for offline display in an ImageView. Folks have wrapped their code around this one and made image loading libraries of their own. These libraries use an AsyncTask instead of a service. Async tasks are expected to wrap up their work within a couple of seconds.
If you are looking to download something larger, I'd recommend the DownloadManager that is available since API 9 instead of using services. There is a lot of code in there that adds resilience to the download.
The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots. Instances of this class should be obtained through getSystemService(String) by passing DOWNLOAD_SERVICE. Apps that request downloads through this API should register a broadcast receiver for ACTION_NOTIFICATION_CLICKED to appropriately handle when the user clicks on a running download in a notification or from the downloads UI. Note that the application must have the INTERNET permission to use this class.
You are probably over engineering this. I have implemented swiping with dynamically loading images and I just a use a simple utility class that does it all for me via static method call.
Try this class:
package com.beget.consumer.util;
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
public class DrawableLoader {
private final Map<String, Drawable> drawableMap;
private WeakReference<ImageView> imageViewReference;
public DrawableLoader() {
drawableMap = new HashMap<String, Drawable>();
}
public Drawable fetchDrawable(String urlString) {
if (drawableMap.containsKey(urlString)) {
return drawableMap.get(urlString);
}
Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawableMap.put(urlString, drawable);
Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
+ drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
+ drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
return drawable;
} catch (MalformedURLException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
}
}
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
if (drawableMap.containsKey(urlString)) {
imageViewReference.get().setImageDrawable(drawableMap.get(urlString));
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
imageViewReference.get().setImageDrawable((Drawable) message.obj);
}
};
Thread thread = new Thread() {
#Override
public void run() {
//TODO : set imageView to a "pending" image
Drawable drawable = fetchDrawable(urlString);
Message message = handler.obtainMessage(1, drawable);
handler.sendMessage(message);
}
};
thread.start();
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
This is all you need. Then when you need to load an image, you call:
fetchDrawableOnThread("http://path/to/your/image.jpg", yourImageViewReference);
That's it.
If you have an URL from a JSON object, parse the URL into your string so:
String url = jsonObj.getString("url");
Then call fetchDrawableOnThread(url, yourImageViewReference);
Use volley.
Using volley network image view you can do this
we use latest architecure components here.We make some observers with live data for some flag that represents download status.In service we download the image and completing we update the live data so that the observers method automatically called

Categories

Resources