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
Related
I am Trying to Implement a service where when I a select a time, the timer starts and runs in the background. the thing is working fine. but when I select another time, the timer overlaps on one another. I want my app to work in such a way that different services should run for different time. also, when I kill the app and reopen it, I get the remaining time in all the services.
however my data is coming from a web service and this web service contains a field with time. when I click the time, the above concept should start.
I have implemented my code as,
BroadCastService.java
public class BroadCastService extends Service {
private long totalTimeCountInMilliseconds;
private long timeBlinkInMilliseconds;
private CountDownTimer countDownTimer;
private boolean blink;
String getTime;
public static final String COUNTDOWN_BR = "project.uop.assignment8";
Intent bi = new Intent(COUNTDOWN_BR);
public BroadCastService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
getTime = intent.getStringExtra("time");
setTimer();
startTimer();
Log.i("madhura","madhura");
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
private void setTimer() {
int time = 0;
//if (getTime.equals("")) {
time = Integer.parseInt(getTime);
// } else
/* Toast.makeText(BroadCastService.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();*/
totalTimeCountInMilliseconds = 60 * time * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
if (blink) {
// mTextField.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
// mTextField.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
String a = String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60);
bi.putExtra("countdown", a);
sendBroadcast(bi);
}
#Override
public void onFinish() {
Toast.makeText(BroadCastService.this, "Finished", Toast.LENGTH_SHORT).show();
}
}.start();
}
}
and my TimerActivity.class
public class TimerActivity extends AppCompatActivity {
TextView mTextField;
TextView hotel;
private long totalTimeCountInMilliseconds;
private long timeBlinkInMilliseconds;
private CountDownTimer countDownTimer;
private boolean blink;
String getTime;
SessionManager sessionManager;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
InitializeToolbar();
Intent in = getIntent();
getTime = in.getStringExtra("time");
Intent intent = new Intent(this,BroadCastService.class);
intent.putExtra("time",getTime);
this.startService(intent);
sessionManager = new SessionManager(this);
hotel = findViewById(R.id.textView);
hotel.setText(sessionManager.getUserName());
Log.i("started", "Started service");
mTextField = findViewById(R.id.timer);
}
public void InitializeToolbar(){
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Order Notification");
}
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
#Override
public void onResume() {
super.onResume();
registerReceiver(br, new IntentFilter(BroadCastService.COUNTDOWN_BR));
Log.i("efgh", "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(br);
Log.i("abcd", "Unregistered broadcast receiver");
}
#Override
public void onStop() {
try {
unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
stopService(new Intent(this, BroadCastService.class));
Log.i("Stopped", "Stopped service");
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
String millisUntilFinished = intent.getStringExtra("countdown");
mTextField.setText(millisUntilFinished);
}
}
}
thanks in advance.
Use Handler and #Overide its method Handler#handleMessage(Message msg)
See this: https://gist.github.com/mjohnsullivan/403149218ecb480e7759
I created my layout for the ExoPlayer buttons
***
<ImageButton
android:id="#id/exo_play"
android:layout_width="50dp"
android:layout_height="50dp"
android:onClick="onPlayClick"
android:background="#drawable/btn_play" />
<ImageButton
android:id="#id/exo_pause"
android:layout_width="50dp"
android:layout_height="50dp"
android:onClick="onPauseClick"
android:background="#drawable/btn_pause" />
***
I have a program in my program that starts and stops from the PlayerActivity. How to make the service stop when clicking on the pause button in the EcxoPlayer, and when you click on play, the service was restarted?
Code PlayerActivity
public class PlayerActivity extends AppCompatActivity {
private int id;
private String title;
private String autor;
private String file;
private String img;
private String MAYBE_ACTION = "MAYBE_ACTION";
static boolean isPlay = false;
ImageButton btnPLayPause;
private TextView txtRadio;
private TextView txtTitle;
private RoundedImageView imgRadio;
private ImageButton exo_pause;
private ImageButton exo_play;
private String internetStatus = "";
BroadcastReceiver br;
BroadcastReceiver serviceReceiver;
public final static String SERVICE_PARAM = "param";
public final static int SERVICE_STATUS = 0;
public final static String BROADCAST_ACTION = "ru.myapps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
id = getIntent().getExtras().getInt("id");
title = getIntent().getExtras().getString("title");
autor = getIntent().getExtras().getString("autor");
file = "link";
img = getIntent().getExtras().getString("img");
RadioPlayer.simpleExoPlayerView = new SimpleExoPlayerView(this);
RadioPlayer.simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
btnPLayPause = (ImageButton) findViewById(R.id.btnPLayPause);
txtRadio = (TextView) findViewById(R.id.txtRadio);
imgRadio = (RoundedImageView) findViewById(R.id.imgRadio);
exo_pause = (ImageButton) findViewById(R.id.exo_pause);
exo_play = (ImageButton) findViewById(R.id.exo_play);
setTitle(title);
txtRadio.setText(title);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION);
registerReceiver(br, intentFilter);
if (NetworkUtil.getConnectivityStatus(this) != 0) {
startPlayerService();
exo_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlay) {
stopPlayerService();
}
}
});
exo_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (NetworkUtil.getConnectivityStatus(PlayerActivity.this) != 0 ) {
if (!isPlay) {
startPlayerService();
}
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
}
public void startPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.putExtra(PlayerService.KEY_STREAM, file);
serviceIntent.putExtra(PlayerService.KEY_RADIO, title);
serviceIntent.setAction(PlayerConstants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
isPlay = true;
btnPLayPause.setImageResource(R.drawable.icon_stop);
exo_pause.setVisibility(View.VISIBLE);
exo_play.setVisibility(View.GONE);
}
private void stopPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.setAction(PlayerConstants.ACTION.STOPFOREGROUND_ACTION);
stopService(serviceIntent);
isPlay = false;
btnPLayPause.setImageResource(R.drawable.icon_play);
exo_pause.setVisibility(View.GONE);
exo_play.setVisibility(View.VISIBLE);
}
private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
internetStatus = NetworkUtil.getConnectivityStatusString(context);
//Toast.makeText(context, internetStatus, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onResume() {
super.onResume();
serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int serviceStatus = intent.getIntExtra(SERVICE_PARAM, 0);
if (serviceStatus == SERVICE_STATUS) {
btnPLayPause.setImageResource(R.drawable.icon_play);
}
}
};
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
registerReceiver(serviceReceiver, filter);
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (NetworkChangeReceiver != null) unregisterReceiver(NetworkChangeReceiver);
unregisterReceiver(br);
unregisterReceiver(serviceReceiver);
}
}
I tried to implement the actions of buttons in onresume but when I pause the service it stops and the play button does not play
Your OnClickListener should be in OnCreate, try this and let me know:
public class PlayerActivity extends AppCompatActivity {
private int id;
private String title;
private String autor;
private String file;
private String img;
private String MAYBE_ACTION = "MAYBE_ACTION";
static boolean isPlay = false;
ImageButton btnPLayPause;
private TextView txtRadio;
private TextView txtTitle;
private RoundedImageView imgRadio;
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private ImageButton exo_pause;
private ImageButton exo_play;
public static String LOG_TAG = "my_log";
private String internetStatus = "";
BroadcastReceiver br;
BroadcastReceiver serviceReceiver;
private AsyncTask jsonTask;
public final static String SERVICE_PARAM = "param";
public final static int SERVICE_STATUS = 0;
public final static String BROADCAST_ACTION = "ru.myapps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
id = getIntent().getExtras().getInt("id");
title = getIntent().getExtras().getString("title");
autor = getIntent().getExtras().getString("autor");
file = "link_mp3_files";
img = getIntent().getExtras().getString("img");
RadioPlayer.simpleExoPlayerView = new SimpleExoPlayerView(this);
RadioPlayer.simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
btnPLayPause = (ImageButton) findViewById(R.id.btnPLayPause);
txtRadio = (TextView) findViewById(R.id.txtRadio);
imgRadio = (RoundedImageView) findViewById(R.id.imgRadio);
exo_pause = (ImageButton) findViewById(R.id.exo_pause);
exo_play = (ImageButton) findViewById(R.id.exo_play);
setTitle(title);
txtRadio.setText(title);
if (NetworkUtil.getConnectivityStatus(this) != 0) {
startPlayerService();
}
exo_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isPlay) {
stopPlayerService();
}
}
});
exo_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (NetworkUtil.getConnectivityStatus(PlayerActivity.this) != 0 ) {
if (isPlay) {
startPlayerService();
}
}
}
});
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION);
registerReceiver(br, intentFilter);
}
#Override
protected void onStart() {
super.onStart();
}
public void startPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.putExtra(PlayerService.KEY_STREAM, file);
serviceIntent.putExtra(PlayerService.KEY_RADIO, title);
serviceIntent.setAction(PlayerConstants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
isPlay = true;
btnPLayPause.setImageResource(R.drawable.icon_stop);
if(exo_play.getVisibility() == View.VISIBLE) {
exo_play.setVisibility(View.GONE);
exo_pause.setVisibility(View.VISIBLE);
}
}
private void stopPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.setAction(PlayerConstants.ACTION.STOPFOREGROUND_ACTION);
stopService(serviceIntent);
isPlay = false;
btnPLayPause.setImageResource(R.drawable.icon_play);
if(exo_pause.getVisibility() == View.VISIBLE) {
exo_pause.setVisibility(View.GONE);
exo_play.setVisibility(View.VISIBLE);
}
}
private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
internetStatus = NetworkUtil.getConnectivityStatusString(context);
//Toast.makeText(context, internetStatus, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onResume() {
super.onResume();
serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int serviceStatus = intent.getIntExtra(SERVICE_PARAM, 0);
if (serviceStatus == SERVICE_STATUS) {
btnPLayPause.setImageResource(R.drawable.icon_play);
}
}
};
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
registerReceiver(serviceReceiver, filter);
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (NetworkChangeReceiver != null) unregisterReceiver(NetworkChangeReceiver);
unregisterReceiver(br);
unregisterReceiver(serviceReceiver);
}
}
In OnResume you can check if it is running or not then stoo it if you would like to.
Your problem is that you never called startPlayerService(); when exo_play is tapped. Please see exo_play.setOnClickListener. I also removed the else statement as it is unnecessary.
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.
I have a strange problem. In my android application I have 10 ms timer running.
after long run(14 hours of run ) any how timer is causing change in device time.
Usually time changes 2 days ahead
public class MainActivity extends Activity {
TextView DateTextView;
TextView BatteryTextView;
String date;
Thread mUpdateUIThread;
public native void WatchDogTimeTest();
int[] m_array ;
Timer mTimerThread;
String StrDdate;
int n = 0;
public IntentFilter s_intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DateTextView = (TextView)findViewById(R.id.DatedisplayTxtVw);
BatteryTextView = (TextView)findViewById(R.id.BatteryStatus);
date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
DateTextView.setText(date);
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
s_intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
s_intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
this.registerReceiver(this.mBatInfoReceiver,s_intentFilter);
CreateMutipleThread();
TimerThread();
WatchDogTimeTest();
}
public void CreateMutipleThread()
{
for(int i = 0 ; i < 100 ; i++)
{
mUpdateUIThread= new Thread() {
#Override
public void run() {
try {
while (!isInterrupted())
{
Thread.sleep(100); //Check for Aux Battery Status After 10 Second
runOnUiThread(new Runnable()
{
#Override
public void run()
{
n++;
if(n >= 10000)
n= 0;
}
});
}
} catch (InterruptedException e) {
}
}
};
mUpdateUIThread.start();
}
}
public void TimerThread()
{
mTimerThread = new Timer();
//Set the schedule function and rate
mTimerThread.schedule(new TimerTask() {
#Override
public void run() {
StrDdate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
}
},1000,1);
}
public void InvalidateTimer()
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
printTime();
}
});
}
public void printTime()
{
}
public BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
final String action = intent.getAction();
//Date Change Broad cast
if(action.equals(Intent.ACTION_DATE_CHANGED))
{
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
DateTextView.setText(date);
DateTextView.setBackgroundColor(Color.RED);
BatteryTextView.setText(mydate);
}
}
};
}
Any idea how to solve this problem. This is my Test Code
I am showing toast message after every 20 seconds from current time but if I going out the app it is not working. Here is my code:
public class Main extends Activity {
final static private long ONE_SECOND = 1000;
final static private long TWENTY_SECONDS = ONE_SECOND * 20;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
Log.i("Receive message in every five seconds", "message");
}
};
registerReceiver(br, new IntentFilter("com.authorwjf.wakeywakey"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.authorwjf.wakeywakey"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(),
TWENTY_SECONDS, pi);
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
}
My question is if the app is not running but still it can show toast message? How can it possible in android?
you must create a Class Updater which contain a Handler
it will be executed periodically (you can define this periode) like that:
import android.os.Handler;
public class Updater {
private Handler mHandler = new Handler();
private Runnable mStatusChecker;
final static private long TWENTY_SECONDS = 20000;
private int UPDATE_INTERVAL = TWENTY_SECONDS;
public Updater(final Runnable updater){
mStatusChecker = new Runnable() {
#Override
public void run() {
updater.run();
mHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
}
public Updater(Runnable updater, int interval){
this(updater);
UPDATE_INTERVAL = interval;
}
public void startUpdates(){
mStatusChecker.run();
}
public void stopUpdates(){
mHandler.removeCallbacks(mStatusChecker);
}}
than create a service "ServiceOn" :
public class ServiceOn extends Service {
Updater updater = new Updater(new Runnable() {
#Override
public void run() {
// put your code here
// toast or what you want
}});
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
updater.startUpdates();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
updater.stopUpdates();
super.onDestroy();
}}
and finally in your activity you can call this service:
context.startService(new Intent(context, ServiceOn.class));
this will work for every 20 seconds even if the app stop running
Try This Code i hope its working...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Handler h=new Handler();
final Runnable r=new Runnable() {
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Example OF Practicle 8",Toast.LENGTH_SHORT).show();
}
};
Timer t=new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
h.post(r);
}
},2000, 5000);
You can use setTimeout
setTimeout( function(){
toastr.clear(); // User to Clear the Toast Message Popup
}, 1000 ); // We can set our own time interval to disappear the popup
Hope it will help you