i am creating an application that keeps track of the number of bytes used.i want to receive a notification when the total_bytes have reached a certain value say 1000 bytes. i have searched over the internet for about an hour and i havent found anything usefull. how do i go about it?
public class Data_usage extends AppCompatActivity {
private Handler mHandler = new Handler();
private long mStartRX = 0;
private long mStartTX = 0;
long total_bytes;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_usage);
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);
}
}
public final Runnable mRunnable=new Runnable() {
#Override
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
TextView Totalbytes=(TextView)findViewById(R.id.TOTALX);
final long rxBytes=TrafficStats.getMobileRxBytes()-mStartRX;
RX.setText(Long.toString(rxBytes));
final long txBytes=TrafficStats.getMobileTxBytes()-mStartTX;
TX.setText(Long.toString(txBytes));
Totalbytes.setText(Long.toString(total_bytes));
long Txx=rxBytes;
long Rxx=txBytes;
total_bytes=Rxx+Txx;
mHandler.postDelayed(mRunnable, 1000);
}
};
}
Maybe have a second Activity that is the notification.
public final Runnable mRunnable=new Runnable() {
#Override
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
TextView Totalbytes=(TextView)findViewById(R.id.TOTALX);
final long rxBytes=TrafficStats.getMobileRxBytes()-mStartRX;
RX.setText(Long.toString(rxBytes));
final long txBytes=TrafficStats.getMobileTxBytes()-mStartTX;
TX.setText(Long.toString(txBytes));
Totalbytes.setText(Long.toString(total_bytes));
long Txx=rxBytes;
long Rxx=txBytes;
total_bytes=Rxx+Txx;
Intent myIntent = new Intent(this, Notification.Class);
Bundle bundle = myIntent.getExtras();
bundle.putInt("bytes", total_bytes);
startActivity(myIntent);
mHandler.postDelayed(mRunnable, 1000);
}
Make changes in Runnable.
public final Runnable mRunnable=new Runnable() {
#Override
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
TextView Totalbytes=(TextView)findViewById(R.id.TOTALX);
final long rxBytes=TrafficStats.getMobileRxBytes()-mStartRX;
RX.setText(Long.toString(rxBytes));
final long txBytes=TrafficStats.getMobileTxBytes()-mStartTX;
TX.setText(Long.toString(txBytes));
Totalbytes.setText(Long.toString(total_bytes));
long Txx=rxBytes;
long Rxx=txBytes;
total_bytes=Rxx+Txx;
if(total_bytes==1000){
// Display alert dialog here
mHandler.removeCallbacks(mRunnable);
}else{
mHandler.postDelayed(mRunnable, 1000);
}
}
};
Hope this will help you.
Related
first of all excuse me if my title doesn't describe my question very well but i couldn't find a better one .
there is a simple stopWatch app that has three button start,stop,reset and a textview to display time . app has just one activity like this:
public class StopwatchActivity extends AppCompatActivity {
private int mNumberOfSeconds = 0;
private boolean mRunning = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
//if if uncomment this runner method and delete the runner inside onClickStart everything will work find
//runner()
}
public void onClickStart(View view){
mRunning = true;
runner();
}
public void onClickStop(View view){
mRunning = false;
}
public void onClickReset(View view){
mRunning = false;
mNumberOfSeconds = 0;
}
public void runner(){
final TextView timeView = (TextView) findViewById(R.id.time_view);
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
int hours = mNumberOfSeconds/3600;
int minutes = (mNumberOfSeconds%3600)/60;
int second = mNumberOfSeconds%60;
String time = String.format("%d:%02d:%02d" , hours , minutes , second );
timeView.setText(time);
if (mRunning){
mNumberOfSeconds++;
}
handler.postDelayed(this , 1000);
}
});
}
}
my problem is when i comment the runner() in onClickStart method and put it in the onCreate method everything is ok . but when i change the code like above the code is still running but after i press stop button and then press start again the second will increment by 4 or 5 very fast.
can anyone explain me what is the difference between this two modes?
declare your handler globally
public void runner(){
timeView = (TextView) findViewById(R.id.time_view);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
int hours = mNumberOfSeconds/3600;
int minutes = (mNumberOfSeconds%3600)/60;
int second = mNumberOfSeconds%60;
String time = String.format("%d:%02d:%02d" , hours , minutes , second );
timeView.setText(time);
if (mRunning){
mNumberOfSeconds++;
}
handler.postDelayed(this , 1000);
}
}
handler.post(runnable);
}
in button function
public void onClickStart(View view){
if(handler != null) {
//restart the handler to avoid duplicate runnable
handler.removeCallbacks(runnable);//or this handler.removeCallbacksAndMessages(null);
}
mRunning = true;
runner();
}
public void onClickStop(View view){
mRunning = false;
handler.removeCallbacks(runnable); // this will stop the handler from working
}
below is an example for updating textiviews in an activity from a service via broadcast receiver but i want to send calculated bandwidth usage from the service to the text views in the other activity, i have tried an approach but its not working (it just shows package names in the text fields)
broadcast service (transmitter)
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();
}
}
Broadcast service (receiver)
public class BroadcastTest extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
public void ohh(View view) {
Intent intent = new Intent(this, BroadcastService.class);
startActivity(intent);
}
private void updateUI(Intent intent) {
String counter = intent.getStringExtra("time");
String time = intent.getStringExtra("counter");
Log.d(TAG, counter);
Log.d(TAG, time);
TextView txtDateTime = (TextView) findViewById(R.id.txtDateTime);
TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
txtDateTime.setText(time);
txtCounter.setText(counter);
}
}
Bandwidth Usage calculator
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);
}
};
}
My approach
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 Handler mHandler = new Handler();
private long mStartRX = 0;
private long mStartTX = 0;
#Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
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);
}
};
#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();
}
}
i am having problem in transmitting the value of "rxBytes" and "txBytes" in the line intent.putExtra("counter", String.valueOf(++counter));
their values are not being used so the are highlighted with yellow
i am creating a sample app in which i want to change a TextVeiw value every second.
TextView value should change continue every second.
to perform this task i tried this below code:
but this code is not changing text values continue, it only change on app start or screen rotate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Boolean b = true;
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
Thread t = new Thread() {
#Override
public void run() {
try {
while (b != false) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update TextView here!
tv.setText(str[random]);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
and i also tried this code:
but this code crash application
private Timer timer = new Timer();
private TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
timerTask = new TimerTask() {
#Override
public void run() {
// refresh your textview
tv.setText(str[random]);
}
};
timer.schedule(timerTask, 0, 1000);
}
Try the following code snippet
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
long millis =(long)currentTime();
dateAndTime.setText(getDate(millis, "dd/MM/yyyy hh:mm:ss.SSS"));
h.postDelayed(this, 1000);
}
});
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "23458", "9654", "987650", };
// //
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
// //
how can I put a Timer in an android dialog? I have all the dialog methods built, but I can't seem to figure out how to update the text in the dialog view every time the timer fires. my update method is already getting called once per second by another class.
here's my code so far:
public class PlaybackTimerEndingDialog extends DialogFragment implements TimerCallbacks.updateTimer {
private AlertDialog.Builder mBuilder;
private long mTime;
private Context mContext;
private View mTimerEndingView;
public PlaybackTimerEndingDialog(long startTime, Context context){
this.mTime = startTime;
this.mContext = context;
}
private void updateView(String message_text){
LayoutInflater inflater = this.getActivity().getLayoutInflater();
this.mTimerEndingView = inflater.inflate(R.layout.playback_timer_ending, null);
TextView messageView = (TextView) this.mTimerEndingView.findViewById(R.id.timer_ending_message);
messageView.setText(message_text);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
this.updateView("The sleep timer will expie in "+ this.formatTime(this.mTime));
this.mBuilder = new AlertDialog.Builder(this.mContext)
// this.mBuilder.setMessage("The sleep timer will expie in "+ this.formatTime(this.mTime))
.setPositiveButton("Add more time", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
TimerCallbacks.createTimer listener = (TimerCallbacks.createTimer) PlaybackTimerEndingDialog.this.mContext;
listener.createTimerDialog();
}
})
.setNegativeButton("Cancel timer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
TimerCallbacks.createTimer listener = (TimerCallbacks.createTimer) PlaybackTimerEndingDialog.this.mContext;
listener.stopTimer();
}
});
this.mBuilder.setView(this.mTimerEndingView);
// Create the AlertDialog object and return it
return this.mBuilder.create();
}
#Override
public void finished() {
// TODO Auto-generated method stub
}
#Override
public void update(long time) {
// TODO Auto-generated method stub
// this.getDialog().set
this.updateView("The sleep timer will expie in "+ this.formatTime(time));
this.mTime = time;
Log.d("current time", Long.toString(time));
// this.mBuilder.setMessage("The sleep timer will expie in "+ this.formatTime(time));
}
private String formatTime(long time) {
int seconds = (int) (time / 1000) % 60 ;
int minutes = (int) ((time / (1000*60)) % 60);
String mnStr = (minutes<10 ? "0" : "")+minutes;
String secStr = (seconds<10 ? "0" : "")+seconds;
return "-"+mnStr +":"+ secStr;
}
}
any help with this would be greatly appreciated.
Put that in some function where you want to start a timer.
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
updateView("fired");
}
}, 1000);
Update: it's the update method that inflate new layout every time, while the dialog is using first inflated layout.
I´m trying to create a fullscreen clock. I managed to set text for hours, minutes and seconds. Well, but when I start the app, it shows the time but the UI is not updating... I dont know how to do it, I read this tutorial but i dont understand it... any one can explain me how to consantly update the UI?
public class Clock1Activity extends Activity {
/** Called when the activity is first created. */
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtHour = (TextView)findViewById(R.id.TxtHour);
final TextView txtMinutes = (TextView)findViewById(R.id.TxtMinute);
final TextView txtSeconds = (TextView)findViewById(R.id.TxtSeconds);
final TextView txtMilliseconds = (TextView)findViewById(R.id.TxtMilliseconds);
final Integer hora = new Integer(Calendar.HOUR_OF_DAY);
final Integer minutos = new Integer(Calendar.MINUTE);
final Integer segundos = new Integer(Calendar.SECOND);
final Long milisegundos = new Long (System.currentTimeMillis());
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
// Get the Current Time
final Runnable updateTask = new Runnable() {
public void run() {
/** txtHour.setText(hora.toString());
txtMinutes.setText(minutos.toString());
txtSeconds.setText(segundos.toString()); */
txtMilliseconds.setText(milisegundos.toString());
Toast toast1 = Toast.makeText(getApplicationContext(), milisegundos.toString(), Toast.LENGTH_SHORT);
toast1.show();
}
};
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 1000);
}
}
Just tell me how to complete it to update UI,please...
You didn't mention which tutorial you're working on, so just in case, you'll probably want to use AsyncTask.
see this example for Create a Apps to Show Digital Time in Android .And in your case use
runOnUiThread for Upadting time on UI.as
CurrentActivity.this.runOnUiThread(new Runnable() {
public void run() {
//UPDATE TIME HERE
}
});
and your code look like:
public class Clock1Activity extends Activity {
/** Called when the activity is first created. */
private Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtHour = (TextView)findViewById(R.id.TxtHour);
final TextView txtMinutes = (TextView)findViewById(R.id.TxtMinute);
final TextView txtSeconds = (TextView)findViewById(R.id.TxtSeconds);
final TextView txtMilliseconds = (TextView)findViewById(R.id.TxtMilliseconds);
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
// Get the Current Time
final Runnable updateTask = new Runnable() {
public void run() {
final Integer hora = new Integer(Calendar.HOUR_OF_DAY);
final Integer minutos = new Integer(Calendar.MINUTE);
final Integer segundos = new Integer(Calendar.SECOND);
final Integer milisegundos = new Integer(Calendar.MILLISECOND);
txtHour.setText(hora.toString());
txtMinutes.setText(minutos.toString());
txtSeconds.setText(segundos.toString());
txtMilliseconds.setText(milisegundos.toString());
}
};
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 1000);
}
}