public void BetTimerFuction()
{
int delay=0;
int period=200;
betTimer = new Timer();
betTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
mHandlerBet.obtainMessage().sendToTarget();
}
}, delay, period);
}
Its my timer code but i didn't work with that timer in view class i m also using canvas .
When I use that timer in view class that timer get a number prosess is very slow when i click the button its increase the the integer two timers
I think u do the null first for your stop function.
public void StopBetTimer()
{
try
{
if(betTimer !=null)
{
betTimer.cancel();
betTimer=null;
}
}
catch(Exception e)
{
}
}
I revised you code because i think in that code no issue. But may be you didn't initialize properly to null your timer when you use first and also stop properly.
public void BetTimerFuction()
{
int delay=0;
int period=100;
betTimer = new Timer();
betTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
mHandlerBet.obtainMessage().sendToTarget();
}
}, delay, period);
}
Here is for you stop function
public void StopBetTimer()
{
try
{
if(betTimer !=null)
{
betTimer.cancel();
betTimer=null;
}
}
catch(Exception e)
{
}
}
Related
I am developing an application that shows the different photos from server and user can set select photos as wallpaper of its device i used given code to set wallpaper it working but i want to wallpaper set automatically every day. I used this code.
Java
private void setAsWallpaper()
{
Picasso.get().load(imageUrl).into(new Target()
{
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
{
progressBar.bringToFront();
progressBar.setVisibility(View.VISIBLE);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(SetWallPaperFullScreenActivity.this);
try
{
wallpaperManager.setBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SetWallPaperFullScreenActivity.this, "Wallpaper set successfully.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable)
{
Log.d("TAG", "Failed: ");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable)
{
Log.d("TAG", "Prepare Load: ");
}
});
}
1) first you need to Schedule job which called every 24 hour. reference link
2) now use below method to set wallpaper
public void setWallpaper {
WallpaperManager myWallpaperManager =
WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.drawable.wallpaper);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try this out,
Create a sticky service as shown below then i have created a TimerTask(Scheduler) which will run after every 24hrs there you can add your code for setting wallpaper. Don't forget to register the service in Manifest. Start this service from any activity.
You can refer the sticky service from here to know more
private Timer timer;
private TimerTask timerTask;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTimer();
return START_STICKY;
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
//schedule the timer, after the first **5000ms** the TimerTask will run in every **24hrs**
timer.schedule(timerTask, 5000, 86400000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//ToDo set wallapaper here
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
}
I'm beginner... I need to run some code after 10 seconds continuously while my button is enable.
and when I clicked on it and it turned to disable-state, timer get stop.
I use below code but it run just once when I click on timerbutton every time again...
I think I have to use threed and I think I used it too! But I did not get to my goal.
private View.OnClickListener ontimerclicked = new View.OnClickListener() {
#Override
public void onClick(View view) {
Handler myHandler = new Handler();
myHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (endistimer==false) {
endistimer=true;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#E91E63"));
varbtnimgnext.performClick();
intdelay=10000;
}
else
{
endistimer=false;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#dddddd"));
intdelay=0;
}
}
}, intdelay);
}
};
I finaly solved it with below code.I put it for anothers:
private View.OnClickListener ontimerclicked = new View.OnClickListener() {
#Override
public void onClick(View view) {
mHandler = new Handler();
if (endistimer==false) {
endistimer=true;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#E91E63"));
}
else
{
endistimer=false;
varbtnimgslidtimer.setBackgroundColor(Color.parseColor("#dddddd"));
intdelay=5000;
cntsec=0;
varbtnplusfive.setText(arrsec[0] +" Sec");
}
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (endistimer) {
try {
Thread.sleep(intdelay);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// your codes
// you can set continue_or_stop to false, for stop
}
});
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(slideword.this,e.toString(),Toast.LENGTH_SHORT);
}
}
}
}).start();
}
};
Using Android studio, I am trying to make an app that gets data from a web-service and display the data and updates the view every 5 sec or when the data on the web-service changes. With this I am trying to change the colours on some button based on an int, the int changes and the color on the button changes when I apply buttons(); to another button and then presses it but I want it to update by itself.
When I used a while loop the app gets stuck
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
buttons();
}
});
The runOnUiThread is placed in the onCreate.
using run on UI thread will cause your UI to freeze , try using a timer task instead .
example :
#Override
public void StopTimerTask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void StartTimer() {
timer = new Timer();
initializeTimerTask();
int UpdateTime = Integer.valueOf(UserSettings.getString("Update", "60000"));
timer.schedule(doAsynchronousTask, 0, YOURTIME);
}
public void initializeTimerTask() {
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
myHandler.post(new Runnable() {
public void run() {
YOUR LOGIC HERE
}
});
}
};
}
doing this where u just put another class into main activity was succesful only problem is that it have to be in my main class
public class updategui extends TimerTask {
Activity context;
Timer timer;
public updategui(Activity context, int seconds) {
this.context = context;
timer = new Timer();
timer.schedule(this,
seconds * 1000, // initial delay
seconds * 1000); // subsequent rate
}
#Override
public void run() {
if(context == null || context.isFinishing()) {
this.cancel();
return;
}
context.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
buttons();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}}
I am in a situation where I need to display the Rate dialog based on the following flow
Open the app (First time )--> display dialog every 2 minutes
If rated --> display dialog next month
If clicked on later button --> display dialog next week.
String rate_value=myPref.getString("rate_value", "later");
Log.e("rate", String.valueOf(rate_value));
if (rate_value=="later") {
initCalendarNextWeek();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, nextWeekDate);
}
else if (rate_value=="now") {
initCalendarNextMonth();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, nextMonthDate);
}
else if (rate_value=="no_thanks") {
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, 120000, 120000);
}
public void initCalendarNextMonth(){
cal=Calendar.getInstance();
cal_day=cal.get(Calendar.DATE);
cal_month=cal.get(Calendar.MONTH);
cal_year=cal.get(Calendar.YEAR);
nextMonthDate=new Date();
nextMonthDate.setDate(cal_day);
nextMonthDate.setMonth(cal_month+1);
nextMonthDate.setYear(cal_year);
}
public void initCalendarNextWeek(){
cal=Calendar.getInstance();
cal_day=cal.get(Calendar.DATE);
cal_month=cal.get(Calendar.MONTH);
cal_year=cal.get(Calendar.YEAR);
nextWeekDate=new Date();
nextWeekDate.setDate(cal_day+7);
nextWeekDate.setMonth(cal_month);
nextWeekDate.setYear(cal_year);
}
Ok, so maybe look at Calendar class. The set methods of Date are deprecated so instead of using
nextMonthDate = new Date()
rather maybe use
nextMonthDate = new Calendar();
because then you can use the methods stated in the Calendar documentation such as add instead of using the setDate or setMonth. I hope this helps.
The below code is starting the thread only once, but I want to stop and start thread again by calling below method.
Thread th;
int t=45;
onstartbuttton()
{
th= new Thread(new callmymethod());
th.start();
}
onstopbutton()
{
}
public class callmymethod implements Runnable {
// TODO Auto-generated method stub
#SuppressWarnings("null")
#Override
public void run() {
// TODO Auto-generated method stub
while(t>-1){
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
time_btn.setText(""+t);
if(t==0)
{
Toast.makeText(getApplicationContext(), "Thread over", Toast.LENGTH_SHORT).show();
}
}
});Thread.sleep(1000);
// Log.i("Thread", "In run"+t);
t=t-1;
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
Now I want to stop thread, so what I have to write in onstopbutton() method and how to start again by calling onstartbutton() method.
You need to add a flag to your thread indicating that it should stop running.
You can use an AtomicBoolean:
final AtomicBoolean flag = new AtomicBoolean();
onstartbuttton() {
th= new Thread(new callmymethod(flag));
flag.set(true);
th.start();
}
onstopbutton() {
flag.set(false); // indicate that the thread should stop
}
public class callmymethod implements Runnable {
public AtomicBoolean flag;
public callmymethod(AtomicBoolean flag) {
this.flag = flag;
}
#Override
public void run() {
int t = 45; // start back from 45
while(t>-1 && flag.get()){
// do as before
}
}
}