how to stop the toast message after stop executing the program - android

public class Home extends ActionBarActivity {
public static final String PREFS_NAME="LoginPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i("hello", "world");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please Enter the Details", Toast.LENGTH_SHORT).show();
}
});
}
}, 10, 10, TimeUnit.SECONDS);
}

Create a custom global object
private Toast toast;
Initialize it in onCreate
toast = Toast.makeText(YOUR_CLASS_NAME.this, "", Toast.LENGTH_SHORT);
Whenever you need to show a Toast
toast.setText("Text...");
toast.show();
To kill all the message based on requirement onPause or onDestroy
toast.cancel();

The problem with your code is that you don't stop the scheduler.
When you close the Activity the Application doesn't stop so the scheduler keeps running.
You can rewrite the code to stop the scheduler when activity stops and to start the scheduler when activity starts (instead of creation).
public class MainActivity extends ActionBarActivity {
private ScheduledExecutorService mScheduler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
mScheduler = Executors.newSingleThreadScheduledExecutor();
mScheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i("hello", "world");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please Enter the Details", Toast.LENGTH_SHORT).show();
}
});
}
}, 5, 5, TimeUnit.SECONDS);
}
#Override
protected void onStop() {
mScheduler.shutdown();
super.onStop();
}
}

Override onBackPressed() method in your activity, place this:
System.exit(0);
this is basically used to exit but this also stop the toast. try this.

Related

android app not responding with using thread

I implemented a program that have a UI. In UI I have 2 button (start and finish). When I clicked start button my service in my app run, and with finish button my service finished.
In my service I connected to xmpp server, when speed of internet is high I don't have any problem, but when speed of internet is low, it takes a long time to connect xmpp server and my UI don't do any thing and crashed. I put connecting to xmpp server in a thread.
my code is:
public class FirstAct extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
btnStart.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(act, MainActivity.class));
}});
btnEnd.setOnClickListener( new OnClickListener() {
#Override
public void onClick( View v ) {
stopService(new Intent(act, MainActivity.class));
}});
}
}
//------------------------
public class MainService extends Service {
#Override
public void onStart(Intent intent, int startId) {
....
toastHandler2.sendEmptyMessage(0);
....
}
private final Handler toastHandler = new Handler() {
#SuppressWarnings({ "null","unused" })
#Override
public void handleMessage(android.os.Message msg){
try{
connectToXmppServer();
}catch(Exception e){
}
}
};
what should I do that, when ConnectToXMPP takes a long time, all of program not crashed???
please help me
I solved my problem with this thread instead of Handler:
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
connectToXmppServer();
}
}).start();
}

Timer isn't cancelled by timer.cancel()

My Timer doesn't stop running if I cancel it!
The Timer only stops if I shut down the whole app!
I don't know why the Timer is not cancelled. If I print out every try on cancelling the Timer I get hundrets of lines but the Timer does not stop!
My Class:
public class PlayActivity extends AppCompatActivity
implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, MediaplayerEvent {
//region Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Initialize_Layout();
Initialize_Objects();
}
#Override
protected void onResume() {
super.onResume();
MusicService.setMediaPlayerEvent(this);
txvSongtitle.setText(serviceInterface.MP_getActualSong().getTitle());
Start_Timer();
}
#Override
protected void onPause() {
timer.cancel();
MusicService.clearMediaPlayerEvent();
super.onPause();
}
#Override
public boolean onSupportNavigateUp() {
finish();
return super.onSupportNavigateUp();
}
//endregion
//region Methods
private void Start_Timer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (serviceInterface.MP_isPlaying()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
seekBar.setMax(serviceInterface.MP_getDuration());
seekBar.setProgress(serviceInterface.MP_getCurrentPosition());
}
});
}
else {
runOnUiThread(new Runnable() {
#Override
public void run() {
timer.cancel();
}
});
}
}
}, 0, 200);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
serviceInterface.MP_seekTo(progress);
Start_Timer();
}
}
//endregion
}
I hope you can help me!
Thanks!
I would suggest using a Thread instead of a Timer. Your Start_Timer()code would change to something like the following:
private Thread mTimerThread;
...
private void Start_Timer() {
mTimerThread = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
if (serviceInterface.MP_isPlaying()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
seekBar.setMax(serviceInterface.MP_getDuration());
seekBar.setProgress(serviceInterface.MP_getCurrentPosition());
}
});
} else {
interrupt();
}
Thread.sleep(200);
}
} catch (InterruptedException e) {
}
}
}
mTimerThread.start();
}
Threads are more efficient and lightweight and perfect for your needs. Plus, by setting the Thread to a global variable, you can make sure to call mTimerThread.interrupt(); during Android lifecycle events, such as onPause().
I hope this fixes your issue. Remember, the Java Thread is your friend!
You're creating and starting a new timer the user moves the seekbar (in onProgressChanged()). That also means you lose the reference to the old one. When isPlaying turns false, all the timers will try to cancel timer -- which only references the most recent one.

