How to call this android bluetooth printing program from phonegap javascript? - java

i was made a bluetooth printer application (android based) for printing some text using datecs DPP-350 printer device. this program use a datecs external library such as bluetoohconnector and RFComm package. it works nicely, here's the code:
package com.myapp.MobilePrinter1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.djarum.MobilePrinter1.BluetoothConnector;
import com.datecs.api.card.FinancialCard;
import com.datecs.api.printer.Printer;
import com.datecs.api.printer.PrinterInformation;
import com.datecs.api.printer.ProtocolAdapter;
import com.datecs.api.printer.ProtocolAdapter.Channel;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MobilePrinter1Activity extends Activity {
public static final String CONNECTION_STRING = "connection_string";
private final Handler mHandler = new Handler();
private final Thread mConnectThread = new Thread() {
#Override
public void run() {
String connectionString = "bth://00:01:90:E6:40:52";
showProgress("Connecting");
if (connectionString.startsWith("bth://")) {
String address = connectionString.substring(6);
connectBth(address);
} else {
throw new IllegalArgumentException("Unsupported connection string");
}
dismissProgress();
}
void connectBth(String address) {
//setPrinterInfo(R.drawable.help, address);
try {
mBthConnector = BluetoothConnector.getConnector(MobilePrinter1Activity.this);
mBthConnector.connect(address);
mPrinter = getPrinter(
mBthConnector.getInputStream(),
mBthConnector.getOutputStream());
} catch (IOException e) {
//error(R.drawable.bluetooth, e.getMessage());
return;
}
mPrinterInfo = getPrinterInfo();
}
Printer getPrinter(InputStream in, OutputStream out) throws IOException {
ProtocolAdapter adapter = new ProtocolAdapter(in, out);
Printer printer = null;
if (adapter.isProtocolEnabled()) {
Channel channel = adapter.getChannel(ProtocolAdapter.CHANNEL_PRINTER);
InputStream newIn = channel.getInputStream();
OutputStream newOut = channel.getOutputStream();
printer = new Printer(newIn, newOut);
} else {
printer = new Printer(in, out);
}
return printer;
}
PrinterInformation getPrinterInfo() {
PrinterInformation pi = null;
try {
pi = mPrinter.getInformation();
//setPrinterInfo(R.drawable.printer, pi.getName());
} catch (IOException e) {
e.printStackTrace();
}
return pi;
}
};
private BluetoothConnector mBthConnector;
private Printer mPrinter;
private PrinterInformation mPrinterInfo;
private ProgressDialog mProgressDialog;
private BluetoothConnector mConnector;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
mConnector = BluetoothConnector.getConnector(this);
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
finish();
}
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printText();
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printBarcode();
}
});
findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printImage();
}
});
}
public void printText() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintText2();
dismissProgress();
}
}.start();
}
public void printBarcode() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintBarcode();
dismissProgress();
}
}.start();
}
public void printImage() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintImage();
dismissProgress();
}
}.start();
}
#Override
protected void onStart() {
super.onStart();
mConnectThread.start();
}
#Override
protected void onStop() {
super.onStop();
if (mBthConnector != null) {
try {
mBthConnector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void showProgress(final String text) {
mHandler.post(new Runnable() {
#Override
public void run() {
mProgressDialog = ProgressDialog.show(
MobilePrinter1Activity.this,
"Please wait",
text,
true);
}
});
}
private void showProgress(int resId) {
showProgress(getString(resId));
}
private void dismissProgress() {
mHandler.post(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
}
});
}
private void doPrintSelfTest() {
try {
mPrinter.printSelfTest();
} catch (IOException e) {
//error(R.drawable.selftest, getString(R.string.failed_print_self_test) + ". " +
//e.getMessage());
}
}
private void doPrintText2() {
EditText EditText1;
EditText1=(EditText)findViewById(R.id.editText1);
String temp;
try {
mPrinter.reset();
mPrinter.printTaggedText(EditText1.getText().toString());
//mPrinter.printTaggedText("Testing Testing!!");
mPrinter.feedPaper(110);
} catch (IOException e) {
//error(R.drawable.text, getString(R.string.failed_print_text) + ". " +
//e.getMessage());
}
}
private void doPrintBarcode() {
EditText EditText1;
EditText1=(EditText)findViewById(R.id.editText1);
try {
mPrinter.reset();
mPrinter.setBarcode(Printer.ALIGN_CENTER, false, 2, Printer.HRI_BOTH, 100);
mPrinter.printBarcode(Printer.BARCODE_CODE128, EditText1.getText().toString());
mPrinter.feedPaper(38);
mPrinter.feedPaper(110);
} catch (IOException e) {
//error(R.drawable.barcode, getString(R.string.failed_print_barcode) + ". " +
//e.getMessage());
}
}
private void doPrintImage() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo_djarum);
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
final int[] argb = new int[width * height];
bitmap.getPixels(argb, 0, width, 0, 0, width, height);
try {
mPrinter.reset();
mPrinter.printImage(argb, width, height, Printer.ALIGN_LEFT, true);
mPrinter.feedPaper(110);
} catch (IOException e) {
Toast.makeText(MobilePrinter1Activity.this, e.getMessage(), 1).show();
}
}
private void dialog(final int id, final String title, final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog dlg = new AlertDialog.Builder(MobilePrinter1Activity.this)
.setTitle(title)
.setMessage(msg)
.create();
dlg.setIcon(id);
dlg.show();
}
});
}
private void error(final int resIconId, final String message) {
mHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog dlg = new AlertDialog.Builder(MobilePrinter1Activity.this)
.setTitle("Error")
.setMessage(message)
.create();
dlg.setIcon(resIconId);
dlg.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
MobilePrinter1Activity.this.finish();
}
});
dlg.show();
}
});
}
private void setPrinterInfo(final int resIconId, final String text) {
mHandler.post(new Runnable() {
#Override
public void run() {
//((ImageView)findViewById(R.id.icon)).setImageResource(resIconId);
//((TextView)findViewById(R.id.name)).setText(text);
}
});
}
}
the main problems now is how to call this program from phonegap? i've tried using droidGap but it will give me error when i start the printer's thread. has anyone know how to solved this?? many thanks..

