How to run a notification when setting off the alarm?

Asked

Viewed 69 times

0

There I have my class MainActivty and ReceberAlarm, the class receberAlarm is the class that must fire the notification, I ask for help.

public class MainActivity extends ActionBarActivity {
static final int NUM_ITEMS = 3;

GPSTracker gps;
public Double latitude;
public Double longitude;
MyAdapter mAdapter;

ViewPager mPager;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_pager);
    setUpPagerAndTabs();

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, 2015);
    calendar.set(Calendar.MONTH, 5);
    calendar.set(Calendar.DAY_OF_MONTH, 22);
    //calendar.set(Calendar.HOUR_OF_DAY,17); //Indicar horas
    //calendar.set(Calendar.MINUTE,35);//Indicar Minutos

    Intent intent = new Intent(MainActivity.this, ReceberAlarm.class);
    PendingIntent pIntent = PendingIntent.getBroadcast(MainActivity.this,0, intent,0);

    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    //Definir o alarme para acontecer no dia determinado                                                                                                     alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pIntent);
}

The class that got the alarm:

public class ReceberAlarm extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      MainActivity m = new MainActivity();
      m.showNotification(); // Activar Notificação
  }
}
  • Gabriel, you cannot/should instill a Activity. For reasons of context variables and so on... What you should do is create a class that creates the notification and uses it by passing the Context as a parameter in both places.

1 answer

0

You can try this way:

In onReceive you trigger the notification.

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.icone)
        .setContentTitle("Título")
        .setContentText("Mensagem");

int mNotificationId = 001;
NotificationManager mNotifyMgr = 
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
  • I don’t know why but you don’t recognize that reserved word... I created a class for notification that receives the context in the constructor and then sets the context for the method that creates the notification

  • What reserved word?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.