I've been struggling with this for hours. I've also checked the documentation and several topics. I found this code in two topics, both guys said the code was working perfectly, but not on my computer. The first Toast appears, but the second one never. What is wrong?
public class HelloAndroid2 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
}
public final class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
}
If the answer above doesn't work for you then there is another way to not receive any callbacks when
AlarmManager
fires an expired alarm. You simply need to check this one out: by sending the wrongIntent
on instantiation ofPendingIntent
. For example you wanted to receive a callonReceive
on one of your receivers but you instantiated aPendingIntent
viagetActivity
orgetService
, but what you actually meant isgetReceiver
.When creating instance of
PendingIntent
, there are many ways to create it (getService
,getActivity
,getReceiver
,getForegroundService
:if you want
Activity
the receiver of the intent then you:if you want
BroadcastReceiver
the receiver of the intent:if you want a foreground
Service
the receiver of the intent:if you want a
Service
the receiver of the intent:Also, make sure you intents are pointing to the correct class. (e.g. creating intents for Activity, Service etc.). You will not receive any call if you pass wrongfully like this:
I also posted similar answer here.
HTH
I had the same problem until I found that I had put my Broadcast Receiver on a different package, not the general.
Simply changed:
for:
Actually you dont need to specify the action since you use the class
AlarmReceiver.class
in the intent.In your
AndroidManifest.xml
, make sure you have a receiver definition within the<application>
tags, something like:<receiver android:name="AlarmReceiver">
Edit: Ok there are 2 ways to use your broadcast receiver.
1) From the code you have provided,
AlarmReceiver.java
that will contains:and
HelloAndroid2.java
:Like this, you can set your broadcast receiver to work with the
AndroidManifest.xml
and the tag<receiver ...>
2)2nd way. With this way, you can use just 1 file
HelloWorld2.java
:In your activity, create your broadcast receiver and register it.