Implementing Timer Task makes the application to crash

I am developing an application in which I want to implement timer task to print a toast message every 5 seconds. The problem is my application crashes after 5 seconds when i run it.Below is part of my code please tell me where I am making mistakes and how can I overcome it.
public class main_activity extends Activity implements BluetoothLeUart.Callback{
public ImageButton fabbutton;
Activity activity;
Timer time;
TimerTask timetask;
Handler handle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
fabbutton = (ImageButton) findViewById(R.id.fabbutton);
startTimer(); //this is where I start my timer task
fabbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanLeDevice(false);
Intent intent = new Intent(getApplicationContext(), ScanList.class);
startActivity(intent);
}
});
}
public void startTimer(){
time = new Timer();
initializeTimerTask();
time.schedule(timetask, 5000, 10000);
}
public void initializeTimerTask(){
timetask = new TimerTask() {
#Override
public void run() {
handle.post(new Runnable() {
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (time != null) {
time.cancel();
time = null;
}
}
}
you forgot to initialize handler,
Just add below line in oncreate or startTimer();
handle = new Handler();
Or even in your case you can use,
runOnUiThread(new Runnable(){
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});

While press back Button splash screen exits and opens Authentication Activity

I created two Activities "SplashActivity and AuthenticationActivity" When I start the app it loads the splash screen for 5 seconds and then it moves on to AuthenticationActivity. My problem is that when I run the app, it loads the splash screen, but within 5 seconds when I click the back button, SplashActivity exits, and immediately AuthenticationActivity appears in the foreground.
Does anyone know how to make it so when I click the back button, my app exits?
Here's my code so far:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread splashTimer = new Thread(){
public void run(){
try{
sleep(5000);
startActivity(new Intent(SplashActivity.this,AuthenticationActivity.class));
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
}
}
};
splashTimer.start();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}}
Timer timer;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initialize();
}
private void initialize()
{
timer = new Timer();
timerTask = new TimerTask()
{
#Override
public void run()
{
//Start your activity here
}
};
timer.schedule(timerTask,2500);
}
#Override
public void onBackPressed() {
super.onBackPressed();
timer.cancel();
}
or you can use Handler also
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initialize();
}
private void initialize()
{
handler = new Handler();
runnable = new Runnable()
{
#Override
public void run()
{
//start your activity here
}
};
handler.postDelayed(runnable, 5000);
}
#Override
public void onBackPressed() {
super.onBackPressed();
handler.removeCallbacks(runnable);
}

bar.setProgress(0) does not work

The following code is from Beginning Android 3, Chapter 20. When the phone is rotated, a new activity will be created and onStart() will be called, and so bar.setProgress(0) is called. However, I don't see the bar's progress is back to the beginning. Why not?
public class HandlerDemo extends Activity {
ProgressBar bar;
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
}
};
AtomicBoolean isRunning=new AtomicBoolean(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.get();i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
} catch (Throwable t) {
// just end the background thread
}
}
});
isRunning.set(true);
background.start();
}
public void onStop() {
super.onStop();
isRunning.set(false);
}
}
Try using this code
#Override
protected void onPause() {
super.onPause();
isRunning.set(false);
bar.setProgress(0);
}

Categories

Resources