Android:从后台服务获取网页的“屏幕截图”?

时间:2015-01-20 15:43:08

标签: android android-webview android-service

我有一个网页的网址,我想在后台截取此网页的“屏幕截图”,例如。在服务中,没有向用户显示用户界面。

我尝试在我的服务中创建WebView,然后使用capturePicture()方法在页面加载完成后获取屏幕截图,但创建的Picture(以及Bitmap我从它创建)总是空的。 (这在普通活动中完美有效,但在我的后台服务中却无效。)

任何方式让这个工作,或者在没有用户界面的情况下获取网页“屏幕截图”的替代方法?

1 个答案:

答案 0 :(得分:4)

注意:这个答案很老 - 我尝试过的最新Android版本是4.4,YMMV在其他Android版本或设备上我没有测试过这个...这是也是一个超级大肆的黑客 - 现在我建议使用网络服务/ API。


想出来,我必须设置'尺寸'的WebView,以便产生的屏幕截图'不是0 x 0大小。然后我必须直接从WebView的绘图缓存获取位图,因为capturePicture()似乎不起作用。

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() {

}


}