All,
I would greatly appreciate some help. We have a system that is being sent data at 2 Hz (every 0.5 sec). My application is supposed to start acquiring this data upon the press of a "start" button through a handler, and upon pressing the "stop" button, the user can choose to save the data collected. If save is chosen, a new activity is SUPPOSED to be started, however, my application crashes. The error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(int)' on a null object reference
at com.example.cherryjp.buttonapp.StartNewSessionActivity$2.onClick(StartNewSessionActivity.java:130)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
and my code:
package com.example.cherryjp.buttonapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Set;
import java.util.Timer;
import java.util.UUID;
/**
*/
public class StartNewSessionActivity extends AppCompatActivity {
final int MSG_START_TIMER = 0;
final int MSG_STOP_TIMER = 1;
final int MSG_UPDATE_TIMER = 2;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
long startTime;
Double endTime;
TextView watch;
Double totalSeconds;
Double seconds;
Double minutes;
Double hours;
String time;
boolean recording = false;
String fromBluetooth;
BluetoothAdapter mBluetoothAdapter;
ArrayAdapter mArrayAdapter;
final Context context = this;
final int REFRESH_RATE = 100;
Stopwatch timer = new Stopwatch();
Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
watch.setText("" + timer.toString());
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER, REFRESH_RATE); //text view is updated every second,
if(writeBuf == null){
break;
}
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
fromBluetooth += writeMessage;
fromBluetooth += "\t";
break;
//though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
//send reset signal for bluetooth
if(recording) {
launchSaveDialog();
}
recording = false;
watch.setText("" + timer.toString());
break;
default:
break;
}
}
};
private BluetoothDevice mDevice;
public void launchSaveDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to save that run?")
.setTitle("Save confirmation");
AlertDialog.Builder builder1 = builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Entry entry = new Entry();
entry.setDate(MySQLiteHelper.getCurrentDateTime(context));
entry.setRiderId(getIntent().getExtras().getLong("RIDER_ID"));
//TODO: loop to pull values from bluetooth transmission
//String fromBluetooth = "5\t1\t3\t2\t5\t3\t3\t4";
String tempString = fromBluetooth;
tempString = fromBluetooth.substring(fromBluetooth.indexOf('\t')+1);
entry.setForceAndTimeTabSeparated(tempString);
MainActivity.riderdb.addEntry(entry);
Toast.makeText(getApplicationContext(),
"Run saved!", Toast.LENGTH_SHORT).show();
showGraph(entry);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void showGraph(Entry entry){
Intent immediateGraphIntent = new Intent(this, ImmediateGraph.class);
final int result = 1;
//Just getEntry on next intent instead of storing extras.
immediateGraphIntent.putExtra("ENTRY_ID", entry.getId());
//immediateGraphIntent.putExtra("PASSTIME", timeArray);
//immediateGraphIntent.putExtra("PASSFORCE", forceArray);
startActivity(immediateGraphIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.session_start_page);
Button startButton = (Button) findViewById(R.id.startsessionbutton);
Button endButton = (Button) findViewById(R.id.endsessionbutton);
watch = (TextView)findViewById(R.id.watch);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
}
}
final ConnectThread mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//START recording stuff.
recording = true;
while(mConnectThread.mConnectedThread == null){
}
mConnectThread.mConnectedThread.write("begin".getBytes());
mHandler.sendEmptyMessage(MSG_START_TIMER);
}
});
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//END recording stuff
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
});
}
public class Stopwatch {
private long startTime = 0;
private boolean running = false;
private long currentTime = 0;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.running = false;
}
public void pause() {
this.running = false;
currentTime = System.currentTimeMillis() - startTime;
}
public void resume() {
this.running = true;
this.startTime = System.currentTimeMillis() - currentTime;
}
//elaspsed time in milliseconds
public long getElapsedTimeMili() {
long elapsed = 0;
if (running) {
elapsed =((System.currentTimeMillis() - startTime)/100) % 10 ;
}
return elapsed;
}
//elaspsed time in seconds
public long getElapsedTimeSecs() {
long elapsed = 0;
if (running) {
elapsed = ((System.currentTimeMillis() - startTime) / 1000) % 60;
}
return elapsed;
}
//elaspsed time in minutes
public long getElapsedTimeMin() {
long elapsed = 0;
if (running) {
elapsed = (((System.currentTimeMillis() - startTime) / 1000) / 60 ) % 60;
}
return elapsed;
}
//elaspsed time in hours
public long getElapsedTimeHour() {
long elapsed = 0;
if (running) {
elapsed = ((((System.currentTimeMillis() - startTime) / 1000) / 60 ) / 60);
}
return elapsed;
}
public String toString() {
return String.format("%1$02d:%2$02d:%3$02d.%4$01d", getElapsedTimeHour(), getElapsedTimeMin(), getElapsedTimeSecs(), getElapsedTimeMili());
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private ConnectedThread mConnectedThread;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "\n".getBytes()[0]) {
mHandler.obtainMessage(MSG_UPDATE_TIMER, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Any thoughts on this? I'm completely out of ideas on what is causing this to crash... something with the bluetooth connectivity, maybe?
Thanks,
John
fromBluetooth is null, and you can't call indexOf(...) on a null String.
You must therefore ensure that fromBluetooth isn't null (good) or handle the case where fromBluetooth is null (better) (e.g. if (fromBluetooth != null) execute logic).
Enjoy
Replace your code
if(fromBluetooth!=null){
tempString = fromBluetooth.substring(fromBluetooth.indexOf('\t')+1);
}
with
fromBluetooth.substring(fromBluetooth.indexOf('\t')+1);
because you not checking string is null or not and directly findvalue using indexOf();
Related
I set a program to send data from the android app to a microcontroller through bluetooth using SPP. mentioned microcontroller device sends a response back after 150 milisec as processing time. My app receives an appropriate response by bluetooth response handler as RecieveBuffer.And application must send data again for the case when the microcontroller doesn't send an appropriate. I used a while conditional statement like below to send data alternatively until getting a response (send flag is true after app gets an appropriate response by bluetooth response handler class).
while(!SendFlag) SendData( SendBuffer+"\r" );
there is a program that my program sends data consecutively and Bluetooth response handler never gets any response since while statement that checks send flag(send flag is true after app gets an appropriate response).
How can I set a delay that makes my app waiting for the response? I mean I have to send data and wait for the response and if response is inacceptable I have to send data again.
without while statement, I can send data and get a response. but I have to check whether received data are acceptable too.
package com.np.schoolbell;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import ir.mirrajabi.persiancalendar.PersianCalendarView;
import ir.mirrajabi.persiancalendar.core.PersianCalendarHandler;
import ir.mirrajabi.persiancalendar.core.models.PersianDate;
public class ledControl extends AppCompatActivity {
EditText et_SendData;
static TextView tv_DataReaded;
PersianCalendarView persianCalendarView;
PersianCalendarHandler calendar;
PersianDate today;
PersianDate sampleday;
List days;
String address = null;
static String TransmiterCode="999";
static String SendBuffer=null;
static String RecieveBuffer=null;
static int Counter=0;
static boolean SendFlag=false;
BluetoothAdapter bAdapter = null;
BluetoothDevice bDevice = null;
BluetoothSocket bSocket = null;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //SPP UUID. Look for it
ConnectedThread cThread;
private static BluetoothResponseHandler brHandler;
private final static int DataIsReady = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_led_control);
persianCalendarView = (PersianCalendarView)findViewById(R.id.persian_calendar2);
calendar = persianCalendarView.getCalendar();
today = calendar.getToday();
//days=calendar.getDays(1);
//Toast.makeText(this, days.toString(), Toast.LENGTH_LONG).show();
//today.setDate(1398,05,01);
//Toast.makeText(this, today.toString(), Toast.LENGTH_LONG).show();
et_SendData = (EditText) findViewById(R.id.et_SendData);
tv_DataReaded = (TextView) findViewById(R.id.tv_DataReaded);
address = getIntent().getStringExtra( "device_address" );
bAdapter = BluetoothAdapter.getDefaultAdapter();
try {
Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_SHORT).show();
if( bSocket == null ) {
bDevice = bAdapter.getRemoteDevice(address);
bSocket = bDevice.createInsecureRfcommSocketToServiceRecord(myUUID);
bAdapter.cancelDiscovery();
bSocket.connect();
}
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Connection Failed. Is it a SPP Bluetooth? Try again.", Toast.LENGTH_SHORT).show();
finish();
}
cThread = new ConnectedThread(bSocket);
cThread.start();
if (brHandler == null) brHandler = new BluetoothResponseHandler(this);
else brHandler.setTarget(this);
}
public void onClick_btn_SendData( View v ) {
SendBuffer=LoadDateTimeBuffer();
while(!SendFlag) SendData( SendBuffer+"\r" );
SendBuffer=LoadAZanSetting();
while(!SendFlag) SendData( SendBuffer+"\r" );
et_SendData.setText("");
}
public String LoadDateTimeBuffer(){
SendFlag=false;
TransmiterCode="420";
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss", Locale.getDefault());
String currentTime = sdf.format(new Date());
String currentDate=ParseFaDigits.convert(calendar.formatNumber(today.getYear()))+ParseFaDigits.convert(calendar.formatNumber(today.getMonth()))+ParseFaDigits.convert(calendar.formatNumber(today.getDayOfMonth()));
return TransmiterCode+currentTime+currentDate;
}
public String LoadAZanSetting(){
SendFlag=false;
TransmiterCode="421";
boolean fajrflag=true;boolean tolueflag=true;boolean zuhrflag=true;boolean maghribflag=true;boolean ishaflag=true;
String FajrFlagString = (fajrflag) ? "1" : "0";
String TolueFlagString = (tolueflag) ? "1" : "0";
String ZuhrFlagString = (zuhrflag) ? "1" : "0";
String MaghribFlagString = (maghribflag) ? "1" : "0";
String IshaFlagString = (ishaflag) ? "1" : "0";
return TransmiterCode+FajrFlagString+TolueFlagString+ZuhrFlagString+MaghribFlagString+IshaFlagString;
}
public void SendData(String Data) {
if( bSocket != null ) {
try {
bSocket.getOutputStream().write(Data.getBytes());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error in Send Data", Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Bluetooth is Not Connected", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if( bSocket == null ) return;
if( bSocket.isConnected() ) {
Disconnect();
}
}
public void onClick_Bluetooth_btn_Disconnect( View v ) {
Disconnect();
}
public void Disconnect() {
if ( bSocket != null && bSocket.isConnected() ) {
try {
bSocket.close();
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
}
catch( IOException e ) {
Toast.makeText(getApplicationContext(), "Error in Disconnecting ", Toast.LENGTH_SHORT).show();
}
}
finish();
}
public static class ConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private InputStream mmInStream;
private OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
//Tell other phone that we have connected
write("connected".getBytes());
}
public void run() {
byte[] buffer = new byte[512];
int bytes;
StringBuilder readMessage = new StringBuilder();
while( !this.isInterrupted() ) {
try {
bytes = mmInStream.read(buffer);
String readed = new String(buffer, 0, bytes);
readMessage.append(readed);
if (readed.contains("\r")) {
brHandler.obtainMessage(ledControl.DataIsReady, bytes, -1, readMessage.toString()).sendToTarget();
readMessage.setLength(0);
}
} catch (Exception e) {
break;
}
}
}
// Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
// Call this from the main activity to shutdown the connection
public void cancel() {
if (mmInStream != null) {
try {mmInStream.close();} catch (Exception e) {}
mmInStream = null;
}
if (mmOutStream != null) {
try {mmOutStream.close();} catch (Exception e) {}
mmOutStream = null;
}
if (mmSocket != null) {
try {mmSocket.close();} catch (Exception e) {}
mmSocket = null;
}
this.interrupt();
}
}
private static class BluetoothResponseHandler extends Handler {
private WeakReference<ledControl> mActivity;
public BluetoothResponseHandler(ledControl activity) {
mActivity = new WeakReference<ledControl>(activity);
}
public void setTarget(ledControl target) {
mActivity.clear();
mActivity = new WeakReference<ledControl>(target);
}
#Override
public void handleMessage(Message msg) {
ledControl activity = mActivity.get();
String Data = (String)msg.obj;
if (activity != null) {
switch (msg.what) {
case DataIsReady :
if( Data == null ) return;
RecieveBuffer=Data;
if(RecieveBuffer.contains(SendBuffer))
{
tv_DataReaded.append(Data);
SendFlag=true;
TransmiterCode="";
SendBuffer="";
RecieveBuffer="";
}
else
{
SendFlag=false;
}
break;
}
}
}
}
}
Thank you a lot in advance.
I found a way to solve the mentioned problem so that I applied a CountDownTimer which sends data every 1 sec through 3 sec and the timer will be canceled due to avoid wasting time if sent data and response are ok both. in regular conditions, this timer sends data once since the application receives an appropriate response.
SendBuffer=LoadDateTimeBuffer();
CountDownTimer yourCountDownTimer=new CountDownTimer(3000, 1000) {
public void onFinish() {
Toast.makeText(ledControl.this, "Error", Toast.LENGTH_SHORT).show();
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
if(!SendFlag)SendData( SendBuffer+"\r" );
else {Toast.makeText(ledControl.this, "sent", Toast.LENGTH_SHORT).show();this.cancel();}
}
}.start();
I have an arduino car which I wish to control via Bluetooth from my android phone. I've made an application for this, but when i try to send multiple consecutive messages through my OutputStream.write function, they get sent as a single, concatinated message. For example: if I call connectedThread.write("200-100"); and then connectedThread.write("300-150"), on my serial monitor it shows up as a single message: "200-100300-150". I have seen this same problem in other StackOverflow posts ( OutputStream.write() never ends , Android outputStream.write send multiple messages ), but they don't have an answer that works for me, I tried using connectedThread.flush() and it doesn't help. Here is my code (the connecting part is in another Activity, and it works fine):
package com.clickau.cosmin.bluetootharduinocarcontroller;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Controls extends AppCompatActivity {
private SeekBar speed;
private SeekBar direction;
private BluetoothSocket btSocket = DataHolder.getData();
private ConnectedThread connectedThread;
private int speedValue;
private int directionValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controls);
speed = (SeekBar) findViewById(R.id.speed);
direction = (SeekBar) findViewById(R.id.direction);
speedValue = speed.getProgress();
directionValue = direction.getProgress();
speed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser)
{
speedValue = speed.getProgress()/5;
speedValue*=5;
directionValue = direction.getProgress()/5;
directionValue*=5;
/*StringBuilder str = new StringBuilder();
if (speedValue == 255)
str.append("STOP");
else
{
if (speedValue > 255)
{
str.append(speedValue - 255);
str.append('F');
}
else if (speedValue < 255)
{
str.append(255-speedValue);
str.append('S');
}
if (directionValue > 100)
{
str.append('D');
str.append(directionValue-100);
}
else if (directionValue < 100)
{
str.append('S');
str.append(100 - directionValue);
}
}
str.append('\n');
connectedThread.write(str.toString());*/
connectedThread.write(speedValue+ "+" + directionValue);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
speed.setProgress(255);
speedValue = speed.getProgress();
}
});
direction.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser)
{
speedValue = speed.getProgress()/5;
speedValue*=5;
directionValue = direction.getProgress()/5;
directionValue*=5;
/*StringBuilder str = new StringBuilder();
if (speedValue == 255)
str.append("STOP");
else
{
if (speedValue > 255)
{
str.append(speedValue - 255);
str.append('F');
}
else if (speedValue < 255)
{
str.append(255-speedValue);
str.append('S');
}
if (directionValue > 100)
{
str.append('D');
str.append(directionValue-100);
}
else if (directionValue < 100)
{
str.append('S');
str.append(100 - directionValue);
}
}
str.append('\n');
connectedThread.write(str.toString());*/
connectedThread.write(speedValue+ "+" + directionValue);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
direction.setProgress(100);
directionValue = direction.getProgress();
}
});
connectedThread = new ConnectedThread(btSocket);
connectedThread.start();
}
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}catch(IOException e) {
Log.e("ERROR", "Connected Thread");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
/*public void run()
{
byte[] buffer = new byte[256];
int bytes;
while (true)
{
try{
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
bluetoothIn.obtainMessage(handlerState, bytes, -1 ,readMessage).sendToTarget();
} catch (IOException e)
{
break;
}
}
}*/
public void write(String input)
{
byte[] msgBuffer = input.getBytes();
try{
mmOutStream.write(msgBuffer);
mmOutStream.flush();
}catch(IOException e)
{
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
I think this might be an optimization for bluetooth, but it's really annoying because I need those messages to be sent sepparatly when I move the controls, not 10 seconds afterwards. Anyone know how to solve this?
I am trying to program that will display a notification when bluetooth device (arduino uno)disconnected or out of range.
When i testing ,power off the bluetooth device,phone has delay 20s show the notificatoin.
I don't know why,hope somebody help me figure it out.
package com.example.arduinosensors;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import android.app.Activity;
import android.app.AlertDialog;
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.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnOn, btnOff;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
public static final int handlerState = 0,MESSAGE_LOST_CONNECT = 1; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private Vibrator mVibrator;
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your bluetooth devices MAC address
private static String address = "20:14:12:03:11:31";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
mVibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V"); //update the textviews with sensor values
sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
}
}
if(msg.what == MESSAGE_LOST_CONNECT) { //
//Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
mVibrator.vibrate(new long[]{10, 100, 100, 100}, -1);
new AlertDialog.Builder(MainActivity.this)
.setTitle("bluetooth disconnected")
.setIcon(R.drawable.blue1)
.setMessage("bluetooth out of range")
.setPositiveButton("yes", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i)
{
//finish();
}
})
.setNegativeButton("cancel", new
DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int i)
{
}
})
.show();
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
//address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
#Override
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "裝置並不支援藍芽", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
private void connectionLost() { //斷線通知副程式
// Send a failure message back to the Activity
Message msg = bluetoothIn.obtainMessage(MainActivity.MESSAGE_LOST_CONNECT);
bluetoothIn.sendMessage(msg);
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
connectionLost();
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "連線失敗", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
I am implementing a simple app that sends and receives data between two devices via bluetooth.
I am following the android developer's blog's bluetoothchat example, but my application seems unable to read from the inputstream of a socket.
Writing to the socket is fine. The app does not throw an error nor update the textview as it is supposed to. Any help would be appreciated. Thank you!
Main activity.java(where list of devices are shown and selected) - probably not the errored file:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
private final static int REQUEST_ENABLE_BT = 22;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "Bluetooth!";
ListView listView;
ArrayList<BluetoothDevice> deviceList;
ArrayAdapter<String> arrayAdapter;
ScanReciever reciever;
BluetoothAdapter bluetooth_adapter;
Button onButton;
Button scanButton;
Button alreadyButton;
AcceptThread acceptThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceList = new ArrayList<>();
//arrayAdapter = new ArrayAdapter<>(this, R.xml.table_item, android.R.id.text1, deviceList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.table_item);
// Set up Buttons
onButton = (Button) findViewById(R.id.onButton);
scanButton = (Button) findViewById(R.id.scanButton);
onButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
askAdapterOn();
}
});
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanForDevices();
}
});
// Set up listview
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
callButtons(deviceList.get(position));
}
});
// Bluetooth setup.
bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
// If device is incapable of using bluetooth:
if (bluetooth_adapter == null) {
onButton.setEnabled(false);
scanButton.setEnabled(false);
}
else if (!bluetooth_adapter.isEnabled()) { // If bluetooth is off:
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
else { // Bluetooth is on and ready:
onButton.setEnabled(false);
scanButton.setEnabled(true);
alreadyButton = (Button) findViewById(R.id.alreadyButton);
alreadyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Collect current devices into a set.
Set<BluetoothDevice> pairedDevices = bluetooth_adapter.getBondedDevices();
// Pass the index of the paired device
if (pairedDevices.size() > 0) {
callButtons(pairedDevices.iterator().next()); // First element in set.
} else {
System.out.println("No paired Device!");
}
}
});
acceptThread = new AcceptThread();
acceptThread.start();
}
}
private class ScanReciever extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
System.out.println("Started");
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("finished");
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("FOUND: " + device.getName());
deviceList.add(device);
arrayAdapter.add(device.getName()+" - Click to pair");
arrayAdapter.notifyDataSetChanged();
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
System.out.println("Connected~!!!!!!!!!!!!!!");
callButtons(deviceList.get(deviceList.size()-1));
}
}
};
protected void askAdapterOn() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
protected void scanForDevices() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
reciever = new ScanReciever();
registerReceiver(reciever, filter);
bluetooth_adapter.startDiscovery();
}
protected void callButtons(BluetoothDevice bd) {
bluetooth_adapter.cancelDiscovery();
Intent toButton = new Intent(getApplicationContext(), buttons.class);
toButton.putExtra("selected",bd);
startActivity(toButton);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK){
if (bluetooth_adapter.isEnabled()){
onButton.setEnabled(false);
scanButton.setEnabled(true);
}
else {
onButton.setEnabled(true);
scanButton.setEnabled(false);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDestroy() {
unregisterReceiver(reciever);
super.onDestroy();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetooth_adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
System.out.println("READY TO ACCEPT");
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
Buttons.java(where the app will initiate a connection and maintain communication) - probably the file with the error:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class buttons extends Activity {
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
BluetoothDevice selected;
BluetoothAdapter bluetoothAdapter;
TextView tv;
Button button1;
Button button2;
Button button3;
Button unpairB;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
ConnectThread connectThread;
ConnectedThread connectedThread;
BluetoothSocket mmSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
selected = getIntent().getExtras().getParcelable("selected");
pair(selected);
connectedThread = null;
try {
connectedThread = new ConnectedThread(mmSocket);
connectedThread.start();
System.out.println("ConnectedThread started!");
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
// Set up Buttons
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
unpairB = (Button) findViewById(R.id.unpairButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(2);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonPressed(3);
}
});
unpairB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unpair(selected);
finish();
}
});
// Set up textview
tv = (TextView) findViewById(R.id.textView);
tv.setText("connected to: " + selected.getName());
}
protected void buttonPressed(int i) {
connectedThread.write(i);
tv.setText(Integer.toString(i));
}
private void pair(BluetoothDevice device) {
connectThread = new ConnectThread(device);
connectThread.start();
}
private void unpair(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e("unpair()", e.getMessage());
}
}
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("Socket was created in ConnectThread");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
// bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
this.bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
System.out.println("Connected to " + socket.getRemoteDevice().getName());
try {
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
if (inputStream == null) System.out.println("Inputstream is null");
else System.out.println("Inputstream is safe");
if (outputStream == null) System.out.println("outstream is null");
else System.out.println("Outputstream is safe");
while (true) {
try {
System.out.println("Blocking?");
bytes = inputStream.read(buffer);
System.out.println("NO");
handler.obtainMessage(MESSAGE_READ, bytes, -1,
buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(int i) {
try {
byte[] buffer = new byte[1024];
buffer[0] = (byte) i;
outputStream.write(buffer);
outputStream.flush();
handler.obtainMessage(MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
System.out.println("Write SUCCESS!!!!!!!!!!!!!!");
} catch (IOException e) {
System.out.println("write ERRORRRRRRRRRRRRRRRRR");
}
}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
}
}
}
private final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
System.out.println("Write was broadcasted");
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(Integer.toString(writeBuf[0]));
///tv.setText(writeMessage);
break;
case MESSAGE_READ:
System.out.println("Read was broadcasted");
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(Integer.toString(readBuf[0]));
tv.setText(readMessage);
break;
}
}
};
}
i need to display message to application user when admin pushes message on browser. for that i implemented a timer so that it displays a message to user on application start. timer keeps running to get as message once in 20 minutes if a new message is pushed. my timer is working fine but on button click.
I want my timer to start as soon as activity loads.
Is this proper way to display a message? (it is like banner)
How resource consuming is a timer?
Timer Task
class secondTask extends TimerTask {
#Override
public void run() {
TestBannerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
fl.setVisibility(View.VISIBLE);
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
text2.setText(String.format("%d:%02d", minutes,
seconds));
}
});
}
};
button click event
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timer.cancel();
timer.purge();
b.setText("start");
} else {
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new secondTask(), 8000, 1200000);
b.setText("stop");
}
}
});
you can use this code:
package packagename.timerService;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
public class TimerService extends Service{
public static final String BROADCAST_TIMER_ACTION = "packagename.timerService.TimerService";
private final Handler handler = new Handler();
private final Handler updateUIHandler = new Handler();
Intent intent;
int time = 0;
private int durationTime = 0;
private int starDate;
private int currentDate;
private Date startTaskDate;
private String taskComment;
#Override
public void onCreate() {
// Called on service created
intent = new Intent(BROADCAST_TIMER_ACTION);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
handler.removeCallbacks(sendUpdatesToUI);
handler.post(sendUpdatesToUI); //post(sendUpdatesToUI);
starDate = Calendar.getInstance().get(Calendar.DATE);
durationTime = 0;
startTaskDate = new Date();
}
} catch (Exception e) {}
return START_STICKY;
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
try{
displayLoggingInfo();
time ++;
durationTime ++;
handler.postDelayed(this, 60 * 1000); // 1 minute
}catch (Exception e) { }
}
};
private Runnable sendUpdatesToUIOnResume = new Runnable() {
public void run() {
displayLoggingInfoForOnResume();
}
};
private void displayLoggingInfoForOnResume() {
try{
currentDate = Calendar.getInstance().get(Calendar.DATE);
intent.putExtra("changeDate", String.valueOf(false));
intent.putExtra("time", String.valueOf(time == 0 ? time : time - 1 ));
sendBroadcast(intent);
} catch (Exception e) { }
}
private void displayLoggingInfo() {
try{
currentDate = Calendar.getInstance().get(Calendar.DATE);
intent.putExtra("changeDate", String.valueOf(false));
intent.putExtra("durationTime", String.valueOf(durationTime));
intent.putExtra("time", String.valueOf(time));
sendBroadcast(intent);
}catch (Exception e) {
// TODO: handle exception
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
try {
handler.removeCallbacks(sendUpdatesToUI);
updateUIHandler.removeCallbacks(sendUpdatesToUIOnResume);
durationTime = 0;
time = 0;
super.onDestroy();
} catch (Exception e) { }
}
#Override
public boolean stopService(Intent name) {
handler.removeCallbacks(sendUpdatesToUI);
updateUIHandler.removeCallbacks(sendUpdatesToUIOnResume);
durationTime = 0;
time = 0;
return super.stopService(name);
}
}