A short introduction as I can:
I have a MainActivity
that implements SomeInterface
, a headless state Fragment called HeadlessFragment
.
HeadlessFragment
is setting an alarm (with compliance to API 18) on the onAttach
method:
Fragment Code
----------------
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (SomeInterface) activity; //HERE IT WORKS!!!
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SomeInterface");
}
//create the Intent for MyBroadCast
mIntent= new Intent(activity, MyBroadCast.class);
mPendingIntent = PendingIntent.getBroadcast(activity, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Set up the Alarm
mAlarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
mAlarmManager.cancel(mPendingIntent );
mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, 10000, mPendingIntent );
}
Now I would expect this activity
variable to pass through as it is to MyBroadCast
, so I implemented MyBroadCast's onReceive
as the following:
BroadCast Code
-----------------
public void onReceive(Context c, Intent indent) {
mContext = c;
try {
// HERE IT DOESN'T WORK - ClassCastException is thrown
SomeInterface callback = (SomeInterface) c;
callback.SomeInterfaceMethod(s);
} catch (ClassCastException e) {
throw new ClassCastException(c.toString()
+ " must implement SomeInterface");
}
}
Unfortunately, it isn't working, as I can't make this cast, and apparently something goes wrong with the context either in the PendingIntent
or the Alarm mechanism, but I have no clue how to investigate further. Does someone here have particular/important insights regarding this issue, before I'm going to change completely my design?
Of course I did my share of reading by going through the entries of Fragments, Intents, Broadcastreceivers in aspect of the context in developer.android API documentation, but couldn't find something of interest.