2015-05-15 2 views
1

Я сделал приложение для Android, в котором я попытался напечатать образец текстового файла, я хочу использовать подключенные к Wi-Fi принтеры, я пробовал эту ссылку Wifi printing in android Но это касается только поиска wifi-принтера и ничего не делать, мой код, как показано ниже, пожалуйста, помогите мне и спасти свою жизньПечать в android только поиск принтеров

код

public class MainActivity extends Activity { 

    public int pageHeight; 
    public int pageWidth; 
    public PdfDocument myPdfDocument; 
    public int totalpages = 4; 
    Button button1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     button1 = (Button) findViewById(R.id.button1); 

    } 

    PrintDocumentAdapter pda = new PrintDocumentAdapter() { 

     @Override 
     public void onWrite(PageRange[] pages, 
       ParcelFileDescriptor destination, 
       CancellationSignal cancellationSignal, 
       WriteResultCallback callback) { 
      InputStream input = null; 
      OutputStream output = null; 

      try { 

       input = getAssets().open("sample.txt"); 
       output = new FileOutputStream(destination.getFileDescriptor()); 

       byte[] buf = new byte[1024]; 
       int bytesRead; 

       while ((bytesRead = input.read(buf)) > 0) { 
        output.write(buf, 0, bytesRead); 
       } 

       callback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES }); 

      } catch (FileNotFoundException ee) { 
       // Catch exception 
      } catch (Exception e) { 
       // Catch exception 
      } finally { 
       try { 
        input.close(); 
        output.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     @SuppressLint("InlinedApi") 
     @Override 
     public void onLayout(PrintAttributes oldAttributes, 
       PrintAttributes newAttributes, 
       CancellationSignal cancellationSignal, 
       LayoutResultCallback callback, Bundle extras) { 

      if (cancellationSignal.isCanceled()) { 
       callback.onLayoutCancelled(); 
       return; 
      } 

      //int pages = computePageCount(newAttributes); 

      PrintDocumentInfo pdi = new PrintDocumentInfo.Builder(
        "Name of file").setContentType(
        PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); 

      callback.onLayoutFinished(pdi, true); 
     } 
    }; 

    @SuppressLint("InlinedApi") 
    public void printDocument(View view) { 
     PrintManager printManager = (PrintManager) this 
       .getSystemService(Context.PRINT_SERVICE); 
     String jobName = this.getString(R.string.app_name) + " Document"; 
     printManager.print(jobName, pda, null); 
    } 

} 

манифеста

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.wifiprint" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="21" /> 

    <uses-feature android:name="android.hardware.wifi" /> 

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 
+0

вы исправить вашу проблему та же проблема для меня. –

ответ

0

Вы должны сделать прослушиватель кнопок первым для события кнопки.

Button button1 = (Button) findViewById(R.id.button1); 
    button1.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      doCustomPrint(); 
     } 
    }); 

И этот метод печати для печати на заказ;

private void doCustomPrint() { 

    PrintDocumentAdapter pda = new PrintDocumentAdapter(){ 

     @Override 
     public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){ 
      InputStream input = null; 
      OutputStream output = null; 

      AssetManager assetManager = getAssets(); 

      try { 
       // File for print. 
       input = assetManager.open("abc.pdf"); 
       output = new FileOutputStream(destination.getFileDescriptor()); 

       byte[] buf = new byte[1024]; 
       int bytesRead; 

       while ((bytesRead = input.read(buf)) > 0) { 
        output.write(buf, 0, bytesRead); 
       } 

       callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES}); 

      } catch (FileNotFoundException ee){ 
       //Catch exception 
      } catch (Exception e) { 
       //Catch exception 
      } finally { 
       try { 
        input.close(); 
        output.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     @Override 
     public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){ 

      if (cancellationSignal.isCanceled()) { 
       callback.onLayoutCancelled(); 
       return; 
      } 

      PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("print_doc.pdf").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); 
      callback.onLayoutFinished(pdi, true); 
     } 
    }; 

    PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE); 
    String jobName = this.getString(R.string.app_name) + " Document"; 
    printManager.print(jobName, pda, null); 
} 

И проверьте эти документы.

http://developer.android.com/training/printing/index.html

How to Print PDF using Android 4.4 Printing framework

+0

wait..for моего обновления по вопросу, мой дорогой друг, я уже объявил его в моем xml .. как этот андроид: onClick = "printDocument", SO будет напрямую вызывать функцию tat, не так ли? После нажатия этой кнопки открывается всплывающее окно для pagelayouts и поиск принтеров, когда я выбираю все принтеры для поиска принтеров, и после этого ничего не происходит ,,,! –

+0

Вы уже прочитали мой вопрос? Я уже упомянул о той ссылке, которую вы мне прислали ... без везения .. :( –

+0

Функция печати нуждается в уровне API 19. Пожалуйста, проверьте тест minSdkVersion на 19 из 8, t забыть добавить android-support-v4.jar lib в свои библиотеки. – Charles