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
Asked
Active
Viewed 480 times
3 Answers
1
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) { }

Matt
- 902
- 7
- 20
1
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();
}

Dr Mido
- 2,414
- 4
- 32
- 72
0
you can use
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//your code
}
}, 10000);

Sejpal Pavan
- 130
- 10