19

I am trying to print the bill through bluetooth using the following code, when I run the app, first time its getting printed, but when I retry its not getting printed.

package com.sel.bluetooth;

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 BluetoothPrint 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:1F:B7:02:8F:44";
            //PRINTER_MAC_ID = "00:12:F3:0D:A3:E6";
            // TRANS_ID="12345678";
            BILL = "\nSale Slip No: 12345678" + "          " + "04-08-2011\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(BluetoothPrint.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);


                    //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(BluetoothPrint.this,
                                device.getName() + " Printing data",
                                Toast.LENGTH_LONG).show();
                        printBillToDevice(PRINTER_MAC_ID);
                        Toast.makeText(BluetoothPrint.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();
    }

}
Selvam Rajendran
  • 1,366
  • 5
  • 20
  • 38
  • hey, i'm looking for the answer too.. why it can't be used for printing some text.. i use datecs DPP-350 for my printers.. any solution? – Michael Frans Dec 07 '11 at 09:08
  • @user905628 Are you using any 3rd party tool to access bluetooth printer in android? Almost all SO links say Android doesn't support BPP(Bluetooth printer profile) natively and 3rd party sdk (almost all are commercially licensed) must be used. But it seems you are not using any 3rd party libraries. Which bluetooth profile are you using? – Krishnabhadra Jul 12 '12 at 06:56
  • HI! I am having the exact same problem. Have you found the solution to the problem?? – Bijay Thapa Nov 27 '12 at 08:34
  • Hey Thank u very much..I get solution of printing from your question ..Thanks a lot.. :) – Kinjal Shah Jan 01 '13 at 14:13

3 Answers3

32

Here is the perfectely working code for blue-tooth printer in android

device_list.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <TextView android:id="@+id/title_paired_devices" 
    android:layout_width="fill_parent" android:layout_height="wrap_content" 
    android:text="My Text" android:visibility="gone" 
    android:background="#666" android:textColor="#fff" 
    android:paddingLeft="5dip" /> 
    <ListView android:id="@+id/paired_devices" 
    android:layout_width="fill_parent" android:layout_height="wrap_content" 
    android:stackFromBottom="true" android:layout_weight="1" /> 
    </LinearLayout>

device_name.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" android:layout_height="wrap_content" 
    android:textSize="18sp" android:padding="5dip" /> 

main.xml

<?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
        <Button android:text="Scan" android:id="@+id/Scan"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="Print" android:id="@+id/mPrint"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="Dissable" android:id="@+id/dis"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        </LinearLayout>

DeviceListActivity.java

    package com.sel.code;

    import java.util.Set; 
          import android.app.Activity; 
          import android.bluetooth.BluetoothAdapter; 
          import android.bluetooth.BluetoothDevice; 
          import android.content.Intent; 
          import android.os.Bundle; 
          import android.util.Log; 
          import android.view.View; 
          import android.view.Window; 
          import android.widget.AdapterView; 
          import android.widget.ArrayAdapter; 
          import android.widget.ListView; 
          import android.widget.TextView; 
          import android.widget.AdapterView.OnItemClickListener; 

    public class DeviceListActivity extends Activity 
    { 
    protected static final String TAG = "TAG"; 
    private BluetoothAdapter mBluetoothAdapter; 
    private ArrayAdapter<String> mPairedDevicesArrayAdapter; 

    @Override 
    protected void onCreate(Bundle mSavedInstanceState) 
    { 
        super.onCreate(mSavedInstanceState); 
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 
        setContentView(R.layout.device_list); 

        setResult(Activity.RESULT_CANCELED); 
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); 

        ListView mPairedListView = (ListView) findViewById(R.id.paired_devices); 
        mPairedListView.setAdapter(mPairedDevicesArrayAdapter); 
        mPairedListView.setOnItemClickListener(mDeviceClickListener); 

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices(); 

        if (mPairedDevices.size() > 0) 
        { 
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); 
            for (BluetoothDevice mDevice : mPairedDevices) 
            { 
                mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress()); 
            } 
        } 
        else 
        { 
            String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString(); 
            mPairedDevicesArrayAdapter.add(mNoDevices); 
        } 
    } 

    @Override 
    protected void onDestroy() 
    { 
        super.onDestroy(); 
        if (mBluetoothAdapter != null) 
        { 
            mBluetoothAdapter.cancelDiscovery(); 
        } 
    } 

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() 
    { 
        public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong) 
        { 
            mBluetoothAdapter.cancelDiscovery(); 
            String mDeviceInfo = ((TextView) mView).getText().toString(); 
            String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17); 
            Log.v(TAG, "Device_Address " + mDeviceAddress); 

            Bundle mBundle = new Bundle(); 
            mBundle.putString("DeviceAddress", mDeviceAddress); 
            Intent mBackIntent = new Intent(); 
            mBackIntent.putExtras(mBundle); 
            setResult(Activity.RESULT_OK, mBackIntent); 
            finish(); 
        } 
    }; 

     } 

