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);
}
Related
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;
}
});
}
}
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 {
}
I want to develop media player type of application which has two button one for play and pause and one for stop. I take two image buttons in my layout file and reference it in Java file and code like this which I put here, but when I click on stop button audio is getting stopped but then I want replay audio file; but I cant play with play button.
my Java code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
mp = MediaPlayer.create(getActivity(), R.raw.arti);
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
Use This:
private BackgroundSound mBackgroundSound;
private MediaPlayer player;
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
player = MediaPlayer.create(HomePage.this, R.raw.background);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
player.setLooping(true); // Set looping
player.setVolume(volume, volume);
player.start();
return null;
}
}
For Playing:
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute();
For Stop:
mBackgroundSound.cancel(true);
if (player != null) {
player.stop();
player.release();
}
For Pause:
if (player != null) {
player.pause();
}
Try this it will help you....
//Click Listener on Image Button with play and Pause method
PLAY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Play-Pause();
}
});
//Play Pause method...........
public void Play-Pause(){
if (mediaPlayer.isPlaying()) {
PLAY.setImageResource(R.drawable.pause);
mediaPlayer.pause();
} else {
PLAY.setImageResource(R.drawable.play);
mediaPlayer.start();
}
}
Once a media player is stopped, you need to call prepare on it again to get it to a state where you can call start(). Look at the state diagram here http://developer.android.com/reference/android/media/MediaPlayer.html#pause%28%29
Check this code, its better and simple solution !
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
Switch sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this,R.raw.nokia);
sw = findViewById(R.id.sw);
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mp.setLooping(true);
}
});
}
public void play(View v){
mp.start();
}
public void pause(View v){
if(mp.isPlaying())
mp.pause();
}
public void stop(View v){
if(mp.isPlaying()) {
boolean loop=mp.isLooping();
mp.stop();
mp = MediaPlayer.create(this, R.raw.nokia);
mp.setLooping(loop);
}
}
}
I have develop application like media player to use for playing audio file from source but issue when I am change the orientation portrait to landscape button and other widget not working and other that is when I am again change orientation landscape to portrait so same issue button and seek bar is not working
my code is here
public class Aarati_Activity extends Fragment
{
private ImageButton btnplay;
private SeekBar seekbar;
MediaPlayer mp;
private ImageButton btnstop;
private int finalTime = 0;
private int startTime = 0;
private int oneTimeOnly = 0;
Handler handler=new Handler();
public Aarati_Activity() {}
int audiocurrent;
int audiomax;
private int mp_progress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
seekbar.setClickable(true);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekchange();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
mp = MediaPlayer.create(getActivity(), R.raw.arti);
audiomax=mp.getDuration();
audiocurrent=mp.getCurrentPosition();
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
btnplay.setImageResource(R.drawable.ic_action_play);
try
{
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getActivity(),"Aarti Currently not playing",Toast.LENGTH_SHORT).show();
}
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
}
});
return v;
}
#SuppressLint("NewApi")
public void seekchange()
{
mp_progress=seekbar.getProgress();
mp.seekTo(mp_progress);
}
private Runnable UpdateSongTime = new Runnable()
{
public void run()
{
startTime = mp.getCurrentPosition();
seekbar.setProgress((int)startTime);
handler.postDelayed(this, 100);
}
};
}
You need to use Service to play song. It will allow you to play song even when app is in background
Tutorial
Basically, from the MVC (Model-View-Controller) viewpoint, an Activity is a Controller, the view hierarchy is the View, and the View and Controller get re-created each time the orientation changes. Meanwhile, song playing belongs to the Model.
Note that an activity has the methods onSaveInstanceState(Bundle) and onCreate(Bundle), and if the bundle passed to onCreate() is not null, it contains the information previously stored by onSaveInstanceState().
And there's also onRetainNonConfigurationInstance(). When the screen turns, the old activity is destroyed and a new activity is created, and these methods let the old activity pass important data to the new one.
Even after you create a service, you have to keep this MVC stuff in mind.
I am attempting to use some of Google's code from their audio capture sample code. They simplified the heck out of their code and made their layout within the class. I want to have an actual xml layout. I know how to do that part, but I would like to know how to change the code below to an onClick method and have all the functionality that is provided with it.
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
Any help is appreciated.
In the layout file, you'll have something like...
<LinearLayout>
<Button android:id="play_button"/>
</LinearLayout>
In the activity, onCreate(), you can then do something like..
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
Button b = findViewById(R.id.play_button);
b.setOnClickListener(clicker);
ALTERNATELY, you can also define the method in the xml layout that will be called in the Activity...
<LinearLayout>
<Button android:id="play_button" onclick="play"/>
</LinearLayout>
and then in the Activity you simply create a method, called play(View view)
public void play(View view) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
Just define the buttons as Button and declare the booleans as Activity variables. Example...
public class AudioRecordTest extends Activity {
...
private Button mPlayButton = null;
private boolean mStartPlaying = true;
// Do the same for mRecordButton and mStartRecording
...
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// The next line assumes the play button has the id "#+id/play_button"
mPlayButton = (Button)findViewById(R.id.play_button);
mPlayButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
((Button)v).setText("Stop playing");
} else {
((Button)v).setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
// Do the same for the mRecordButton
}
}
Extending button just to set an onClickListener is not a good idea. You should only extend something when you are going to add new functionality to it. Not when you are going to use it for a particular purpose that does not require additional functionality.
Button button = new Button(this);
button.setOnClickListener(...);
If you need to use XML, you can load it programmatically with a LayoutInflater.
Your boolean isPlaying is not a property of the button itself but of the media it is playing. You should not hide it inside the button.