Start Timer on activity create method android - android

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);
}
}

Related

Android thread error

The thread in my application is giving a weird error on the myThread.start() function specifically the start is wrong the error is "Cannot resolve symbol start" . initially i thought it was a bracket issue but when i adjust them it ends up breaking the OnClicklistner. The thread is suppose just suppose to make the user wait before doing a set text and then the following button will take the user to a website. Can any one see my error?
package com.example.trap.york_hw6;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
public class Main3Activity extends AppCompatActivity implements View.OnClickListener {
Button Cheat;
Button NextPage3;
WebView browser3;
#SuppressLint("HandlerLeak")
Handler handler = new Handler() {
public void handleMessage(Message msg) {
TextView statement = (TextView) findViewById(R.id.snitch);
statement.setText("Checking to see if your a cop");
}
;
};
#SuppressLint("HandlerLeak")
Handler handler2 = new Handler() {
public void handleMessage(Message msg) {
browser3.loadUrl("https://www.youtube.com");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
browser3 = (WebView) findViewById(R.id.webkit3);
browser3.getSettings().setJavaScriptEnabled(true);
browser3.getSettings().setDomStorageEnabled(true);
Cheat = (Button) findViewById(R.id.CC);
NextPage3 = (Button) findViewById(R.id.Next3);
NextPage3.setOnClickListener(this);
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
;
Thread myThread = new Thread(r);
myThread.start();
};
}
});
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
;
Thread myThread2 = new Thread(r2);
myThread2.start();
};
}
public void onClick(View v) {
Intent i = new Intent(this, Main4Activity.class);
i.putExtra("value", "I got this from MainActivity2");
i.putExtra("value1", 5);
startActivityForResult(i, 3);
}
}
You are starting thread inside wrong block. Try the code below .
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
};
};
Thread myThread2 = new Thread(r2);
myThread2.start();
AND
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
};
};
Thread myThread = new Thread(r);
myThread.start();
}
});
You can not initialise and start Runnable inside its block.
You can write like this.
Cheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable r = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
};
Thread myThread = new Thread(r);
myThread.start();
}
});
and second one
final Runnable r2 = new Runnable() {
public void run() {
long futureTime = System.currentTimeMillis() + 7000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
handler.sendEmptyMessage(0);
}
};
Thread myThread2 = new Thread(r2);
myThread2.start();
Suggestion : Also i seen your onClick method, i suggest you check clicked button's id before doing any action like. Because if you have multiple buttons having OnClickListener referring to current class, you will need to check.
public void onClick(View v) {
switch (v.getId()){
case R.id.Next3:
Intent i = new Intent(this, Main4Activity.class);
i.putExtra("value", "I got this from MainActivity2");
i.putExtra("value1", 5);
startActivityForResult(i, 3);
break;
}
}

How to stop timer in timer task and re-enable a button after timer stops?

I am trying to create an App with timer in it using service, however the timer works fine but there is a problem in my code when timer completed (comes to 0:0) my button should again re enable automatically but it stays on disabled state only, I tried a lot to re enable it but did not solved.
So please see my code below and tell me what should I do to re enable it?
I am new to services and android , any help will be appreciated
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
et_hours.setVisibility(View.INVISIBLE);
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(false);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(false);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(true);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void listener() {
btn_start.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
et_hours.setText("1");
et_hours.setEnabled(false);
btn_start.setEnabled(false);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("mm:ss");
date_time = simpleDateFormat.format(calendar.getTime());
mEditor.putString("data", date_time).commit();
mEditor.putString("hours", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
TimerService.java
public class Timer_Service extends Service {
public static String str_receiver = "com.countdowntimerservice.receiver";
private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("mm:ss");
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("mm:ss");
strDate = simpleDateFormat.format(calendar.getTime());
Log.e("strDate", strDate);
TimeDifference();
}
});
}
}
public String TimeDifference() {
try {
date_current = simpleDateFormat.parse(strDate);
} catch (Exception e) {
}
try {
date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
} catch (Exception e) {
}
try {
long diff = date_current.getTime() - date_diff.getTime();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.MINUTES.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
//long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours >= 0) {
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", diffMinutes2, diffSeconds2);
//String str_testing = diffMinutes2 + ":" + diffSeconds2;
Log.e("TIME", timeLeftFormatted);
if (long_hours == 0){
mEditor.putBoolean("finish", true);
mTimer.cancel();
}
updateTime(timeLeftFormatted);
} else {
mEditor.putBoolean("finish", true).commit();
mTimer.cancel();
}
}catch (Exception e){
mTimer.cancel();
mTimer.purge();
}
return "";
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish","Finish");
}
private void updateTime(String str_time){
intent.putExtra("time",str_time);
sendBroadcast(intent);
}
}
First, make your Intent an instance variable like-
private Button btn_start;
private TextView tv_timer;
.
.
private Intent intent_service;
inside init() your code should look like-
intent_service = new Intent(getApplicationContext(), Timer_Service.class);
.
.
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(false);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false); // a change is here
tv_timer.setText(str_value);
}
and inside the onClick(View v) add this line of code-
mEditor.putBoolean("finish", false).commit();
.
.
startService(intent_service); // start the service
Now change your BroadcastReceiver-
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
To
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
if (str_time.equals("00:00")) {
stopService(intent_service); // stop service after work done
btn_start.setEnabled(true);
}
}
};
and now make a small change in your Timer_Service class-
if (long_hours == 0){
mEditor.putBoolean("finish", true).commit(); // a change is here
mTimer.cancel();
}
try it and let me know if it works.

Why does my application crash sometimes?

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();

SetText using Broadcast Intent android

i am able to display current time and a counter in my textviews but i want to display uploaded and downloaded bytes in the same instead. below are my codes-
in other words, i want to send bandwidth usage to receiver class instead of sending current time and counter.
broadcast service (this calss sends data to receiver class)
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
#Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 10000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("time", new Date().toLocaleString());
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
Bandwidth Usage Example
public class Main extends Activity {
private Handler mHandler = new Handler();
private long mStartRX = 0;
private long mStartTX = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
i have tried this but it just shows the package name in both of the textviews
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
private long mStartRX = 0;
private long mStartTX = 0;
#Override
public void onCreate() {
super.onCreate();
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
// RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
// TX.setText(Long.toString(txBytes));
handler.postDelayed(this, 10000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("rxBytes", toString());
intent.putExtra("txBytes", toString());
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}

Executing something each X second is not exact

I'm testing something and I want print out execution time with this code:
private Runnable runnerLog = new Runnable() {
#Override
public void run() {
String timeStamp = new SimpleDateFormat("HH:mm:ss yyyy-dd-MM").format(Calendar.getInstance().getTime());
System.out.println("Current time: " + timeStamp);
mHandlerLogger.postDelayed(runnerLog, mInterval);
}};
The result should be like:
13:45:10
13:45:12
13:45:14
13:45:16
and so on...
but i noticed that sometimes is not difference 2 seconds, but three:
13:45:10
13:45:12
13:45:15
13:45:17
13:45:19
13:45:21
13:45:24
What is the reason for this situation? Is there better solution for executing something each X seconds?
try this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
please try this:
private Handler myhandler ;
private long RETRY_TIME = xx;
private long START_TIME = yy;
//oncreate
myhandler= new Handler();
myhandler.postDelayed(myRunnable, START_TIME);
//your runnable class
private Runnable myRunnable = new Runnable() {
public void run() {
//doing something
myhandler.postDelayed(myRunnable, RETRY_TIME);
}
};

Categories

Resources