Main.java

        package com.sel.code;

        import java.io.IOException;
        import java.io.OutputStream;
        import java.nio.ByteBuffer;
        import java.util.Set;
        import java.util.UUID;

        import android.app.Activity;
        import android.app.ProgressDialog;
        import android.bluetooth.BluetoothAdapter;
        import android.bluetooth.BluetoothDevice;
        import android.bluetooth.BluetoothSocket;
        import android.content.Intent;
        import android.os.Bundle;
        import android.os.Handler;
        import android.os.Message;
        import android.util.Log;
        import android.view.View;
        import android.view.Window;
        import android.view.WindowManager;
        import android.widget.Button;
        import android.widget.Toast;

        public class Main extends Activity implements Runnable {
            protected static final String TAG = "TAG";
            private static final int REQUEST_CONNECT_DEVICE = 1;
            private static final int REQUEST_ENABLE_BT = 2;
            Button mScan, mPrint, mDisc;
            BluetoothAdapter mBluetoothAdapter;
            private UUID applicationUUID = UUID
                    .fromString("00001101-0000-1000-8000-00805F9B34FB");
            private ProgressDialog mBluetoothConnectProgressDialog;
            private BluetoothSocket mBluetoothSocket;
            BluetoothDevice mBluetoothDevice;

            @Override
            public void onCreate(Bundle mSavedInstanceState) {
                super.onCreate(mSavedInstanceState);
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                setContentView(R.layout.main);
                mScan = (Button) findViewById(R.id.Scan);
                mScan.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View mView) {
                        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                        if (mBluetoothAdapter == null) {
                            Toast.makeText(Main.this, "Message1", 2000).show();
                        } else {
                            if (!mBluetoothAdapter.isEnabled()) {
                                Intent enableBtIntent = new Intent(
                                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(enableBtIntent,
                                        REQUEST_ENABLE_BT);
                            } else {
                                ListPairedDevices();
                                Intent connectIntent = new Intent(Main.this,
                                        DeviceListActivity.class);
                                startActivityForResult(connectIntent,
                                        REQUEST_CONNECT_DEVICE);
                            }
                        }
                    }
                });

                mPrint = (Button) findViewById(R.id.mPrint);
                mPrint.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View mView) {
                        Thread t = new Thread() {
                            public void run() {
                                try {
                                    OutputStream os = mBluetoothSocket
                                            .getOutputStream();
                                    String BILL = "";

                                    BILL = "\nInvoice No: ABCDEF28060000005" + "    "
                                            + "04-08-2011\n";
                                    BILL = BILL
                                            + "-----------------------------------------";
                                    BILL = BILL + "\n\n";
                                    BILL = BILL + "Total Qty:" + "      " + "2.0\n";
                                    BILL = BILL + "Total Value:" + "     "
                                            + "17625.0\n";
                                    BILL = BILL
                                            + "-----------------------------------------\n";
                                    os.write(BILL.getBytes());
                                        //This is printer specific code you can comment ==== > Start

                                    // Setting height
                                    int gs = 29;
                                    os.write(intToByteArray(gs));
                                    int h = 104;
                                    os.write(intToByteArray(h));
                                    int n = 162;
                                    os.write(intToByteArray(n));

                                    // Setting Width
                                    int gs_width = 29;
                                    os.write(intToByteArray(gs_width));
                                    int w = 119;
                                    os.write(intToByteArray(w));
                                    int n_width = 2;
                                    os.write(intToByteArray(n_width));

                                    // Print BarCode
                                    int gs1 = 29;
                                    os.write(intToByteArray(gs1));
                                    int k = 107;
                                    os.write(intToByteArray(k));
                                    int m = 73;
                                    os.write(intToByteArray(m));

                                    String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
                                    System.out.println("Barcode Length : "
                                            + barCodeVal.length());
                                    int n1 = barCodeVal.length();
                                    os.write(intToByteArray(n1));

                                    for (int i = 0; i < barCodeVal.length(); i++) {
                                        os.write((barCodeVal.charAt(i) + "").getBytes());
                                    }
       //printer specific code you can comment ==== > End
                                } catch (Exception e) {
                                    Log.e("Main", "Exe ", e);
                                }
                            }
                        };
                        t.start();
                    }
                });

                mDisc = (Button) findViewById(R.id.dis);
                mDisc.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View mView) {
                        if (mBluetoothAdapter != null)
                            mBluetoothAdapter.disable();
                    }
                });

            }// onCreate

            @Override
            protected void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
                try {
                    if (mBluetoothSocket != null)
                        mBluetoothSocket.close();
                } catch (Exception e) {
                    Log.e("Tag", "Exe ", e);
                }
            }

            @Override
            public void onBackPressed() {
                try {
                    if (mBluetoothSocket != null)
                        mBluetoothSocket.close();
                } catch (Exception e) {
                    Log.e("Tag", "Exe ", e);
                }
                setResult(RESULT_CANCELED);
                finish();
            }

            public void onActivityResult(int mRequestCode, int mResultCode,
                    Intent mDataIntent) {
                super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

                switch (mRequestCode) {
                case REQUEST_CONNECT_DEVICE:
                    if (mResultCode == Activity.RESULT_OK) {
                        Bundle mExtra = mDataIntent.getExtras();
                        String mDeviceAddress = mExtra.getString("DeviceAddress");
                        Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                        mBluetoothDevice = mBluetoothAdapter
                                .getRemoteDevice(mDeviceAddress);
                        mBluetoothConnectProgressDialog = ProgressDialog.show(this,
                                "Connecting...", mBluetoothDevice.getName() + " : "
                                        + mBluetoothDevice.getAddress(), true, false);
                        Thread mBlutoothConnectThread = new Thread(this);
                        mBlutoothConnectThread.start();
                        // pairToDevice(mBluetoothDevice); This method is replaced by
                        // progress dialog with thread
                    }
                    break;

                case REQUEST_ENABLE_BT:
                    if (mResultCode == Activity.RESULT_OK) {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this,
                                DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    } else {
                        Toast.makeText(Main.this, "Message", 2000).show();
                    }
                    break;
                }
            }

            private void ListPairedDevices() {
                Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
                        .getBondedDevices();
                if (mPairedDevices.size() > 0) {
                    for (BluetoothDevice mDevice : mPairedDevices) {
                        Log.v(TAG, "PairedDevices: " + mDevice.getName() + "  "
                                + mDevice.getAddress());
                    }
                }
            }

            public void run() {
                try {
                    mBluetoothSocket = mBluetoothDevice
                            .createRfcommSocketToServiceRecord(applicationUUID);
                    mBluetoothAdapter.cancelDiscovery();
                    mBluetoothSocket.connect();
                    mHandler.sendEmptyMessage(0);
                } catch (IOException eConnectException) {
                    Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
                    closeSocket(mBluetoothSocket);
                    return;
                }
            }

            private void closeSocket(BluetoothSocket nOpenSocket) {
                try {
                    nOpenSocket.close();
                    Log.d(TAG, "SocketClosed");
                } catch (IOException ex) {
                    Log.d(TAG, "CouldNotCloseSocket");
                }
            }

            private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    mBluetoothConnectProgressDialog.dismiss();
                    Toast.makeText(Main.this, "DeviceConnected", 5000).show();
                }
            };

            public static byte intToByteArray(int value) {
                byte[] b = ByteBuffer.allocate(4).putInt(value).array();

                for (int k = 0; k < b.length; k++) {
                    System.out.println("Selva  [" + k + "] = " + "0x"
                            + UnicodeFormatter.byteToHex(b[k]));
                }

                return b[3];
            }

            public byte[] sel(int val) {
                ByteBuffer buffer = ByteBuffer.allocate(2);
                buffer.putInt(val);
                buffer.flip();
                return buffer.array();
            }

        }

