2013-07-11 78 views
2

我已經構建了一個簡單的應用程序,可以在單擊按鈕時顯示通知。如何顯示編程通知?已編程的Android通知

,我調用的代碼是:

Notification.Builder builder = new Notification.Builder(this) 
    .setTicker("Notifica") 
    .setSmallIcon(android.R.drawable.stat_notify_chat) 
    .setContentTitle("Notifica") 
    .setContentText("Hai una notifica!") 
    .setAutoCancel(true) 
    .setContentIntent(PendingIntent.getActivity(this, 0, 
      new Intent(this, MainActivity.class) 
        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0)); 
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    nm.notify("interstitial_tag", 1, builder.build()); 
+0

似乎你需要'AlarmManager' – gunar

+0

你需要一個報警管理器來做到這一點, –

回答

4

您可以捆綁使用AlarmManagerBroadcastReceiver

首先,您必須創建掛起的意圖,並在某處註冊AlarmManager.set。 然後創建您的廣播接收器並接收該意圖。

更新:這是我承諾的代碼。

首先您需要創建廣播接收器。

public class NotifyHandlerReceiver extends BroadcastReceiver { 

    public static final String ACTION = "me.pepyakin.defferednotify.action.NOTIFY"; 

    public void onReceive(Context context, Intent intent) { 
     if (ACTION.equals(intent.getAction())) { 
      Notification.Builder builder = new Notification.Builder(context) 
       .setTicker("Notifica") 
       .setSmallIcon(android.R.drawable.stat_notify_chat) 
       .setContentTitle("Notifica") 
       .setContentText("Hai una notifica!") 
       .setAutoCancel(true) 
       .setContentIntent(PendingIntent.getActivity(context, 0, 
         new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0)); 

      NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      nm.notify("interstitial_tag", 1, builder.build()); 
     } 
    } 
} 

這是您的廣播接收器,可以處理通知請求。因爲它可以工作,你必須在你的AndroidManifest.xml註冊。如果您不這樣做,Android將無法處理您的通知請求。

只需將<receiver/>聲明添加到您的<application/>標記中即可。

<receiver android:name=".NotifyHandlerReceiver"> 
     <intent-filter> 
      <action android:name="me.pepyakin.defferednotify.action.NOTIFY" /> 
     </intent-filter> 
    </receiver> 

拿一張紙條,那動作名稱完全一樣的NotifyHandlerReceiver.ACTION定義。

然後你可以使用此代碼

public static final int REQUEST_CODE_NOTIFY = 1; 

public void scheduleNotification(long delayTimeMs) { 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    long currentTimeMs = SystemClock.elapsedRealtime(); 

    PendingIntent pendingNotifyIntent = PendingIntent.getBroadcast(
      this, 
      REQUEST_CODE_NOTIFY, 
      new Intent(NotifyHandlerReceiver.ACTION), 
      PendingIntent.FLAG_UPDATE_CURRENT); 
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, currentTimeMs + delayTimeMs, pendingNotifyIntent); 
} 

從活動啓動延遲在delayTimeMs量毫秒的通知。

+0

是的,只需一秒鐘。 – pepyakin

+0

非常感謝! :) – user2520969

+0

在這裏你走,代碼如我所承諾的。 – pepyakin