问题描述:

I HAVE to be missing something, I made a test Application Project for myself and this works perfectly there but when I tried to implement my AlarmManager into my main project's fragment it just won't work. Here's my code:

The Method that is in my fragment:

public void schedule()

{

Long time = new GregorianCalendar().getTimeInMillis()+10*1000;

Intent intent = new Intent(getActivity(), AlarmReceiver.class);

AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, time, 10*1000, PendingIntent.getBroadcast(getActivity(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));

}

and here is my AlarmReceiver.class

public class AlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent)

{

Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();

}

}

And also here are the preparations in my Manifest file:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

<application

... >

<receiver android:name=".AlarmReceiver"/>

What am I doing wrong?

Note: It seems that it doesn't even reach the AlarmReceiver

网友答案:

Your code seems to work. But it the problem is the manifest. the

<receiver android:name=".AlarmReceiver"/>

should be the with the full package name, for example

<receiver android:name="com.example.AlarmReceiver"/>

I've double check it with my app. so you are good to go.

网友答案:

You are using the receiver incorrectly. What you need to do first is to add an action to your receiver's manifest

<receiver android:name=".AlarmReceiver">
<intent-filter>
            <action android:name="com.example.action.ALARM" />
</intent-filter>

Then, construct the intent with that action:

public void schedule() {
Long time = new GregorianCalendar().getTimeInMillis()+10*1000;
Intent intent = new Intent("com.example.action.ALARM");

...

}

and in your receiver:

public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.example.action.ALARM")
  Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}

This should do the trick.

相关阅读:
Top