Hold the button for 2 seconds and then show an AlertDialog - java

I have a button and when I hold the button for 2 seconds, I want to show an AlertDialog.
This is what I have tried:
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Helper.setTimeout(() -> {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Message");
builder.setMessage(text);
builder.show();
System.out.println("I am text");
}
}, 2000);
return super.onTouch(view, motionEvent);
}
}
My method setTimeout():
public static void setTimeout(Runnable runnable, int delay){
new Handler(Looper.getMainLooper()).postDelayed(runnable, delay);
}
My problem is that sometimes the AlertDialog shows up multiple times and I always get this warning:
W/InputEventReceiver: Attempted to finish an input event but the input
event receiver has already been disposed.
What am I doing wrong?
I don't know if there is a better solution. I have also tried It with
btn.setOnLongClickListener(v -> {
System.out.println("hold");
return true;
});
but that doesn't output anything.

You can try this
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Message");
builder.setMessage("hello");
builder.show();
}
}, 2000);
return false;
}
});
}
}

Related

How can I move the Splash screen with touch

My splash screen diseapear after 2 seconds but I want it to diseapear also after a screen touch
Like if I press screen I moved next page without waiting until the end of the timer.
Is it possible??
public class SplashActivity extends Activity {
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
}
},2000);
}
}
Tes it is possible, you can add a touch listener to your layout that do the same as what will happen after two seconds , some thing like that
findViewById(R.id.myLayout).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
return true;
}
});
EDIT :
or you can instead add the next code outside onCeate method if the layout don't receive the touch event:
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
return super.dispatchTouchEvent(ev);
}

Use public boolean onKeyDown in all activities

I'm new in Android Studio and I have created a simple application with 10 activities.
Now, I want to intercept the KeyEvent.KEYCODE_BACK from the user in all of my activities.
I'm opening a dialog when KEYCODE_BACK. It's ok in my MainActivity but I don't want to copy this code in all of my activities.
Would anyone have an idea ?
public class MainActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
I think that you should separate this code into a separate abstract class and make exdends of this class for all your activities
public abstract class BaseActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
And in all activities
public class ActivityA extends BaseActivity {
}

Need a sound to play every second if a button is toggled

I have a toggle button and i need the 'mp' sound to play every second if that button is toggled.The code below is what i tried and it does play the sound every second but the button stops responding so i can't turn it off.
ToggleButton btn = findViewById(R.id.button);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.beat);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
while (isChecked) {
mp.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thank you in advance.
Never use Thread.sleep(1000) it is the terrible thing you can do to the app. Your app is not
responsding because you are putting Main thread of app to sleep.
I have created this class for you for desmonstration. you can tweak is further to your needs.
private Handler soundHandler = new Handler();
private int delay = 1000;
private Runnable soundRunnable;
private MediaPlayer mediaPlayer;
private boolean isToggleChecked;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = findViewById(R.id.button);
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
isToggleChecked = isChecked;
if(isChecked){
playSound();
}else {
stopSound();
}
}
});
}
#Override protected void onResume(){
super.onResume();
if(isToggleChecked){
playSound();
}
}
// this will make sure sound stops when app stops or goes in background
#Override
protected void onPause() {
soundHandler.removeCallbacks(soundRunnable);
super.onPause();
}
private void playSound(){
soundHandler.postDelayed(new Runnable() {
public void run() {
soundRunnable = this;
if(mediaPlayer != null) {
mediaPlayer.start();
}
soundHandler.postDelayed(soundRunnable, delay);
}
}, delay);
}
private void stopSound(){
if(mediaPlayer != null){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
soundHandler.removeCallbacks(soundRunnable);
}
}
}
I found an answer to another question and modified it to fit my needs and now it works perfectly.Here is the solution/code.
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer = null;
int delayMillis;
Handler handler;
Runnable runnable;
private boolean isToggleChecked;
private ToggleButton toggleButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.button);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
};
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isToggleChecked = true;
toggleMediaPlayer();
}
else {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
isToggleChecked = false;
}
}
});
}
#Override
public void onResume() {
super.onResume();
if (isToggleChecked) {
toggleButton.setChecked(true);
}
else {
toggleButton.setChecked(false);
}
}
private void toggleMediaPlayer(){
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
}else{
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
delayMillis = 1000;
handler.postDelayed(runnable,delayMillis);
}
});
}
}
}

