如何创建通知服务?

时间:2014-02-23 20:35:02

标签: java android

很抱歉,如果此类问题已经发布,我仍然没有找到我正在寻找的答案。

我的任务很简单 - 我想在晚上9点创建一个强烈推送通知的应用。

这是我发现的和我现在拥有的东西 -

    Intent intent = new Intent();
    AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 6);
    cal.set(Calendar.HOUR, 9);
    cal.set(Calendar.AM_PM, Calendar.PM);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60*24 , pIntent);
    Notification noti = new Notification.Builder(this)
            .setTicker("Ticker Title")
            .setContentTitle("Content Title")
            .setContentText("Notification content.")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent).getNotification();
    noti.flags=Notification.FLAG_AUTO_CANCEL;
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, noti);

我必须有一种服务才能显示通知。我该如何创建它?如果我的代码错了,请随意重新编写。

提前多多感谢!!

1 个答案:

答案 0 :(得分:1)

内部清单

<service android:enabled="true" android:name=".NotifyIntentService" />

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

内部活动

    Intent intent = new Intent(this, AlarmReciever.class);
    AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 6);
    cal.set(Calendar.HOUR, 9);
    cal.set(Calendar.AM_PM, Calendar.PM); 
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
    AlarmManager.INTERVAL_DAY, pIntent);

在主项目中

   public class AlarmReciever extends BroadcastReceiver
    {
             @Override
                public void onReceive(Context context, Intent intent)
                {
                     Intent serviceIntent = new Intent(context,
                             NotifyIntentService.class); 
                       startService(serviceIntent);
                 }

    }

意向服务

public class NotifyIntentService extends IntentService
{


    @Override
    protected void onHandleIntent(Intent intent) {
         //your notification code
         //notify();

    }
}

notification in all device