Riy*_* PK 3 java android android-print-manager
我在使用anroid 4.4打印api时收到错误"java.lang.IllegalStateException:只能从活动中打印".
它适用于4.4以上的所有anroid吗?
我的代码
public class MainActivity extends Activity {
Context cotext;
WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cotext = getApplicationContext();
}
public void printData(View view){
doWebViewPrint();
}
private void doWebViewPrint() {
// Create a WebView object specifically for printing
WebView webView = new WebView(cotext);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
Log.i("TAG", "page finished loading " + url);
createWebPrintJob(view);
mWebView = null;
}
});
// Generate an HTML document on the fly:
String htmlDocument = "<html><body><h1>Test Content</h1><p>Testing, " +
"testing, testing...</p></body></html>";
webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null);
// Keep a reference to WebView object until you pass the PrintDocumentAdapter
// to the PrintManager
mWebView = webView;
}
private void createWebPrintJob(WebView webView) {
// Get a PrintManager instance
PrintManager printManager = (PrintManager) cotext
.getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
// Save the job object for later status checking
//mPrintJobs.add(printJob);
}
}
Run Code Online (Sandbox Code Playgroud)
请帮我.
还有android wifi打印的例子吗?
我的应用程序使用 PDF 打印,使用PrintManager. 我在实现多语言支持后遇到了这个问题。
Androidcontext通过createConfigurationContext(). 这会使PrintManager实例使用的引用无效,从而导致上述IllegalStateException.
解决方案
我的解决方案是存储attachBaseContext() 我的活动成员传递的原始上下文的引用。然后PrintManager通过调用getSystemService()原始context引用而不是非活动context引用来检索实例。
private Context originalContext;
@Override
protected void attachBaseContext(Context newBase) {
this.originalContext = newBase;
super.attachBaseContext(LocaleHelper.onAttach(newBase,appLocale));
}
// Starting printing (PDF generation):
PrintManager printManager = (PrintManager) originalContext.getSystemService(Context.PRINT_SERVICE);
Run Code Online (Sandbox Code Playgroud)
我知道这是迟到的答案.
你必须使用YourCurrentActivity.this而不是getApplicationContext()
因为getApplicationContext()引用整个应用程序,context而YourCurrentActivity.this仅引用当前活动context.
如果您要打印 HTML 内容,此 Android培训会更快、更容易。
现在对于例外情况,我认为您会因为这一行而得到此例外:
PrintManager printManager = (PrintManager) cotext
.getSystemService(Context.PRINT_SERVICE);
Run Code Online (Sandbox Code Playgroud)
您正在使用的上下文是应用程序上下文,尽管您处于活动中并且可以/应该仅使用该活动作为上下文。我不确定为什么cotext在这段代码中你需要一个单独的。
| 归档时间: |
|
| 查看次数: |
2036 次 |
| 最近记录: |