How to end a handler and change activity with a button? - java

Hello I am a college student with a background of html and JavaScript making this app as a side project for work. I would like help with ending a count down timer early via a button press while also taking the user to another activity. I have used two different guides to assemble my code and I have the timer working. I have a limited knowledge of java so any help would be welcomed, here is my code:
public class Main2Activity extends AppCompatActivity {
Button button1;
int flag=0;
// page should show up for 2 seconds then take you to the main page, but I want a button there to stop the count down and take the user to a different page That I will use as a credits page
private static int TIME_OUT = 2000; //Time to launch the another activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Main2Activity.this, MainActivity.class); //Main2Activity is the Welcome page and MainActivity is the home page
startActivity(i);
finish();
}
}, TIME_OUT);
button1 = (Button) findViewById(R.id.credit);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
Handler.removeCallbacksAndMessages(null);
Intent intent = new Intent(Main2Activity.this, credit.class);
startActivity(intent);
}
});
}
}

You should declare a global Handler and use it everywhere. Don't use final in Handler
Handler handler;
private static int TIME_OUT = 2000; //Time to launch the another activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Main2Activity.this, MainActivity.class); //Main2Activity is the Welcome page and MainActivity is the home page
startActivity(i);
finish();
}
}, TIME_OUT);
button1 = (Button) findViewById(R.id.credit);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
handler.removeCallbacksAndMessages(null);
Intent intent = new Intent(Main2Activity.this, credit.class);
startActivity(intent);
}
});
}

You can use sendMessage+removeMessage to CANCEL a post but you cant execute it immediately.
Handler h = new Handler() {
public void handleMessage(int what){
Intent i = new Intent(Main2Activity.this, MainActivity.class);
startActivity(i);
finish();
}
}
h.sendEmptyMessageDelayed(111, TIME_OUT);
//On your button Listener
h.removeMessages(111);
This way the message will be canceled and not fired in the timeout.

Related

Add a back button in activity

Good morning, Guys I have a code that plays an audio when the activity starts it performs a welcome greeting, however when I go to other activities and return to the main menu the audio is played again I would like to notice that when I use the back action bar button I don't have this problem, but I need to use a button in the fragment or activity, I can't have an action bar in my app
Code to Play audio:
new Timer().schedule(new TimerTask() {
#Override
public void run() {
MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
play.start();
}
}, 1000);
Code button on fragment:
button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(getContext(), MainActivity.class);
startActivity(intent1);
}
});
Stop your media playback when you leave the activity in onPause of the Activity
#Override
public void onPause() {
super.onPause();
play.stop();
}
And you don't need to restart the previous activity on click of the button in the second activity, you just need to call onBackPressed() to go to the previous activity.
button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
This is my second answer.
In the case you have to relauch the first activity(if it is destroyed) from the second one,
you can also use onSaveInstanceState(Bundle outState)
to save the audio played state in the activity.
In the first activity
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlayed",true);
super.onSaveInstanceState(outState);
}
In onCreate() of the first activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstaceState.getBoolean("isPlayed") == false) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
play.start();
}
}, 1000);
}
}
Later on, you can relaunch the first activity from the second activity.
button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(getContext(), MainActivity.class);
startActivity(intent1);
}
});
Dont forget to stop the audio playback in the first activity.
#Override
public void onPause() {
super.onPause();
play.stop();
}

How to use mediaplayer and update seekbar in a function that contain custom dialog in android studio?

I want to use mediaplayer in a function that provide dialog with positive and negative answer. when positive answer selected one audio will played, and when negative selected another activity will appear.
I do these and my audio play successfully, but my seekbar couldn't update.
my function name is autoPlayDialog that code of call is this:
else {
if(MainActivity.getBadgeCount() == 0 ){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
}
}, 3000);
} else {
autoPlayDialog();
//Intent i = new Intent(Splash.this, MainActivity.class);
//startActivity(i);
}
}
and then my function code is:
private void autoPlayDialog()
{
final MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.song2);
final SeekBar seekBar;
final Runnable runnable;
final Handler handler;
final ImageView playIcon;
seekBar = findViewById(R.id.autoseekbar);
playIcon = findViewById(R.id.autopauseplay);
handler = new Handler();
View view = LayoutInflater.from(Splash.this).inflate(R.layout.activity_auto_play,null);
final AlertDialog dialog = new AlertDialog.Builder(this)
.setView(view)
.setTitle("new message")
.setMessage("Do you want to play?")
.setPositiveButton("Yes", null) //Set to null. We override the onclick
.setNegativeButton("No", null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
playIcon.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
changeSeekbar();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playIcon.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
dialog.dismiss();
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
}
});
}
});
Button button2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
}
});
}
});
dialog.show();
}
My problem is that this line of code seekBar.setMax(mediaPlayer.getDuration()) make error and my app closed. autoPlayDialog function is developed in Splash activity and seekbar assigned to another xml file seekbar with this line of code seekBar = findViewById(R.id.autoseekbar) that this xml file assigned to view of my dialog: View view = LayoutInflater.from(Splash.this).inflate(R.layout.activity_auto_play,null);
Also about playIcon image i have this problem too.
Thank you for your attention :)

Why doubleclick on a custom button crashes an android app

