从后台服务Android生成运行时视图

时间:2017-08-19 09:49:13

标签: android service view runtime

任何人都可以澄清:是否可以通过后台服务创建运行时视图?

我正在活动中创建Runtime Layout Inflater视图,然后创建该Inflater视图的位图并在PDF中添加该位图 - 所有这些都在活动中运行良好。

但是我在服务中尝试了这个但它创建了空白的PDF - 所以任何人都像这样实现了这个解决方案的任何策略 - 或者是否有其他方法从后台服务创建动态运行时视图? - 每个人都会感激。

在后台服务类中

 try {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.temp,null);
        LinearLayout linearLayout = (LinearLayout) v.findViewById(R.id.linear);

        linearLayout.measure(1000, 480);
        linearLayout.layout(100, 0, 1000, 480);

        ByteArrayOutputStream stream = null;

        Bitmap pictureBitmap = getBitmapFromView(linearLayout); // obtaining the Bitmap

        stream = new ByteArrayOutputStream();
        pictureBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        image = com.itextpdf.text.Image.getInstance(stream.toByteArray());
        image.scaleToFit(600f, 740f);

        createPdf();

    } catch (Exception e) {
        e.printStackTrace();
    }

从视图创建位图

public static Bitmap getBitmapFromView(LinearLayout view) {
    view.setDrawingCacheEnabled(true);

    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();

    if (bgDrawable != null)
    {
        bgDrawable.draw(canvas);
    }
    else
    {
        canvas.drawColor(Color.WHITE);
    }

    view.draw(canvas);
    return returnedBitmap;
}

用于创建PDF

private void createPdf() throws FileNotFoundException, DocumentException {

    File pdfFolder = new File(Environment.getExternalStorageDirectory(), "/PDFDemo");

    if (!pdfFolder.exists()) {
        pdfFolder.mkdir();
        Log.i(TAG, "Pdf Directory created");
    }

    Log.e(TAG,"before document");

    String targetPdf = "/sdcard/TEMP2.pdf";

    File myFile = new File(targetPdf);
    OutputStream output = new FileOutputStream(myFile);

    Document document = new Document(PageSize.A4,10,10,10,10);

    PdfWriter.getInstance(document, output);

    document.open();
    document.setMarginMirroringTopBottom(true);

    for(int i=0;i<9;i++) {
        document.add(image);
    }

    document.close();

    Log.e(TAG,"after document");
}

0 个答案:

没有答案