簡體   English   中英

如何在特定時間獲得通知?

[英]How to get notification at a specific time?

我試圖在特定時間發出通知。 AlarmManager使用了AlarmManagerBroadcastReceiver在主要活動中, AlarmManager調用了BroadcastReceiver但是我無法從該類獲取觸發通知。 這在行nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);給我一個錯誤nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); 我不知道該怎么辦。

這是我的代碼

主要活動

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();

    }}`

廣播接收者

`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);

    }

}

使用傳遞的上下文:

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

代替:

nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM