2014-02-23 39 views
-1

對不起,如果任何這類問題已發佈,我仍然沒有找到我正在尋找的答案。如何創建通知服務?

我的任務很簡單 - 我想創建一個應用程序,在9PM激動地推送通知

這裏是我發現了什麼我現在有 -

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

我放牧,必須有一種服務的顯示通知。我如何創建它?如果我的代碼不對,請隨時重新制作。

非常感謝!

+0

從API 19開始,所有對setRepeating()的調用都將委託給setInexactRepeating(),因此您無法確定它將在晚上9點完全被觸發。我與我的手機在線,這就是爲什麼我不能幫助你的代碼不幸。 – Endzeit

回答

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

+0

非常感謝。 不清楚清單中的「也聲明服務」,我應該如何放置「onHandleIntent」以及如何使用notify()元素。謝謝 – user3053246

+0

裏面通知把你的通知代碼。下面我發佈的鏈接,以通知所有設備 – qwr

+1

@ user3053246使我的答案有點clear.not測試,但認爲它應該工作。更多檢查http://developer.android.com/reference/android/app/AlarmManager.html – qwr