I want to execute two code blocks at pre-defined times. I am using AlarmManager for that purpose. Two separte AlarmManagers and two separate pending intents. I have set 2 alarms to trigger (1st one triggered after 5 seconds, 2nd one after 19 seconds), when i press a button on screen. My problem is both alarms, and as a result both corresponding code blocks are simultaneously triggered at same time after 5 seconds. I changed Ids of both Pending Intents yet i am facing this problem.
Following is my main activity java class code:
public class PerseusAndroid extends Activity implements OnClickListener, OnItemClickListener {
PendingIntent pi,pi2;
AlarmManager amon,amoff;
BroadcastReceiver br,br2;
BluetoothSocket m_btSck;
public static final int idTab2FWD = Menu.FIRST + 1,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.PreseusAndroid);
setup();
setup2();
}
private void setup()
{
br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
if (m_btSck != null )
try {
m_btSck.getOutputStream().write('1');
Toast.makeText(getBaseContext(), "Led is ON.. : )", Toast.LENGTH_LONG).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
registerReceiver(br, new IntentFilter("net.pocketmagic.perseus") );
final int _id2 = (int) System.currentTimeMillis();
pi = PendingIntent.getBroadcast( this,_id2 , new Intent ("net.pocketmagic.perseus"),PendingIntent.FLAG_CANCEL_CURRENT );
amon = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
}
private void setup2()
{
br2 = new BroadcastReceiver() {
@Override
public void onReceive(Context c1, Intent i1) {
if (m_btSck != null )
try {
m_btSck.getOutputStream().write('0');
Toast.makeText(getBaseContext(), "Led is Off.. : )", Toast.LENGTH_LONG).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
registerReceiver(br2, new IntentFilter("net.pocketmagic.perseus") );
final int _id = (int) System.currentTimeMillis();
pi2 = PendingIntent.getBroadcast( this, _id, new Intent("net.pocketmagic.perseus"),PendingIntent.FLAG_ONE_SHOT );
amoff = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
}
@Override
public void onClick(View v) {
int cmdId = v.getId();
if (cmdId == idTab2FWD)
{
amon.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +5000, pi );
//amoff.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +19000, pi2);
}
}
}
}
You are registering both intents/receivers with the same intent/filter. This means it will trigger the other receiver as well. Just make the Intent/IntentFilter specific for each action, i.e instead of "net.pocketmagic.perseus"
use: "net.pocketmagic.perseus.ACTION_1"
and "net.pocketmagic.perseus.ACTION_2"
.