I implemented a custom button and added a task to it with delay so it shows the animation.
When I double click it, it crashes. I want to make so it's only clickable once.
i have tried setEnabled(false);
i have tried setClickable(false);
i tried a variable that check if a button has been clicked and disables it.
public class Login extends AppCompatActivity {
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final SubmitButton LoginBtn = findViewById(R.id.login);
handler = new Handler();
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBtn.setEnabled(false);
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoginBtn.setEnabled(true);
Intent startActivity = new Intent(Login.this, Main_page.class);
startActivity(startActivity);
finish();
}
}, 3200);
}
});
}
}
As I wrote, I want that if the button has been clicked that it becomes unclickable.
Try this:
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final SubmitButton LoginBtn = findViewById(R.id.login);
handler = new Handler();
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBtn.setEnabled(false);
handler.postDelayed(new Runnable() {
#Override
public void run() {
LoginBtn.setEnabled(true);
Intent startActivity = new Intent(Login.this, Main_page.class);
startActivity(startActivity);
finish();
}
}, 3200);
}
});
...
Explanation:
Your enable/disable block is outside of the onClick listener and it's in the onCreate method: in this way you call setEnable() method only when the activity was created.
But some time setEnable() can not work in case of very rapid click like explained in the second response here. In that case you can use a timer to check the elapsed time.
By the way, I think that your app crash because you don't handle in the right way the Handler. I suggest you also to add:
#Override
protected void onStop(){
handler.removeCallbacksAndMessages(null);
}
Try...
view.setOnClickListener(null);
...after your click event.

Remove activities manually from Android app stack

I been working on Android Native App , What i was trying to do is :
Activities - A -> B -> C Then A-> B -> C -> C .
From C Activity if it again point to C then i want to remove C , B from stack manually .
On my back it should move only to A .
I tried finish() but problem is :
Activities - A -> B -> C Then A-> B -> C -> C on finish A -> B -> C required state A-> C .
Is anyone know how to catch all activities in stack and remove specific activities from stack ??
In Activity C, override onBackPressed and add in something like:
#Override
public void onBackPressed() {
if (shouldGoBackToA) { // There are various ways this could be set
Intent intent = new Intent(this, AActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
finish();
}
}
FLAG_ACTIVITY_CLEAR_TOP will cause it to go down the stack to the existing copy of A Activity instead of starting a new one. From the docs:
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
While calling intent pass a flag called actvity clear top like this:
Intent newIntent=new Intent(this,MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(newIntent);
You can use this :
In A activity while passing to B activity, the intent should be added with a flag FLAG_ACTIVITY_NO_HISTORY like this,
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent=new Intent(AActivity.this,Bactivty.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(newIntent);
}
});
While moving to CActivity:
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent = new Intent(Bactivty.this, CActivity.class);
startActivity(newIntent);
}
});
On backpress will take you to AActivity now.
Step 1: Start activty for result A -> B -> C1 -> C2..
Call your Activity with startActivityForResult
Intent intent = new Intent(yourActivity.this, nextActivity.class);
startActivityForResult(intent, 1);
Step 2: In C2 specify that you want to go back to A..
Whenever you are done with your activity write the below code
Intent i = getIntent();
i.putString("Result","GottoA");
setResult(Activity.RESULT_OK, i);
finish();
Step 3: Whenever C2 finishes , previsus stack activit's onActivityResult is called.. so u can check in C1 and B onActivityResult whether you have set any result bck.. and finish accordingly
and impliment the following code in Activity B and c
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent i = getIntent();
if (resultCode == RESULT_OK && i.getString("Result","null").equals"GottoA") {
i.putString("Result","GottoA");
setResult(RESULT_OK, i);
finish();
}
}
In Activity C, when back button is pushed start activity A like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), A.class);
intent.putExtra("EXIT", true);
startActivity(intent);
}
Then in Activity A's onCreate() do this
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
this complete example may help you...
public class ActivityA extends Activity {
public static final int ID_TEXTVIEW = 0xDEAF1;
public static final int ID_BUTTON = 0xDEAF2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = getContentView(this);
TextView textView = (TextView) contentView.findViewById(ID_TEXTVIEW);
textView.setText("ActivityA");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
});
}
public static View getContentView(Context context) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
TextView textView = new TextView(context);
textView.setLayoutParams(layoutParams);
textView.setId(ID_TEXTVIEW);
layout.addView(textView);
Button button = new Button(context);
button.setText("Next");
button.setLayoutParams(layoutParams);
button.setId(ID_BUTTON);
layout.addView(button);
return layout;
}
}
public class ActivityB extends Activity {
public static final String ACTION_FINISH = "com.myapp.test2.ACTION_FINISH";
public ActivityB() {
}
private FinishReceiver finishReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityB");
setContentView(contentView);
final Button button = (Button) contentView
.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
}
});
finishReceiver = new FinishReceiver();
IntentFilter filter = new IntentFilter(ACTION_FINISH);
registerReceiver(finishReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(finishReceiver);
}
private class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH)) {
finish();
}
}
}
}
public class ActivityC extends Activity {
public ActivityC() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityC");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.ACTION_FINISH);
sendBroadcast(intent);
intent = new Intent(ActivityC.this, ActivityC.class);
startActivity(intent);
finish();
}
});
}
}

Android. Call system dialog

Is there a way to open the system dialog settings->location & security->Install from SD card programmatically from my application?
You launch at least the security setting by the following code.
public class MainActivity extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName(
"com.android.settings",
"com.android.settings.SecuritySettings");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}

Categories

Resources