【发布时间】:2011-11-14 18:03:02
【问题描述】:
我想请教您如何通过按一个按钮来捕获和保存使用 Phonegap 编译的 Android 应用程序中当前显示的内容。
我对可能的方法进行了数小时的研究:
创建一个查找当前视图的 Phonegap 插件,将其转换为位图,然后将其保存到设备 SD 卡。如here所见。
使用 HTML5 Canvas 标记并将其和任何子元素转换为 PNG 文件,使用 here 中的 toDataURL 方法。
我很忙,非常感谢任何可能有帮助的建议、教程或链接。有数百个 SO 帖子说这不能在 Android 中完成,但考虑到我发现了两个可能的链接,我不敢相信。
我已经尝试了上面的链接,但是有一些未解决的问题使我无法让它们正常工作。我一直在寻找替代品。
编辑:下面是我正在使用的插件代码,以及第一个链接中关于如何记录视图屏幕截图的代码。
package com.company.msgbox;
//imports
@Override
public PluginResult execute(String arg0, final JSONArray arg1, String arg2) {
if ( arg0.equals(SHOW) )
{
this.ctx.runOnUiThread(new Runnable()
{
public void run()
{
// try/catch generated by editor
try {
msg = arg1.getString(MSG_INDEX);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Title");
alertDialog.setMessage(msg);
alertDialog.show();
//screen shot
View content = findViewById(R.id.rootlayout);
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/test.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}//end of scope
});
}
return new PluginResult(Status.OK);
}
}
我在这一行得到一个空指针异常:
View content = findViewById(R.id.rootlayout);
我的问题是,Phonegap 是否在 Android 中创建视图,如果是,您如何使用 findViewById 方法选择它们?
【问题讨论】:
-
“有数百个 SO 帖子说这不能在 Android 中完成,但考虑到我发现了两个可能的链接,我不敢相信。” ——这些帖子中的大多数都是针对试图捕获任何应用程序活动的屏幕截图的人,而不仅仅是他们自己的。这是不支持的。您的方法仅适用于您的活动,并且它们受到支持,只是不是特别好。 :-)
-
@LordSnoutimus:
findViewById()是Activity上的一个方法。我不知道 PhoneGap 插件架构。ctx可能是您的Activity。如果没有,请联系 PhoneGap 人员,了解如何通过插件访问您的Activity。我希望这是可能的。 -
@LordSnoutimus:如果它还不是
Activity,您必须将其转换为Activity。与 JavaScript 不同,Java 是强类型的。但是你会打电话给ctx.findViewById(R.id.rootlayout)(如果ctx是Activity)或((Activity)ctx).findViewById(R.id.rootlayout)(如果ctx真的是Activity,但作为更通用的Context交给你)。如果ClassCastException失败,那么ctx是Context的其他类型,而不是Activity,你又回到了原点。 -
@LordSnoutimus:太棒了——我从来没有访问过绘图缓存。我建议你就这个话题提出一个新问题。
-
@LordSnoutimus:尝试
R.id.appView,基于github.com/callback/callback-android/blob/master/framework/res/…
标签: javascript android mobile cordova