How to Stop a Loop at the Press of a Button - java

I want the onClick method not only to create a new activity to the new page, but also to trigger the end of the loop, so that if someone clicks the background of the splash screen, the new screen doesn't reload after the loop stops.
Here is my code,
package clouds.clouds;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread logotimer = new Thread() {
#Override
public void run(){
try{
int logotimer = 0;
while(logotimer <5000) {
sleep(100);
logotimer = logotimer +100;
}
startActivity(new Intent("clouds.clouds.SPLASH"));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
}
};
logotimer.start();
}
public void onClickz(View v){}
public void speed2 (View v){
startActivity(new Intent("clouds.clouds.BUTTONZ"));
}
}
Any suggestions?

Call logotimer.interrupt() in your onClick() method. This should cause an InterruptedException in your thread which you should handle by doing nothing (or whatever else you want to do when you interrupt your thread)

Add a volatile boolean variable to your class (call it cancelled). Set it to true when the button is clicked, and check for cancelled == false in your while condition.
public class splash extends Activity {
volatile bool cancelled = false;
...
protected void onCancel(...)
{
cancelled = true;
...
while(!cancelled && logotimer <5000) {
...

boolean exit = false;
int logotimer = 0;
while(logotimer <5000 && exit != false) {
sleep(100);
logotimer = logotimer +100;
// value = ???
if(logotimer == value) {
exit = true;
}
}

package clouds.clouds;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class splash extends Activity {
Thread logotimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
logotimer = new Thread();
Thread logotimer = new Thread() {
#Override
public void run(){
try{
int logotimer = 0;
while(logotimer <5000) {
sleep(100);
logotimer = logotimer +100;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
startActivity(new Intent("clouds.clouds.SPLASH"));
}
};
logotimer.start();
}
public void onClickz (View v){}
public void speed2 (View v){
logotimer.interrupt();
startActivity(new Intent("clouds.clouds.BUTTONZ"));
}
}

Related

How to display a textView Multiple times Based in time

I want to display a TextView during 10 seconds, then make it disappear, every 5 minutes, but I am not able to do it, I have already read this Android CountDownTimer - adding time results in multiple timers running, and many others, but still cant do it, here is what I have tried
private void placeFingerPrint() {
authViewModel.getSession().compose(bindToLifecycle()).subscribe(session -> {
this.session = session;
TextView textView = view.findViewById(R.id.player_finger_print);
MediaItem mediaItem = getPlayingMediaItem();
new CountDownTimer(20000, 10000) {
#Override
public void onTick(long millisUntilFinished) {
if (fingerprint.getChannel() != null && fingerprint.getChannel().contains(mediaItem.getExternalId())) {
textView.setVisibility(View.VISIBLE);
textView.setText(session.getHouseHoldId());
} else {
textView.setVisibility(View.GONE);
}
}
#Override
public void onFinish() {
textView.setVisibility(View.GONE);
start();
}
}.start();
});
We can achieve this using Thread in android. CountDownTimer usually uses if you have a definite end time.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ThreadSample extends AppCompatActivity {
Handler uiHandler = new Handler();
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_sample);
textView = findViewById(R.id.textView);
NameCounter runnable = new NameCounter();
new Thread(runnable).start();
}
class NameCounter implements Runnable {
int count = 0;
boolean show = true;
#Override
public void run() {
while (true) { // add your customized condition here to exit from the loop.
uiHandler.post(new Runnable() {
#Override
public void run() {
if (show)
textView.setVisibility(View.VISIBLE);
else
textView.setVisibility(View.GONE);
}
});
try {
if (show) {
Thread.sleep(10000);
show = false;
} else {
Thread.sleep(5000);
show = true;
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
}
}
}

Media Player pauses the music when the activity loses focus(when home or screen goes off)

the mediaplayer stops music when homebutton is pressed or screen goes off....I want the music to continue even if the activity loses focus....but i want the music to pause for the incoming calls and if user pauses the music....also the music should stop when the activity is closed via the back button
here's sample of my code:
package com.example.acer.aartisangrah;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize(18);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private final PhoneStateListener mPhoneListener=new PhoneStateListener(){
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
// Call receive state
if (state != TelephonyManager.CALL_STATE_IDLE) {
if ((play!= null) && (play.isPlaying()))
{
play.pause();
but19.setBackgroundResource(R.drawable.play);
}
}
}
};
public void run() {
int currentPosition = play.getCurrentPosition();
final int total = play.getDuration();
while (play != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setBackgroundResource(R.drawable.play);
} else {
play.start();
but19.setBackgroundResource(R.drawable.pause);
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
play.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play.seekTo(0);
but19.setBackgroundResource(R.drawable.play);
}
});
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
protected void onDestroy()
{
super.onDestroy();
play.release();
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(22);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize(18);
count = 0;
}
if (count == 1) {
tv4.setTextSize(22);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
}
EDIT
After using this code for the activity...this activity does not get opened on some devices...the app just closes itself....Please Help!!!
Other activities without this code works just fine...
First of all, you have the following code
#Override
protected void onPause()
{
super.onPause();
if ((play!= null) && (play.isPlaying()))
{
play.pause();
}
}
onPause method is executed every time the activity goes to background (loses focus) or when it is closed by the user. So your first step would be to remove this code from the onPause method, where you deliberately call play.pause().
You should overwrite the onBackPressed() method and do something similar to what you are doing but calling play.stop()
Check here, specifically on the Performing cleanup section where it says the following
a MediaPlayer object can consume a significant amount of system
resources, so you should keep it only for as long as you need and call
release() when you are done with it. It's important to call this
cleanup method explicitly rather than rely on system garbage
collection because it might take some time before the garbage
collector reclaims the MediaPlayer
Make sure to take a look at that guide as well.
To stop pausing of music when app gets to background. Comment play.pause() as below:
#Override
protected void onPause()
{
super.onPause();
if ((play!= null) && (play.isPlaying()))
{
// play.pause();
}
}
The playback should itself stop it on back press (I'm almost certain). Make sure you dispose off the mediaPlayer in onDestroy().
To stop it on call receive. Instantiate the following receiver in your activity:
// Listens for phone state and pauses in an event of call
private final PhoneStateListener mPhoneListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
// Call receive state
if (state != TelephonyManager.CALL_STATE_IDLE) {
if ((play!= null) && (play.isPlaying()))
{
play.pause();
}
}
}
};
You need to register for it as (probably in onCreate()):
// Make mTelephonyManager an instance variable
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Don't forget to unregister it in onDestroy():
mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);

Radio app into a service [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hi I was following a tutorial I found to make an app that plays a radio, the app works until you exit because then the sound stops. I have researched and found out that it needs to be a service but I am not sure how to change it to a service, this is the code I used.
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
I tried changing it but I am not sure how to put the functions from the main activity into a new service and then run it.
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
} // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I tried using the above code but I do not know how to start the action and whether or not it will work.
Thank you for reading :)
Call a service from your main activity.
startService(new Intent(MusicService.ACTION_PLAY));
your service class.
public class MusicService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
return START_STICKY;
}

