質問

i have a button when its clicked it will trigger doStartAlarm(View v) and this method will trigger a static method startAlarmNow, when i click the button it will start the alarm but then the application stops, this is part of the logCat :

FATAL EXCEPTION: main

java.lang.IllegalStateException: Could not execute method of the activity

Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

i wanted the onClick method doStartAlarm to call the static method startAlarmNow, so i can use this static method within a class that implements BroadcastReceiver,

this is my code bellow .

public class MainActivity extends Activity {
    static Ringtone ringtone = null;
    static AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);


}

    public static void startAlarmNow(Context context) {
    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

    if (alert == null) {

        alert = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        if (alert == null) {

            alert = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        }

    }
    if (ringtone != null) {
        Toast.makeText(context, "ringtone is  already playing",
                Toast.LENGTH_LONG).show();
    } else {
        ringtone = RingtoneManager.getRingtone(context, alert);

        ringtone.setStreamType(AudioManager.STREAM_ALARM);

        int volume = audioManager
                .getStreamVolume(AudioManager.STREAM_ALARM);
        if (volume == 0) {
            volume = audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_ALARM);
        }
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume,
                AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

        if (ringtone != null) {

            ringtone.play();
            Toast.makeText(context, "ringtone is playing",
                    Toast.LENGTH_LONG).show();

            Intent i = new Intent(context, StopAlarmActivity.class);
            context.startActivity(i);

        }
    }
}

public void doStartAlarm(View v) {
    Context context = getApplicationContext();
    startAlarmNow(context);

}
役に立ちましたか?

解決

instead using getApplicationContext() method use this which references Activity object which also is context.: startAlarm(this);

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top