I dont think that you can invoke too many APIs from the standard android browser (except some like location, contacts n all), but what is possible is other way round embedding a webview in a native app(which can be your above mentioned thread code) and invoking this code from a Javascript event using JavaScript Interface apis of android platform (which is pretty straight forward).

Related

Attempt to invoke virtual method 'java.io.InputStream android.bluetooth.BluetoothSocket.getInputStream()'

I am trying to connect my android app with hc-06 for sending and receiving data purpose, below is the error occur and I've been stuck here from 3 days.
There error occured to me is
Attempt to invoke virtual method 'java.io.InputStreamandroid.bluetooth.BluetoothSocket.getInputStream()'
Kindly somebody solve it or provide me another working code for sending and receiving data through bluetoth hc-06 android app
package infoaryan.in.hc05_bluetooth;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class LedControl extends AppCompatActivity {
TextView textView;
Button btn1, btn2, btn3, btn4, btn5, btnDis;
String address = null;
TextView lumn;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
InputStream mmInputStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_led_control2);
Intent intent = getIntent();
address = intent.getStringExtra(MainActivity.EXTRA_ADDRESS);
btn1 = findViewById(R.id.button2);
btn2 = findViewById(R.id.button3);
//For additional actions to be performed
btn3 = findViewById(R.id.button5);
btn4 = findViewById(R.id.button6);
btn5 = findViewById(R.id.button7);
btnDis = findViewById(R.id.button4);
lumn = findViewById(R.id.textView2);
textView = findViewById(R.id.textView3);
new LedControl.ConnectBT().execute();
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("0");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("5");
}
});
btnDis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Disconnect();
}
});
beginListenForData();
}
private void sendSignal ( String givenumber ) {
if ( btSocket != null ) {
try {
btSocket.getOutputStream().write(givenumber.getBytes());
} catch (IOException e) {
msg("Error");
}
}
}
private void Disconnect () {
if ( btSocket!=null ) {
try {
btSocket.close();
} catch(IOException e) {
msg("Error");
}
}
finish();
}
private void msg (String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute () {
progress = ProgressDialog.show(LedControl.this, "Connecting...", "Please Wait!!!");
}
#Override
protected Void doInBackground (Void... devices) {
try {
if ( btSocket==null || !isBtConnected ) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
}
return null;
}
#Override
protected void onPostExecute (Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
} else {
msg("Connected");
isBtConnected = true;
}
progress.dismiss();
}
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.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);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
textView.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
#Override
protected void onResume() {
super.onResume();
}
}

Getting the value from textview