UnicodeFormatter.java

    package com.sel.code;

    import java.io.*;

    public class UnicodeFormatter {

        static public String byteToHex(byte b) {
                // Returns hex String representation of byte b
                char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'a', 'b', 'c', 'd', 'e', 'f' };
                char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
                return new String(array);
        }

        static public String charToHex(char c) {
                // Returns hex String representation of char c
                byte hi = (byte) (c >>> 8);
                byte lo = (byte) (c & 0xff);
                return byteToHex(hi) + byteToHex(lo);
        }

    } // class
Selvam Rajendran
  • 1,366
  • 5
  • 20
  • 38
  • how to set width of the charactor?? can u pls help me?/ – Poovizhirajan N Feb 21 '13 at 12:12
  • a manual is their friend, `$01` is used to reduce the width so is am printing `hello` word means how can i send to the printer with `$01`. – Poovizhirajan N Feb 21 '13 at 12:25
  • a code walk through somewhere would be very helpful..also can I print from a mac machine that has shared its printer over bluetooth – anz Mar 19 '13 at 07:37
  • Has anyone made this into a PhoneGap plugin? I could really use it! – Scott R. Frost Mar 28 '13 at 13:35
  • @SelvamR thaks for this code i had tried this it's working fine but this will not print arbic text can you check it..? – CoronaPintu Jul 02 '13 at 04:48
  • Unicode characters (ex: ğşçöüı ) display incorrectly as square box when printing with bluetoothadapter.outputstream in Epson LX-300+II. It's a dot matrix printer and Character table is PC 857 in printer settings. So I solved problem by using my fixUnicodeCharacters method for now. – Engin Ardıç Jul 11 '13 at 08:57
  • 1
    I tried your solution. but it doesn't work. Then I looked for your code and found a code line: private UUID applicationUUID = UUID .fromString("00001101-0000-1000-8000-00805F9B34FB");How you know the printer that you want to connect with is listening the same UUID like this. – Huy Duong Tu Jul 23 '13 at 01:53
  • 1
    @SelvamR I used ur code but it is not printing anything through printer..Please Help – Manish Aug 26 '13 at 09:47
  • @SelvamR : I am using evolute impress printer and i am passing string as bytes but i cant able to get print from printer using above. can u guide me how to over come this problem – Giridharan Jan 05 '15 at 07:31
  • @Poovizhirajan.N: which printer are you using?? – Giridharan Jan 05 '15 at 07:32
  • @Giridharan own printer form my organization – Poovizhirajan N Jan 05 '15 at 08:54
  • it working correctly. But I need to keep the state of Bluetooth. if I back press or finish the activity Bluetooth socket closed. how to connect the socket for the entire app. – Muthu Krishnan Dec 31 '19 at 09:58
  • Can anyone guide me here with this code. Blue light blinks on printer after pairing but the print command does nothing. Nothing prints on the printer. What could be the reason? – Suraj Sahijwani Jan 15 '21 at 07:01
0

I've just uncommented //mBTSocket.close();

Then, just before, add:

if (mBTAdapter != null)
    mBTAdapter.cancelDiscovery();

and everything goes well!

Nikana Reklawyks
  • 3,233
  • 3
  • 33
  • 49
Kingxlayer
  • 119
  • 5
0

Also try closing the OutputStream after writing to it, preferably in the finish block using:

os.close();
MelOS
  • 595
  • 5
  • 10