Android Timer is causing random Device time change - android

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

Related

I want to do a TransitionDrawable transition multiple times using xml transition

Here my transition and reverse transition happens only once not 10 times, Can u tell me where I'm wrong ??
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0;i<10;i++)
{
Resources res = getApplicationContext().getResources();
Drawable background[] = new Drawable[2];
background[0] = res.getDrawable(R.drawable.shapes);
background[1] = res.getDrawable(R.drawable.large_shape);
final TransitionDrawable transition = new TransitionDrawable(background);
ImageView imgview = findViewById(R.id.transitimage);
imgview.setImageDrawable(transition);
Runnable r1 = new Runnable() {
#Override
public void run() {
transition.startTransition(2000);
}
};
Runnable r2 = new Runnable() {
#Override
public void run() {
transition.reverseTransition(2000);
}
};
Handler h = new Handler();
h.postDelayed(r1, 0);
h.postDelayed(r2, 2000);
}
}
}
public void repeat() {
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
if (i>9) { // i is a field,its initial value equals 0
cancel(); // stop timer
}
if (flag) {
transition.startTransition(2000);
} else {
transition.reverseTransition(2000);
}
flag = !flag;
i += 1;
}
public void onFinish() {
repeat();
}
}.start();
}
Call above function in some place.

Unable to Show Toast in Services after Every 5 Second

When ever i try to toast in service it Doesn't work But When I use LOg it Work Fine How Can I Fix this?
This is My Code Check it please:
Main Activity
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn =(Button) findViewById(R.id.btnDownload);
Intent in= new Intent(this,MyService.class);
startService(in);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Main2Activity.class);
startActivity(i);
}
});
}
My Service Class: If I use Log Instead Of Toast it Works But When I Use Toast It Doesn't Show Anything...
public class MyService extends Service {
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Runnable r=new Runnable() {
#Override
public void run() {
for (int i=0 ; i<5 ; i++){
long futureTime = System.currentTimeMillis()+5000;
while (System.currentTimeMillis() < futureTime){
synchronized (this){
try {
wait(futureTime-System.currentTimeMillis());
Toast.makeText(getApplicationContext(),"Image Downloading",Toast.LENGTH_SHORT);
}catch (Exception e){}
}
}
}
}
};
Thread razasThread = new Thread(r);
razasThread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(),"OnDestroy method Called",Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Try doing it using Handler. It might be throwing an exception since you are trying to show the Toast on a different thread:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
for (int i=0 ; i<5 ; i++){
long futureTime = System.currentTimeMillis()+5000;
while (System.currentTimeMillis() < futureTime){
synchronized (this){
try {
wait(futureTime-System.currentTimeMillis());
Toast.makeText(getApplicationContext(),"Image Downloading",Toast.LENGTH_SHORT).show();
}catch (Exception e){}
}
}
}
}
});

Android update ProgressBar with Handler

I would like to update the progressBar with Handler and for loop but without success.
Code:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(progress_k, 100);
}
}, 2000);
}
}
Question:
The progress bar increase immediately to the end value instead of progressively.
Why?
Try this:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
final int curr_progress_k = progress_k;
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(curr_progress_k, 100);
}
}, progress_k * 100); // adjust "100" value to adjust speed
}
}
Repeat a task with a time delay?
#inazaruk
private ProgressBar progressBar;
private Handler mHandler;
private int progressInt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
progressBar = (ProgressBar) findViewById(R.id.pb);
progressBar.setProgress(0);
mHandler = new Handler();
runnable.run();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
updateProgress();
} catch (Exception ignored) {
} finally {
mHandler.postDelayed(runnable, progressInt);
}
}
};
private void updateProgress() {
progressInt += 1;
if (progressInt > 100) {
mHandler.removeCallbacks(runnable);
} else {
progressBar.setProgress(progressInt);
}
}
try this code:
Solution 1
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler();
class Task implements Runnable {
int start,end;
Task(int a,int b) { start = a; end = b;}
#Override
public void run() {
for (int i =start ; i <= end; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler1.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
}
});
}
}
}
Thread t = new Thread(new Task(from, to)); //call it
t.start();
}
Solution 2: More Simple
If thread is too much to ask for this problem..
you can use the following solution to use a single Handler to update progressbar:
code
public class HandlerDemo extends Activity
{
ProgressBar bar;
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
bar.incrementProgressBy(5);
}
};
boolean isRunning = false;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
}
public void onStart()
{
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
for (int i = 0; i < 20 && isRunning; i++)
{
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t)
{
// just end the background thread
}
}
});
isRunning = true;
background.start();
}
public void onStop()
{
super.onStop();
isRunning = false;
}
}
Hope it helps..

Increasing counter in TimerTask

How can I increase my counter i here:
private void startTimer() {
int i = 0;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++; //i must declared final error
runOnUiThread(new Runnable() {
#Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}
You have to move i out of the scope of the function. Then it does not have to be declared final and you can change it. Change your code to this
private int i = 0;
private void startTimer() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++;
runOnUiThread(new Runnable() {
#Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}

Why do I get "Cannot resolve method scheduleAtFixedRate"?

I have no idea to why I am recieving this error. With all the example I've seen with the class TimerTask , this should not cause a problem.
public class CountUp extends AppCompatActivity {
EditText upText = (EditText) findViewById(R.id.Up);
int counter = 0;
float StartTime = 0;
float OffsetTime = 1000; //Offset time is the time between event. 1000 is going to be our milliseconds (1 second)
TimerTask tt = new TimerTask() {
#Override
public void run() {
upText.setText(counter);
counter++;
}
};
public void CountUp(View view){
try {
Timer timer = new Timer();
timer.scheduleAtFixedRate(tt,StartTime,OffsetTime); <--- //This is were I am receiving an error
}catch (Exception e){
}
}
Replace your whole code with this one:
public class CountUp extends AppCompatActivity {
EditText upText;
TimerTask tt;
int counter = 0;
//startTime and offsetTime must be long and not float.
long startTime = 0;
long offsetTime = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Change this to your current layout.
setContentView(R.layout.main_activity);
upText = (EditText) findViewById(R.id.Up);
tt = new TimerTask() {
#Override
public void run() {
upText.setText(String.valueOf(counter));
counter++;
}
};
}
public void countUp(View view) {
try {
Timer timer = new Timer();
timer.scheduleAtFixedRate(tt, startTime, offsetTime);
} catch (Exception e) {
}
}
}

Categories

Resources