How to play song after X seconds from starting an activity - java

I'm creating an android application, i need a way to run song after some seconds from starting activity, by default the song starts directly after i open that activity.
thank you for your help

Whenever you need to wait for a specific period of time in a single thread, you can use:
try {
Thread.sleep(millis);
} catch (InterruptedException e) { }

By using Thread.sleep() or SystemClock.sleep() this causing blocking/freezing of Main thread of the app, I suggest using Handler.postDelayed() instead
firstly add your media file under res/raw directory, If isn't exist you must create it.
right click on res directory >> new >> Android Resource Directory
on Resource type choose raw, then copy your media file to it for example "song.mp3"
the code
public class MainActivity extends AppCompatActivity {
//Creating MediaPlayer object
private MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
player = MediaPlayer.create
(MainActivity.this, R.raw.song); // >> here's choose your song file
player.start();
}
}, 10000); // >> Put time with milliseconds, this will delay the start play for 10 seconds
}
you may want to stop the song by override onStop method like this
#Override
protected void onStop() {
super.onStop();
if (player.isPlaying())
player.stop();
}

you can use
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//your code
}
}, 10000);

Related

Hanging the UI thread in Android deliberately [duplicate]

Why i can't force Android ANR with this code?
No log messages or pop up. The application is just launched lazily.
[UPDATE]
I can't get it even sleeping a View.setOnClickListener or BroadcastReceiver.onReceive!
Is there a trick?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e("Test", "", e);
}
}
}
I'm using Samsung GT-6200L with stock Android 3.2
Try it in onTouchEvent. In onCreate your activity is not fully running
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG,"onTouchEvent");
while(true) {}
}
The ANR-WatchDog project has a test app that produces ANRs in a reliable manner (as reliable as ANRs can be): the app hangs because of a deadlock.
The gist of it:
Prepare a lock object as a private field in your activity:
final Object mutex = new Object();
Have a thread that performs some work in a critical section, and an android.os.Handler that posts work depending on the same lock.
new Thread(new Runnable() {
#Override
public void run() {
synchronized (mutex) {
while (true) {
try {
Thread.sleep(60000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
synchronized (mutex) {
// Shouldn't happen
throw new IllegalStateException();
}
}
}, 1000);
Putting the above code snippet inside a button click handler, for example, should do the trick.
I've been facing the same issue yesterday, and I've found out that using a plain debug build ANR dialogs simply won't show up. (Although the UI thread was completely hanged.)
But after exporting and properly signing the application the dialogs were popped up properly (in every cases mentioned above). However I am still not sure what really prevents to pop up ANR messages, maybe someone else can clarify this later...
Try using:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int a=0;
while(true) {
a++;
}
}
Your code probably didn't work because it got setup too early, and the Activity probably wasn't fully initialized and created yet. With the above code, launch the activity and touch/swipe on the screen and wait for the ANR dialog to popup.
Make a button in your activity.
public void onBtn1(View v) {
int a = 0;
while(true) {
a++;
}
}
Make the button execute the above code.
Spam click the button with your finger =)
I used this code for force ANR
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void force(View view){
while(true) {}
}
I just created a simple button in the xml file and set android:onClick=force

Android: Media Player not pausing in second activity using ImageView

I have spent almost the day trying to figure it out and yet could not manage to achieve it. I basically have two activities, MainActivity.java and GameActivity.java. The music stops but after going back to MainActivity.java and coming back to GameActivity.java using ImageView several times.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView iv;
public static final String BG_SOUND_CHECK = "background playing!";
// public static MediaPlayer backgroundSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
final MediaPlayer backgroundSound = MediaPlayer.create(this, R.raw.background_music);
handler.postDelayed(new Runnable() {
#Override
public void run() {
backgroundSound.setLooping(true);
backgroundSound.start();
Log.v(BG_SOUND_CHECK, "After loop Started!");
}
}, 3000);
getSupportActionBar().hide();
iv = (ImageView)findViewById(R.id.playImage);
iv.setOnClickListener(new View.OnClickListener(){
public void onClick(View view1){
// backgroundSound.setLooping(false);
backgroundSound.pause();
// Log.v(BG_SOUND_CHECK, "Playing After Play Button Click");
Intent myIntent = new Intent(MainActivity.this, GameActivity.class);
// myIntent.putExtra("backgroundSoundObj",backgroundSound);
startActivity(myIntent);
// Log.v(BG_SOUND_CHECK, "After Game Scene");
}
});
}
}
GameActivity.java
public class GameActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// MainActivity.backgroundSound.pause();
// Rest of the code
}
}
I tried putting the music onPause(); in
1) ImageView onClick();
2) As soon as the GameActivity.java is loaded
but both ways end up pausing it only after I try coming back to MainActivity.java and going to GameActivity.java several times.
Do you see how you put your backgroundSound.start() inside the postDelayed-3000 ?
backgroundSound.pause() anytime before that 3000ms is not going to do anything.
It has nothing to do with going back and forth between your two activities, it just so happens that doing that takes up more than 3000ms, so when you do click for pause(), 3000ms has passed.
What you can do, to fit your current code, is to separate that into a Runnable.
Runnable bgSound = new Runnable() {
#Override
public void run() {
backgroundSound.setLooping(true);
backgroundSound.start();
Log.v(BG_SOUND_CHECK, "After loop Started!");
}
}
Use it with handler.postDelayed(bgSound, 3000)
In your onClick, if you want to stop it from playing before it starts, can use handler.removeCallbacks(bgSound), to stop it after it plays, your pause(). If you don't care to know if it has or hasn't started, you can do both alongside each other, should work fine too.
(if you don't want the music to play after you've left your main activity, you should also do the same actions in your onDestroy and/or onPause)

