How can I setup multiple alarms in Android?

不羁的心 提交于 2019-11-27 06:53:35

Ok, when you set an PendingIntent, you're supposed to assign it a unique ID to it, incase you want to identify it later (for modifying/canceling it)

static PendingIntent    getActivity(Context context, int requestCode, Intent intent, int flags) 
//Retrieve a PendingIntent that will start a new activity, like calling Context.startActivity(Intent).
static PendingIntent    getBroadcast(Context context, int requestCode, Intent intent, int flags) 
//Retrieve a PendingIntent that will perform a broadcast, like calling Context.sendBroadcast().

The Request code is that ID.

In your code, you keep resetting the SAME PendingIntent, instead use a different RequestCode each time.

PendingIntent pIntent = PendingIntent.getActivity(context,uniqueRQCODE, newIntent, 0);

It has to be an integer, i suppose you have a primaryid (itemId) that can identify Alarm A from Alarm B.

You can set up multiple alarms by supplying different request code in pendingIntent.getBroadcast(......)

The approach which I used to setup multiple alarm is that I created a single alarm. I initialized a static integer in alarm setting class which will be incremented each time from my main activity whenever I click on "add alarm" button in my main activity. E.g.

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void addAlarmClick(View v) {
    AlarmActivity.broadcastCode++;
    startActivity(new Intent(this, AlarmActivity.class));
}
}

AlarmActivity.java

public class AlarmActivity extends AppCompatActivity {`
//........
public static int broadcastCode=0;
//........
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this,
                            broadcastCode, myIntent, 0);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!