Reputation: 865
I have the following code which would give me a ringtone from my activity. I need this ringtone to keep ringing continuously for 30 seconds. As you can observe from the code below, I stop this ringtone on the 30th second using Timer. The issue I have is, instead of ringing continuously for 30 seconds, it rings for once and then stops. Can someone point out the solution for this such that I can have the ringtone for 30 seconds continuous?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
final Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
r.stop();
t.cancel();
finish();
}
}, 30000);
}
Upvotes: 0
Views: 2526
Reputation: 29
Please try the below code.
private Uri notification;
private final Ringtone r;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
playRing();
}//end of onCreate
private void playRing(){
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
r.stop();
t.cancel();
// I recommend not to put finish() in onCreate() method
//finish();
}
}, 30000);
}
Upvotes: 1
Reputation: 19790
Probably because the Ringtone and Timer are deleted after the onCreate.
Make the Ringtone and Timer a private member of your Activity.
Upvotes: 1