Click here to Skip to main content
11,493,046 members (64,149 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Android Eclipse
I am making app where I have to from android BT(Bluetooth) to BT printer

I can print the page and text file but i am not getting print in manner as in the text file ..This is my code to print..



import java.io.OutputStream;
import java.lang.reflect.Method;
 
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
 
public class MainActivity extends Activity {
  BluetoothAdapter mBTAdapter;
  BluetoothSocket mBTSocket = null;
  Dialog dialogProgress;
  String BILL, TRANS_ID;
  String PRINTER_MAC_ID;
  final String ERROR_MESSAGE = "There has been an error in printing the bill.";
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    try {
 
      // BILL = getIntent().getStringExtra("TO_PRINT");
      // TRANS_ID = getIntent().getStringExtra("TRANS_ID");

      // PRINTER_MAC_ID = getIntent().getStringExtra("MAC_ID");

      PRINTER_MAC_ID = "00:03:7A:25:1E:D8";
      // PRINTER_MAC_ID = "00:12:F3:0D:A3:E6";
      // TRANS_ID="12345678";
      BILL = "Sale Slip No: 12345678" + "          " + "19-11-2012\n";
      BILL = BILL + "----------------------------------------";
      BILL = BILL + "\n\n";
      BILL = BILL + "Total Qty:" + "     " + "2.0\n";
      BILL = BILL + "Total Value:" + "     " + "17625.0\n";
      BILL = BILL + "-----------------------------------------";
 
      mBTAdapter = BluetoothAdapter.getDefaultAdapter();
 
      dialogProgress = new Dialog(MainActivity.this);
 
      try {
        if (mBTAdapter.isDiscovering())
          mBTAdapter.cancelDiscovery();
        else
          mBTAdapter.startDiscovery();
      } catch (Exception e) {
        Log.e("Class ", "My Exe ", e);
      }
      System.out.println("BT Searching status :"
          + mBTAdapter.isDiscovering());
      if (mBTAdapter == null) {
        Toast.makeText(this, "Device has no bluetooth capability",
            Toast.LENGTH_LONG).show();
        finish();
      } else {
        if (!mBTAdapter.isEnabled()) {
          Intent i = new Intent(
              BluetoothAdapter.ACTION_REQUEST_ENABLE);
          startActivityForResult(i, 0);
        }
 
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(
            BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        // Don't forget to unregister during
        // onDestroy
        dialogProgress.setTitle("Finding printer...");
        dialogProgress
            .setOnDismissListener(new DialogInterface.OnDismissListener() {
              public void onDismiss(DialogInterface dialog) {
                dialog.dismiss();
                setResult(RESULT_CANCELED);
                finish();
              }
            });
        dialogProgress.show();
 
      }
 
    } catch (Exception e) {
      Log.e("Class ", "My Exe ", e);
    }
  }
 
  public void printBillToDevice(final String address) {
 
    new Thread(new Runnable() {
 
      public void run() {
        runOnUiThread(new Runnable() {
 
          public void run() {
            dialogProgress.setTitle("Connecting...");
            dialogProgress.show();
          }
        });
 
        mBTAdapter.cancelDiscovery();
 
        try {
          System.out
              .println("**************************#****connecting");
          BluetoothDevice mdevice = mBTAdapter
              .getRemoteDevice(address);
          Method m = mdevice.getClass().getMethod(
              "createRfcommSocket", new Class[] { int.class });
          mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
 
          mBTSocket.connect();
          OutputStream os = mBTSocket.getOutputStream();
          os.flush();
 
          os.write(BILL.getBytes());
          System.out.println(BILL);
 
          if (mBTAdapter != null)
            mBTAdapter.cancelDiscovery();
 
          mBTSocket.close();
          setResult(RESULT_OK);
          finish();
        } catch (Exception e) {
          Log.e("Class ", "My Exe ", e);
          // Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
          // Toast.LENGTH_SHORT).show();
          e.printStackTrace();
          setResult(RESULT_CANCELED);
          finish();
 
        }
 
        runOnUiThread(new Runnable() {
 
          public void run() {
            try {
              dialogProgress.dismiss();
            } catch (Exception e) {
              Log.e("Class ", "My Exe ", e);
            }
          }
        });
      }
    }).start();
  }
 
  @Override
  protected void onDestroy() {
    Log.i("Dest ", "Checking Ddest");
    super.onDestroy();
    try {
      if (dialogProgress != null)
        dialogProgress.dismiss();
      if (mBTAdapter != null)
        mBTAdapter.cancelDiscovery();
      this.unregisterReceiver(mReceiver);
    } catch (Exception e) {
      Log.e("Class ", "My Exe ", e);
    }
  }
 
  private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
 
      try {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
          // Get the BluetoothDevice object from the Intent
          BluetoothDevice device = intent
              .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
          System.out.println("***" + device.getName() + " : "
              + device.getAddress());
 
          if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
            mBTAdapter.cancelDiscovery();
            dialogProgress.dismiss();
            Toast.makeText(MainActivity.this,
                device.getName() + " Printing data",
                Toast.LENGTH_LONG).show();
            printBillToDevice(PRINTER_MAC_ID);
            Toast.makeText(MainActivity.this,
                device.getName() + " found", Toast.LENGTH_LONG)
                .show();
          }
        }
      } catch (Exception e) {
        Log.e("Class  ", "My Exe ", e);
        // Toast.makeText(BluetoothPrint.this,
        // ERROR_MESSAGE,Toast.LENGTH_SHORT).show();

      }
    }
  };
 
  @Override
  public void onBackPressed() {
    try {
      if (mBTAdapter != null)
        mBTAdapter.cancelDiscovery();
      this.unregisterReceiver(mReceiver);
    } catch (Exception e) {
      Log.e("Class ", "My Exe ", e);
    }
    setResult(RESULT_CANCELED);
    finish();
  }
 
}

[edit]indexation corrected and code block added[/edit]
Posted 21-Nov-12 2:37am
Edited 21-Nov-12 12:54pm
Nelek70.7K
v2
Comments
AndroidVivek at 21-Nov-12 7:37am
   
here is code where the text is set statically...

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

We have to use mobile printing commands to print in manner
like this cmd to set page

! 0 200 200 210 1

we have to add this with our string....
lil bit odd to do...
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 419
1 Maciej Los 286
2 F-ES Sitecore 224
3 KarstenK 210
4 CPallini 208
0 Sergey Alexandrovich Kryukov 10,132
1 OriginalGriff 8,630
2 Sascha Lefèvre 3,624
3 Maciej Los 3,392
4 Richard Deeming 2,500


Advertise | Privacy | Mobile
Web04 | 2.8.150520.1 | Last Updated 27 Nov 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100