sohotcall

Bluetooth Printer Android Java

Jul 27th, 2018
132
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Bluetooth Printer Android
  3. HOWTO:
  4. 1. Install app ini di android
  5. 2. Buat dokumen yang mau di print, taruh ke web
  6. 3. Buat halaman web berisi link seperti contoh di bawah.
  7. 4. Nanti kalau linknya diklik, dokumen kecetak deh.
  8. 5. Enjoy!
  9. <h1>Contoh</h1>
  10. <p>Untuk ngeprint isi halaman http://gungsukma.pw/test.txt ke printer MTP-II,
  11. klik <a href="myapp://ahok.gungsukma.com/?device=MTP-II&url=http://gungsukma.pw/test.txt">di sini</a>.</p>
  12. */
  13.  
  14. package com.gungsukma.btp;
  15.  
  16. import android.bluetooth.BluetoothAdapter;
  17. import android.bluetooth.BluetoothDevice;
  18. import android.bluetooth.BluetoothSocket;
  19. import android.content.Intent;
  20. import android.net.Uri;
  21. import android.os.Bundle;
  22. import android.support.v7.app.AppCompatActivity;
  23. import android.util.Log;
  24. import android.widget.Toast;
  25.  
  26. import java.io.BufferedInputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.OutputStream;
  30. import java.net.URL;
  31. import java.net.URLConnection;
  32. import java.util.UUID;
  33.  
  34. // Permisi, manifest numpang lewat..
  35. /*
  36. <?xml version="1.0" encoding="utf-8"?>
  37. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  38.     package="com.gungsukma.btp">
  39.     <uses-permission android:name="android.permission.INTERNET" />
  40.     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  41.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  42.     <uses-permission android:name="android.permission.BLUETOOTH" />
  43.     <application
  44.         android:allowBackup="true"
  45.         android:label="@string/app_name"
  46.         android:supportsRtl="true"
  47.         android:theme="@style/AppTheme"
  48.         android:usesCleartextTraffic="true">
  49.         <activity android:name=".PrintFile">
  50.             <intent-filter>
  51.                 <action android:name="android.intent.action.VIEW" />
  52.                 <category android:name="android.intent.category.DEFAULT" />
  53.                 <category android:name="android.intent.category.BROWSABLE" />
  54.                 <data android:host="ahok.gungsukma.com" />
  55.                 <data android:scheme="myapp"/>
  56.             </intent-filter>
  57.         </activity>
  58.     </application>
  59. </manifest>
  60. */
  61.  
  62. public class PrintFile extends AppCompatActivity {
  63.    
  64.     private static final UUID MY_UUID = UUID.fromString( "00001101-0000-1000-8000-00805F9B34FB" );
  65.     private static final String newLine = System.getProperty( "line.separator" );
  66.    
  67.     public void showToast( final String toast ) {
  68.         runOnUiThread( new Runnable() {
  69.             @Override public void run() {
  70.                 Toast.makeText( PrintFile.this, toast, Toast.LENGTH_SHORT ).show();
  71.             }
  72.         } );
  73.         Log.d( "BTP", toast );
  74.     }
  75.    
  76.     // Mendownload webpage (atau tepatnya dokumen), mengembalikan kontennya
  77.     public String downloadWebpage( String uri ) {
  78.         StringBuilder sb = new StringBuilder();
  79.         try {
  80.             URL url = new URL( uri );
  81.             URLConnection connection = url.openConnection();
  82.             connection.connect();
  83.             int i = connection.getContentLength();
  84.             BufferedInputStream in = new BufferedInputStream( url.openStream() );
  85.             try {
  86.                 byte dataBuffer[] = new byte[1024];
  87.                 int bytesRead;
  88.                 while ( ( bytesRead = in.read( dataBuffer, 0, 1024 ) ) != -1 ) {
  89.                     String s = new String( dataBuffer, 0, bytesRead );
  90.                     sb.append( s );
  91.                 }
  92.             } catch ( Exception e ) {
  93.                 showToast( "Cannot download webpage ( 1 ). " + e.getMessage() );
  94.             }
  95.             in.close();
  96.         } catch ( Exception e ) {
  97.             showToast( "Cannot download webpage ( 2 ). " + e.getMessage() );
  98.         }
  99.         return sb.toString();
  100.     } // downloadWebpage
  101.    
  102.     @Override protected void onCreate( Bundle savedInstanceState ) {
  103.         super.onCreate( savedInstanceState );
  104.         setContentView( R.layout.layout );
  105.         Intent intent = getIntent();
  106.        
  107.         if ( intent.getAction().equals( Intent.ACTION_VIEW ) && intent.getScheme().equals( "myapp" ) ) {
  108.             Uri uri = intent.getData();
  109.             final String deviceName = uri.getQueryParameter( "deviceName" );
  110.             final String url = uri.getQueryParameter( "url" );
  111.             new Thread( new Runnable() {
  112.                 public void run() {
  113.                     DoBTP( deviceName, url );
  114.                     runOnUiThread( new Runnable() {
  115.                         @Override public void run() {
  116.                             PrintFile.this.finish();
  117.                         }
  118.                     } );
  119.                 }
  120.             } ).start();
  121.         }
  122.     } // onCreate
  123.    
  124.     // Print ke bluetooth printer
  125.     public void DoBTP( String deviceName, String url ) {
  126.         BluetoothAdapter btAdapter;
  127.         BluetoothDevice btDevice = null;
  128.         BluetoothSocket btSocket = null;
  129.         String address = null;
  130.         btAdapter = BluetoothAdapter.getDefaultAdapter();
  131.         for ( BluetoothDevice d : btAdapter.getBondedDevices() )
  132.             if ( d.getName().equals( deviceName ) || d.getAddress().equals( deviceName ) )
  133.                 address = d.getAddress();
  134.         try {
  135.             btDevice = btAdapter.getRemoteDevice( address );
  136.         } catch ( Exception e ) {
  137.             showToast( "Cannot find device. " + e.getMessage() );
  138.         }
  139.         try {
  140.             btSocket = btDevice.createRfcommSocketToServiceRecord( MY_UUID );
  141.         } catch ( IOException e ) {
  142.             showToast( "Cannot socket. " + e.getMessage() );
  143.         }
  144.         try {
  145.             btSocket.connect();
  146.             try {
  147.                 InputStream tmpIn = btSocket.getInputStream();
  148.                 OutputStream tmpOut = btSocket.getOutputStream();
  149.                 try {
  150.                     int bytes = tmpIn.available();
  151.                     byte[] buffer = new byte[1024];
  152.                     if ( bytes != 0 )
  153.                         tmpIn.read( buffer, 0, bytes );
  154.                 } catch ( IOException e ) {
  155.                     showToast( "Cannot empty buffer. " + e.getMessage() );
  156.                 }
  157.                 for ( String s : downloadWebpage( url ).split( newLine ) )
  158.                     tmpOut.write( ( s + "\n" ).getBytes() );
  159.                 // TODO: I'm trying to cut paper here
  160.                 // 29 'V' 48 atau 29 'V' 65 atau GS 86 65 0
  161.                 String cutPaper = new String( new byte[]{'\n', 0x1B, 'm', '\n'} );
  162.                 tmpOut.write( cutPaper.getBytes() );
  163.             } catch ( IOException e ) {
  164.                 showToast( "Cannot stream. " + e.getMessage() );
  165.             }
  166.         } catch ( IOException e ) {
  167.             showToast( "Cannot connect. " + e.getMessage() );
  168.         } finally {
  169.             try {
  170.                 btSocket.close();
  171.             } catch ( IOException e ) {
  172.                 showToast( "Cannot close socket. " + e.getMessage() );
  173.             }
  174.         }
  175.     } // DoBTP
  176.    
  177. } // class
RAW Paste Data