如何在特定时间获得通知?

时间:2014-02-20 11:29:24

标签: android android-notifications android-alarms

我试图在特定时间点火。我正在使用AlarmManagerBroadcastReceiver。在主要活动AlarmManager中调用BroadcastReceiver但我无法从该类中获取通知。它给了我一个错误 nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); 我不知道该怎么做。

这是我的代码

MainActivity

public class MainActivity extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
            long current_time=System.currentTimeMillis();
            Calendar time9=Calendar.getInstance();
            time9.set(Calendar.HOUR_OF_DAY,16);
            time9.set(Calendar.MINUTE,30);
            time9.set(Calendar.SECOND,0);
            Intent intent=new Intent(MainActivity.this,ScheduledReciever.class);
            PendingIntent pintent=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            long interval = 60 * 1000; //
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,time9.getTimeInMillis(), interval, pintent);
            finish();

    }}`

BroadcastReciever

`public class ScheduledReciever extends BroadcastReceiver {
    static final int uniqueId=1234;
    NotificationManager nm;


    @SuppressWarnings("deprecation")
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        String body="i hope this works";
        String title="trying";
        Intent it=new Intent(context,SecondActivity.class);
        PendingIntent pit=PendingIntent.getActivity(context, 0, it,0);
        Notification n=new Notification(R.drawable.att,body,System.currentTimeMillis());
        n.setLatestEventInfo(context, title, body, pit);
        n.defaults=Notification.DEFAULT_ALL;
        nm.notify(uniqueId, n);

    }

}

1 个答案:

答案 0 :(得分:0)

使用传递的上下文:

nm=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

而不是:

nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);