Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

android - Setting up Alarm Manager is creating 2 Instances of my Main Activity

I have 2 activities, a Main Activity and SetAlarm Activity. I call SetAlarm Activity from Main. When I set up the alarm I create an instance of my main. How do I set up the alarm without creating another instance of the Main or do I kill the main before setting up the alarm? Quite new to this. I have read several of the alarm manager examples, but they all seem to set up a new intent and I think this is what is creating my 2 instances. Is this how you set up the alarm. It does go off.

Here is how I call SetAlarm from the Main:

public void setAlarm(View view) {
    Intent intent = new Intent(this, SetAlarmActivity.class);
    startActivityForResult(intent, 2);  
} 

Here is how I set up the Alarm:

public void setUpAlarm() {
    if (VERBOSE) Log.v(TAG, "+++ IN setUpAlarm +++");                   
        PLAY_MUSIC = "Y";
        Intent intentAlarm = new Intent(this, MainActivity.class);
        intentAlarm.putExtra("playMusic",PLAY_MUSIC);
        intentAlarm.putExtra("mPos", mPos);
        intentAlarm.putExtra("result",ALARM_SET);
        setResult(RESULT_OK,intentAlarm);
        pIntent = PendingIntent.getActivity(this, 12345, 
                intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
        am.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pIntent );
    } // setAlarmPlaySong

I cut the alarm off in the main:

@Override
public void onResume() {
    if (VERBOSE) Log.v(TAG, "+++ IN onResume +++");
    super.onResume();  
    Intent intent = getIntent()
    if (intent.hasExtra("playMusic")  && intent.hasExtra("mPos")) {
   playMusicFlag = intent.getStringExtra("playMusic"); 
   mPos = intent.getIntExtra("mPos", 0);   
   if (playMusicFlag.equalsIgnoreCase("Y")) {
       if (VERBOSE) Log.v(TAG, "+++ playMusicFlag is SET+++");
           playSongs();
               showStopAlarmButton();
       } // if    
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you want that your startActivity should not start multiple instances of alam activity you should go to your manifest and have to add an attribute named launchMode for your alarm activity and set it to SingleTop that will ensure that only one instance remains in the taskk back stack(plac where every activity resides in LIFO manner)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...