delay between menu and game activity

I am making my own game for practising.
Once my game became bigger and bigger i noticed some delay once the main activity was about load.
So after reading, some threads i come up with another activity ( main ) showing a splash screen until the real main (menu) activity is loaded.
That worked pretty well, but since my game is on another activity once i change activity to play the game and then press the back button, or even when i am calling again the real main (menu) activity i face again this shitty lag/delay.
So to summurize, i have 3 activities so far.
1) The main activity which loads the splash screen and then calls the MenuActivity
2) The MenuActivity which basicly provides settings and buttons to start
3) The GameActivity which is the game
I could easily remove the MenuActivity and mix up the game with the menu activity handling the menu with the visibility of the images/buttons but i am wondering why is this happening for future knowleque also.
Here's the MenuActivity that makes the delay
public class MainActivity extends AppCompatActivity {
RelativeLayout _layer = null;
SharedPreferences _res;
Boolean _onFirstLoad=true,_bgMusic,_doubleBackToExitPressedOnce = false;
ImageView _musicBtnStop, _musicBtnStart, _about, _infoBtn;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(_onFirstLoad)
{
loadAllContent();
_onFirstLoad = false;
}
if (_bgMusic) {
_musicBtnStart.setVisibility(View.INVISIBLE);
BackGroundMusic.playMusic(); //starting
} else {
_musicBtnStart.setVisibility(View.VISIBLE);
_musicBtnStop.setVisibility(View.INVISIBLE);
}
//Start Game Button
_layer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
callGameStart();
return false;
}
return false;
}
});
_musicBtnStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callMusicStop();
}
});
_musicBtnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callMusicStart();
}
});
_about.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callGameStart();
}
});
}
#Override
public void onBackPressed() {
if (_doubleBackToExitPressedOnce) {
super.onBackPressed();
BackGroundMusic.quit();
return;
}
_doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
_doubleBackToExitPressedOnce=false;
}
}, 2000);
}
private void callGameStart() {
Intent game = new Intent(this, GameInterface.class);
startActivity(game);
}
private void callMusicStart() {
BackGroundMusic.setMuted(false);
_musicBtnStop.setVisibility(View.VISIBLE);
_musicBtnStart.setVisibility(View.INVISIBLE);
editor = _res.edit();
editor.putBoolean("bgMusic", true);
editor.apply();
}
private void callMusicStop() {
BackGroundMusic.setMuted(true);
_musicBtnStop.setVisibility(View.INVISIBLE);
_musicBtnStart.setVisibility(View.VISIBLE);
editor = _res.edit();
editor.putBoolean("bgMusic", false);
editor.apply();
}
private void loadAllContent() {
BackGroundMusic.setParams(MainActivity.this, R.raw.background_sound); //setting the music file
_layer = (RelativeLayout) findViewById((R.id.main));
_res = getApplicationContext().getSharedPreferences("com.nvm.tapper.prefs.xml", 0); // load our xml database
_bgMusic = _res.getBoolean("bgMusic", true);
_musicBtnStop = (ImageView) findViewById(R.id.stopMusic);
_musicBtnStart = (ImageView) findViewById(R.id.startMusic);
_about = (ImageView) findViewById(R.id.about);
}

andEngine alertdialog error

error java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare() =(
If I call showDialog (id) in GameActivity - works
But if I call activity.showDialog from another class - an error
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
Log.d("Dialog", "Dialog 1");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Help");
alert.setMessage("Help");
WebView wv = new WebView(this);
wv.loadUrl("http:\\www.google.com");
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
alert.setView(wv);
AlertDialog ALERT = alert.create();
return ALERT;
default:
return null;
}
}
I want to call a dialog with any other class
UPDATE:
new code activiti.runOnUiUpdate()
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("Dialog", "Dialog 1");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Help");
alert.setMessage("Help");
WebView wv = new WebView(this);
wv.loadUrl("http:\\www.google.com");
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
alert.setView(wv);
AlertDialog aALERT = alert.create();
}
});
return ALERT;
default:
return null;
}
}
Make your dialog in the update thread method, example
activity.runOnUiThread(new Runnable(){
#Override
public void run() {
//code for dialog creation goes here
}
});
update any internal references from this to the activities context activity
also you could just dialog.show() at the end of creating it and make it show up after its created. Hope I helped.

Categories

Resources