Hello guys I got a code that I do for my project, the code is to get the value of the heartbeat sensor from Arduino to my android phone using Bluetooth. So far it's going well it can send the value to my app without a problem. but the problem now is I want to get the value of it so I can use my algorithm with it, but seems like I got in a pickle now.
Here is the code :
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
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.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
What i want is to get the value of mTxtReceive on this :
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
I used System.out.println for seeing if i got the value but in the log it didn't show any thing.
So i need you guys wisdom for this any help?
Your view mTextReceive seems to be a TextView and therefore not editable:
private TextView mTxtReceive;
If it's not an EditText (editable) mTxtReceive.getEditableText will return null see docs
and getText should be called instead see docs.
Therefore your condition might always resolve from
if(txtLength > mMaxChars) into if(null > 50000) which is always false (or actually it might even crash before) and therefore your code inside the if-block is never executed
Try:
// recommended for debugging. Check if this is even called and if text length is really longer than max chars
Log.d(TAG, "text length:" + mTxtReceive.getText().length());
int txtLength = mTxtReceive.getText().length();
if(txtLength > mMaxChars){
// not sure what operation you want to do here but leave out for debugging
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getText().toString());
}
Also use Log.d instead of System.out.println since your log might otherwise not be forwarded to Logcat. Also are you sure this block is executed at all? I'd put a Log.d(TAG, "text length:" + mTxtReceive.getText().length()); outside of the condition for debugging purposes. And finally the obvious question would be if the txtLength is even longer than max chars (and that would be quite a long text with 50000 chars). But you can verify that simply with the recommended log outside the block as well.

Use Common MQTT class for Android APP