Making a temporary Activity .. Like a hello screen

I want to make a temporary Activity that allowed me to show it , For Example it is appear only for 5 seconds so how can I make it >> Like a hello screen in the beginning in my app .
By the way I am using Android Studio
The splash screen displays for 2 seconds and then the main activity of the application appears. For this, we add a java class that displays the splash screen. It uses a thread towait for 2 seconds and then it uses an intent to start the next activity.
public class SplashScreen extends Activity {
private long ms=0;
private long splashTime=2000;
private boolean splashActive = true;
private boolean paused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread mythread = new Thread() {
public void run() {
try {
while (splashActive && ms < splashTime) {
if(!paused)
ms=ms+100;
sleep(100);
}
} catch(Exception e) {}
finally {
Intent intent = new Intent(SplashScreen.this, Splash.class);
startActivity(intent);
}
}
};
mythread.start();
}
}

background music automatically stops

I have made an application with Splash Music. But whenever I go in preferences of app, the music automatically stops, and then never plays untill I restart the application. Same is the case when I open an activity, which tells whether phone is in "Normal" or in "Silent" Mode.
What is the reason for this weird behavior?
Here is the Splash music code where I check whether to play music or not..
public class SplashScreen extends Activity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
mp= MediaPlayer.create(SplashScreen.this, R.raw.got);
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
;
if(pref.getBoolean("music", true))
{
mp.start();
}
if(pref.getBoolean("loop", true))
{
mp.setLooping(true);
}
Thread timer= new Thread()
{
public void run()
{
try
{
sleep(5000);
Class ourclass = Class.forName("com.umer.practice2.Menu");
Intent myintent= new Intent(SplashScreen.this,ourclass);
startActivity(myintent);
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Thanks
It is because you are creating and playing your mediaplayer object on the main thread. When your activity is getting paused, you are finishing the activity which is stopping your mediaplayer. If you want to keep you music independent of the activity, offshore it to a service.
Running in a Service should help you.

Create opening application

I would like to display an image at the opening of my application Android (Java), is like a toast in full screen only.
That is, when you open the application and an image appears and disappears after you start the program.
What better way to do this?
You mean Splash screen? If so, here is your answer: Splash Screen
It's called a SplashScreen
the links are here
http://www.anddev.org/simple_splash_screen-t811.html
and here
http://blog.iangclifton.com/2011/01/01/android-splash-screens-done-right/
Cheers
I think you are looking for Splash screen in android.
I found above link really helpful. There are lots of other article available. Just ask Google
You have to create an Activity with this image on the layout.
Then within this activity, create a Thread that will sleep for X seconds. When the Thread slept enough, start a new activity.
This is an example code :
public class SplashActivity extends Activity {
public StartThread th;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
th = new StartThread(this);
th.start();
}
}
class StartThread extends Thread {
SplashActivity parentActivity;
public StartThread(SplashActivity splashActivity) {
this.parentActivity = splashActivity;
}
#Override
public void run() {
super.run();
try {
this.sleep(3000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
Intent menu = new Intent("com.yourpackage.yourapplication.NEXTACTIVITY");
this.parentActivity.startActivity(menu);
this.parentActivity.finish();
this.parentActivity.th = null;
}
}
}

Categories

Resources