Skip to content

Instantly share code, notes, and snippets.

@imammubin
Created February 28, 2020 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imammubin/8fd94b2be6823b3ec6de0ac8a5ac7fd5 to your computer and use it in GitHub Desktop.
Save imammubin/8fd94b2be6823b3ec6de0ac8a5ac7fd5 to your computer and use it in GitHub Desktop.
package id.co.kopkarbsm.votingsystem;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Set;
import java.util.UUID;
public class PostresultActivity extends AppCompatActivity {
TextView textView;
WebView webView;
BluetoothAdapter bluetoothAdapter;
BluetoothSocket socket;
BluetoothDevice bluetoothDevice;
OutputStream outputStream;
InputStream inputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
String value = "";
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.postresult_activity);
textView = findViewById(R.id.textView);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavascript(PostresultActivity.this),"androidJS");
webView.setWebViewClient(new webCallBack());
webView.setWebChromeClient(new webChromeClientCallback());
webView.setVisibility(View.INVISIBLE);
textView.setText("BEFORE POST RESULT");
if(getIntent().getExtras()!=null)
{
textView.setText("POST RESULT");
textView.setText(getIntent().getExtras().getString("code"));
String code=getIntent().getExtras().getString("code");
String postData = "code=" + URLEncoder.encode(code);
webView.postUrl(CustomString.url_aktivasi,postData.getBytes());
webView.setVisibility(View.VISIBLE);
}
}
private class webCallBack extends WebViewClient
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
return super.shouldOverrideUrlLoading(view,request);
}
@Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view,url);
}
}
private class webChromeClientCallback extends WebChromeClient {
@Override
public void onReceivedTitle(WebView webView,String title){
super.onReceivedTitle(webView,title);
}
}
public class MyJavascript {
Context mContext;
MyJavascript(Context context) {
mContext = context;
}
@JavascriptInterface
public void loadMainActivity(String url) {
Toast.makeText(PostresultActivity.this,"Reload", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(mContext,MainActivity.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
}
@JavascriptInterface
public void print(String textPrint,String namaPrinter) {
Toast.makeText(PostresultActivity.this,"PRINTING: "+textPrint,Toast.LENGTH_LONG).show();
IntentPrint(textPrint,namaPrinter);
}
}
public void IntentPrint(String txtvalue,String namaPrinter)
{
byte[] buffer = txtvalue.getBytes();
byte[] PrintHeader = { (byte) 0xAA, 0x55,2,0 };
PrintHeader[3]=(byte) buffer.length;
InitPrinter(namaPrinter);
if(PrintHeader.length>128)
{
value+="\nValue is more than 128 size\n";
Toast.makeText(PostresultActivity.this, value, Toast.LENGTH_LONG).show();
}
else
{
try
{
outputStream.write(txtvalue.getBytes());
outputStream.close();
socket.close();
}
catch(Exception ex)
{
value+=ex.toString()+ "\n" +"Excep IntentPrint \n";
Toast.makeText(PostresultActivity.this, value, Toast.LENGTH_LONG).show();
}
}
}
public void InitPrinter(String namaPrinter)
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try
{
if(!bluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals(namaPrinter)) //Note, you will need to change this to match the name of your device
{
bluetoothDevice = device;
Toast.makeText(this, "DEVICE FOUND: "+device.getName()+" "+bluetoothDevice, Toast.LENGTH_LONG).show();
break;
}
}
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
Method m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket) m.invoke(bluetoothDevice, 1);
bluetoothAdapter.cancelDiscovery();
socket.connect();
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
beginListenForData();
}
else
{
value+="No Devices found";
Toast.makeText(PostresultActivity.this, value, Toast.LENGTH_LONG).show();
return;
}
}
catch(Exception ex)
{
value+=ex.toString()+ "\n" +" InitPrinter \n";
Toast.makeText(PostresultActivity.this, value, Toast.LENGTH_LONG).show();
}
}
void beginListenForData() {
try {
final Handler handler = new Handler();
// this is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = inputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(
readBuffer, 0,
encodedBytes, 0,
encodedBytes.length
);
// specify US-ASCII encoding
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
// tell the user data were sent to bluetooth printer device
handler.post(new Runnable() {
public void run() {
Log.d("e", data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment