I asked a question similar to this yesterday but have changed my code a fair bit and have a different issue now.
I have a toggle button that sets an alarm manager with a pending intent that should trigger after 5 seconds. I have it on a one shot setting, so i want the message to appear once (as later I will be implementing this for a date value).
I get no errors with this code, but I cant seem to trigger my intent that then shows my toast message.
Here’s how I have defined the activity of the ‘DateAlarm’ class in the xml:
<activity
android:name=".DateAlarm"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.example.flybase2.DateAlarm" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Heres my my toggle button onClick method for my toggle button with the alarm manager:
case (R.id.toggleButton1):
Integer dobMonth = setDate.getMonth();
Integer dobYear = setDate.getYear();
Integer dobDate = setDate.getDayOfMonth();
Date set;
set = new Date(dobYear - 1900, dobMonth, dobDate);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, DateAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + (5 * 1000), pendingIntent);
break;
And my final ‘DateAlarm’ class that holds the action of the intent.
package com.example.flybase2;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;
public class DateAlarm extends Activity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(context, "Appointment is today", Toast.LENGTH_LONG).show();
}
}
You have two problems:
You are using
PendingIntent.getService()instead ofPendingIntent.getActivity()SinceDateAlarmextendsActivity, you wantPendingIntent.getActivity().In
DateAlarmyour context variable is null. In onCreate() you should initialize it. Also note that sinceActivityextendsContext, this variable isn’t needed. However if you do want to use that variable do:or