user3817175
user3817175

Reputation: 3

Activity not showing?

I am trying to build an app that works as an alarm clock. I implemented everything with help of the AlarmManager and it works fine. But I have one problem, when the alarm rings it starts an Activity which shows a screen with a button and plays a sound. But it shows only a black screen and vibrates + plays the sound and then after that it shows the alarm screen.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wecker);
    laufen = true;
    mp = MediaPlayer.create(getApplicationContext(), R.raw.ton); 
    verstanden =(Button)findViewById(R.id.button1);
    verstanden.setOnClickListener(new View.OnClickListener() {public void onClick(View view) 
    {
        finish();
    }
    });
    for (int i=0; i<10;i++)
    {
    mp.start(); 
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(1000);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    }
}

}

What can I do to show the activity and play the sound simultaneously?

Upvotes: 0

Views: 50

Answers (2)

Uwais A
Uwais A

Reputation: 737

You have put Thread.sleep(1000); in your onCreate() method which is on your UI Thread. Your activity's UI only shows up at onResume() which is after onCreate() so it doesn't get there until your sleep commands are finished. You need to create a new Thread and run the vibrator/sleep cycle on that Thread. Usage is shown in Shivam Verma's answer.

Upvotes: 0

Shivam Verma
Shivam Verma

Reputation: 8023

Thread.sleep(1000); Blocks your UI Thread hence, the black screen shows up.

Use this :

new Thread( new Runnable() {
    public void run()  {
        try { 
        // Add loop to play music and vibrate here

        } catch (InterruptedException ie)  {}
    }
) }.start();

Upvotes: 1

Related Questions