I am an novice android developer, I am using MQTT protocol for my android app.
I have found a code from internet for MQTT.But problem is that i have to use this MQTT Code for every activity which is redundant.I want to make a common java class
which can be call called any time whenever i need MQTT connection and communication.I have already tried but failed.Please anyone suggest me how to approach this?The code is given below
com.example.ab.mushroomv2;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class DashboardActivity extends AppCompatActivity {
final Context context = this;
//private EditText result;
private static final String TAG = "DA";
ProgressBar p_temp;
TextView progressingTemp;
MqttAndroidClient client;
String clientId;
static String topicTemp = "mushroom/temp";
String subMsg, top;
static String host = "tcp://iot.eclipse.org:1883";
Handler progressHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
p_temp = (ProgressBar) findViewById(R.id.progress_bar_temp);
progressingTemp = (TextViewfindViewById(R.id.progress_circle_temp_text);
establish();
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
establish();
}
#Override
public void messageArrived(String topic, MqttMessage message) throws
Exception {
subMsg = new String(message.getPayload());
top=new String(topic);
if(top.contains("temp"))
{
double a=Double.parseDouble(subMsg);
final int msgTemp = (int) a;
Log.d(TAG, String.valueOf(msgTemp));
new Thread(new Runnable() {
public void run() {
progressHandler.post(new Runnable() {
public void run() {
p_temp.setProgress(msgTemp);
progressingTemp.setText("" + msgTemp + " ℃
");
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
}
public void establish() {
clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(this.getApplicationContext(), host,
clientId);
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(DashboardActivity.this, "Client Connected",
Toast.LENGTH_SHORT).show();
try {
client.subscribe(topicTemp, 0);
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable
exception) {
Toast.makeText(DashboardActivity.this, "Client failed to
Connect", Toast.LENGTH_SHORT).show();
// establish();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
You need to create a singleton class. Here is an sample.
public class SocketIO {
private static final String TAG = SocketIO.class.getSimpleName();
private static SocketIO instance;
private Socket socket;
private SocketIO() {
try {
socket = IO.socket("http://ur_url_here");
} catch (URISyntaxException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
}
public static synchronized SocketIO getInstance() {
if (instance == null) {
instance = new SocketIO();
}
return instance;
}
public Socket getSocket() {
return socket;
}
public void open() {
if (socket != null)
socket.open();
}
public void close() {
if (socket != null)
socket.close();
}}

How to change layout background dynamically

I am having problem in my code.I am trying to change the layout background of my app every second.I used Thread in this code.I've searched the site but I couldn't find anything useful.Here is the code.
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
//private Bitmap open, close;
private LinearLayout myL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myL = (LinearLayout) findViewById(R.id.LinearLayout2);
// myL=(LinearLayout) findViewById(R.id.LinearLayout2);
//close = BitmapFactory.decodeResource(getResources(), R.drawable.kapa);
//open = BitmapFactory.decodeResource(getResources(), R.drawable.ac);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Thread th = new Thread() {
public void run() {
while (true) {
myL.setBackgroundResource(R.drawable.kapa);
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myL.setBackgroundResource(R.drawable.ac);
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
th.start();
}
}
From the answer to this question Change Layout background continuously...
Try using a Handler. Example...
public class MainActivity extends Activity {
final int CHANGE_BG_RES = 1;
final int RESOURCE_1 = R.drawable.kapa;
final int RESOURCE_2 = R.drawable.ac;
private LinearLayout myL;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (CHANGE_BG_RES == msg.what) {
int res = msg.arg1;
myL.setBackgroundResource(res);
int nextRes;
if (RESOURCE_1 == res)
nextRes = RESOURCE_2;
else
nextRes = RESOURCE_1;
Message m = obtainMessage (CHANGE_BG_RES, nextRes, 0, null);
sendMessageDelayed(m, 1000);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myL = (LinearLayout) findViewById(R.id.LinearLayout2);
}
#Override
protected void onResume() {
super.onResume();
Message m = handler.obtainMessage(CHANGE_BG_RES, RESOURCE_1, 0, null);
handler.sendMessageDelayed(m, 1000);
}
}
Try this:
public class MainActivity extends Activity {
//private Bitmap open, close;
private LinearLayout myL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myL = (LinearLayout) findViewById(R.id.LinearLayout2);
// myL=(LinearLayout) findViewById(R.id.LinearLayout2);
//close = BitmapFactory.decodeResource(getResources(), R.drawable.kapa);
//open = BitmapFactory.decodeResource(getResources(), R.drawable.ac);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Runnable runnable = new Runnable() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.kapa);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.ac);
}
});
}
}
};
new Thread(runnable).start();
}
}

Display success message after file is copied

I am fairly new to Android development so I thought I would start off with a basic app. When a button is pressed, it copies a file to the location written in the code (see my code below). When I press the install button and the file is copied to its location, I want a toast message to display "Successfully Installed or Error while copying file". How would I implement this?
public class TrialActivity extends Activity {
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runDialog(5);
}
private void runDialog(final int seconds)
{
progressDialog = ProgressDialog.show(this, "Please Wait...", "unpacking patch in progress");
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(seconds * 1000);
progressDialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
((Button)findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramView)
{
}
{
InputStream in = null;
OutputStream out = null;
String filename="savegame.bin";
try {
in = getResources().openRawResource(R.raw.savegame);
out = new FileOutputStream("/sdcard/Android/data/files/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
);
}
}
use next code:
private class AsyncTaskDialog extends AsyncTask<Void, Void, Void> {
Toast toastSuccess;
boolean flagSuccessCopy =false;
protected void onPreExecute() {
super.onPreExecute();
}
}
protected Boolean doInBackground(Void... params) {
copyFiles();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (getActivity() != null) {
if(flagSuccessCopy){
toastSuccess = Toast.makeText(context, "Success", duration);
}else{
toastSuccess = Toast.makeText(context, "Error", duration);
}
toast.show();
}
}
Allows to copy any file from any application to SD card
import ru.gelin.android.sendtosd.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ProgressDialog extends AlertDialog implements Progress {
/** Activity for which the dialog is created */
Activity activity;
/** Progress manager for the dialog */
ProgressManager manager = new ProgressManager();
/**
* Creates the customized progress dialog for
* activity.
*/
protected ProgressDialog(Activity activity) {
super(activity);
}
#Override
public void setFiles(int files) {
synchronized (manager) {
manager.setFiles(files);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateTotalProgress();
}
}
});
}
#Override
public void nextFile(final File file) {
synchronized (manager) {
manager.nextFile(file);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateFileName(file);
updateFileProgress();
updateTotalProgress();
}
}
});
}
#Override
public void processBytes(long bytes) {
synchronized (manager) {
manager.processBytes(bytes);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateFileProgress();
}
}
});
}
void updateTotalProgress() {
ProgressBar progress = (ProgressBar)findViewById(R.id.total_progress);
progress.setMax(manager.getFiles());
progress.setProgress(manager.getFile());
TextView text = (TextView)findViewById(R.id.total_files);
text.setText(getContext().getString(R.string.files_progress,
manager.getFile(), manager.getFiles()));
}
void updateFileName(File file) {
if (file == null) {
return;
}
TextView view = (TextView)findViewById(R.id.file_name);
view.setText(file.getName());
}
void updateFileProgress() {
ProgressBar progress = (ProgressBar)findViewById(R.id.file_progress);
if (manager.getProgressInUnits() < 0) {
progress.setIndeterminate(true);
} else {
progress.setIndeterminate(false);
progress.setMax((int)(manager.getSizeInUnits() * 10));
progress.setProgress((int)(manager.getProgressInUnits() * 10));
}
TextView text = (TextView)findViewById(R.id.file_size);
text.setText(getContext().getString(manager.getSizeUnit().progressString,
manager.getProgressInUnits(), manager.getSizeInUnits()));
}
}
source: http://code.google.com/p/sendtosd-android/source/browse/src/ru/gelin/android/sendtosd/progress/ProgressDialog.java?spec=svn0933973391a12bee4759a32f5776864c64022d71&r=0933973391a12bee4759a32f5776864c64022d71

Categories