2016-06-02 3 views
0

Я получаю сообщение об ошибке «java.lang.IllegalStateException: может печатать только из активности» при использовании анимированного анонса 4.4.ошибка: «java.lang.IllegalStateException: может печатать только из активности»?

Работает ли он над всем андроидом выше 4.4?

мой код

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); 
    } 
} 

пожалуйста, помогите мне.

есть ли какой-нибудь пример Wi-Fi Wi-Fi?

+0

Возможно, это поможет. http://stackoverflow.com/questions/14097990/require-android-program-to-connect-to-a-wifi-printer-and-physically-print-conten –

+0

Спасибо @Dipalishah. я могу сделать с https://developer.android.com/training/printing/custom-docs.html –

ответ

0

Если вы печатаете HTML-контент, этот Android training работает быстрее и проще.

Теперь за исключением, я думаю, вы получаете это исключение из этой строки:

PrintManager printManager = (PrintManager) cotext 
      .getSystemService(Context.PRINT_SERVICE); 

Контекст вы используете является контекст приложения, хотя вы в деятельности и можно/нужно просто используйте эту деятельность как контекст. Я не уверен, зачем вам нужен отдельный cotext в этом коде.

2

Я знаю, что это поздний ответ.

Вы должны использовать YourCurrentActivity.this вместо getApplicationContext()

Поскольку getApplicationContext() относится к всему приложению context в то время как YourCurrentActivity.this относится только текущую деятельность context.

Смежные вопросы