How do I use a while loop with an onTouch function? (Android)

Well, I have been looking up answers, but none have worked for me. I have a button that when it is HELD DOWN, is suppose to continue to move an image across the screen. But for some reason, it just keeps freezing my kindle when I tap the button. I think the thread is part of the problem, but i'm unsure. Here is the code:
package com.evilsea.darkages;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnTouchListener, Runnable {
ImageView leftImageButton;
boolean leftButtonDown = false;
ImageView knight;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread1 = new Thread(this);
thread1.start();
this.run();
}
public void addListenerOnLeftButton() {
leftImageButton = (ImageView) findViewById(R.id.left_button);
leftImageButton.setOnTouchListener(leftButtonlistener);
knight = (ImageView) findViewById(R.id.knight_image);
}
OnTouchListener leftButtonlistener = new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
leftButtonDown = true;
try {
while(leftButtonDown) {
Thread.sleep(10);
moveLeft(5);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
leftButtonDown = false;
break;
}
return false;
}
};
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
#Override
public void run() {
addListenerOnLeftButton();
}
public void moveLeft(int speed) throws InterruptedException {
knight.setLeft(knight.getLeft() -speed);
}
}
BTW, I am just starting out w/ android, so I am sorry if this is an obvious question. Thanks! Much appreciated.
Firstly, you are making a UI thread sleep that's why your UI is getting freeze.Here, i have created a async task where i am sleeping background thread and running a UI update on main thread as you can see below in doInBackground method.Here is your solution -:
public class MainActivity extends Activity {
private ImageView leftImageButton;
private boolean leftButtonDown = false;
private ImageView knight;
private AsyncTask asyncTask = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leftImageButton = (ImageView) findViewById(R.id.imageView2);
knight = (ImageView) findViewById(R.id.imageView1);
leftImageButton.setOnTouchListener(new LeftImageListener());
}
public void startTask() {
asyncTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
if (leftButtonDown) {
while (leftButtonDown) {
try {
Thread.sleep(10);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
moveLeft(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return null;
}
}.execute();
}
public void moveLeft(int speed) throws InterruptedException {
knight.setLeft(knight.getLeft() - speed);
}
public class LeftImageListener implements OnTouchListener {
public LeftImageListener() {
// TODO Auto-generated constructor stub
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
leftButtonDown = true;
startTask();
break;
case MotionEvent.ACTION_UP:
leftButtonDown = false;
break;
default:
break;
}
return true;
}
}
}
create a second thread was right but you should fill it with some action cause the thread you`ve created is an empty one :)
and you dont need to call run after starting your thread.
Thx Abhishek Birdawade for doing the code work for me :)

java.lang.UnsupportedOperationException error on splashscreen.java

I keep getting this errors related to Thread.stop() in splashscreen.java. I'm pretty new at it and aware of deprecated Thread.stop() but can someone please explain what I'm doing wrong here, thanks..
java.lang.UnsupportedOperationException
at java.lang.Thread.stop(Thread.java:1076)
at java.lang.Thread.stop(Thread.java:1063)
at com.dapp.d.SplashScreen$4.run(SplashScreen.java:88)
This is full source code of splashscreen.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
public class SplashScreen extends Activity {
private boolean active = true;
private int splashTime = 3000;
private boolean clickFlag = true;
private Thread splashTread = null;
private Button btnHelp;
private Button btnAboutUs;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.splashRelativeLayout);
relativeLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri uri = Uri.parse("http://www.exmaple.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
btnAboutUs = (Button)findViewById(R.id.btnAboutus);
btnHelp = (Button)findViewById(R.id.btnHelp);
try{
btnAboutUs.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
clickFlag = false;
splashTread.stop(); <<<<<<<<<<<<<<<<<<< line 49
Intent intent = new Intent();
intent.setClass(getApplicationContext(), AboutUs.class);
startActivity(intent);
SplashScreen.this.finish();
}
});
btnHelp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
clickFlag = false;
splashTread.stop(); <<<<<<<<<<<<<<<<<<< line 63
Intent intent = new Intent();
intent.setClass(getApplicationContext(), HelpActivity.class);
startActivity(intent);
SplashScreen.this.finish();
}
});
splashTread = new Thread() {
#Override
public void run() {
try{
int waited = 0;
while(active && (waited < splashTime)) {
sleep(100);
waited += 100;
}
} catch(InterruptedException e) {
// do nothing
}finally {
if(clickFlag){
Intent intent=new Intent();
intent.setClass(getApplicationContext(), SearchWord.class);
startActivity(intent);
finish();
stop(); <<<<<<<<<<<<<<< line 88
}else{
finish();
stop();
}
}
}
};
splashTread.start();
}catch (Exception e) {
// TODO: handle exception
}
}
}
I don't think you need to call stop there at all. Your thread doesn't loop so it will execute and end normally. Try just removing the stop();
I had a similar problem and the solution is to wrap the stop method in a try/catch statment and in the catch use Throwable t.
It will work.

Categories

Resources