2013-05-10 129 views
12

创建通知我试图创建本守则一个通知:与广播接收器

private void setNotificationAlarm(Context context) 
{ 
    Intent intent = new Intent(getApplicationContext() , MyNotification.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); 

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 , pendingIntent); 
    Log.d("ME", "Alarm started"); 
} 

public class MyNotification extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     Log.d("ME", "Notification started"); 

     NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(context) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("My notification") 
      .setContentText("Hello World!"); 

     NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     mNotificationManager.notify(1, mBuilder.build()); 
    } 
} 

在这里,我Mainfest声明:

<receiver 
    android:name=".MyNotification" 
    android:enabled="true" 
    android:exported="false" > 
</receiver> 

我现在的问题是,所产生的报警,但通知不显示。 BroadcastReceiver在mainfest文件中声明,并且没有编译器或运行时错误。

我的第二个问题是不建议使用setLatestEventInfonew Notification构造函数。我可以用什么来代替它?

回答

9

我认为你需要使用

PendingIntent.getBroadcast (Context context, int requestCode, Intent intent, int flags) 

,而不是getService

+0

好感谢接住那。我上面更新了我的代码。目前没有任何事情发生...... – Cilenco 2013-05-10 22:44:09

+1

BroadcastReceivers通常会采取一些行动。定义您的广播接收器将使用的操作,然后将该操作添加到清单中并且用于该意图。更多细节[here](http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html) – 2013-05-10 22:51:01

3

您使用Notification.Builder现在打造的通知和未决的意图必须PendingIntent.getBroadcast()

6

可以使用

Intent switchIntent = new Intent(BROADCAST_ACTION);

,而不是在这里BROADCAST_ACTION使用

Intent intent = new Intent(getApplicationContext() , MyNotification.class);

是,你是在明显

<receiver android:name=".MyNotification " android:enabled="true" > 
    <intent-filter> 
     <action android:name="your package.ANY_NAME" /> 
    </intent-filter> 
</receiver> 

定义动作,你可以通过使用操作名称

public class MyNotification extends BroadcastReceiver { 
@Override 
public void onReceive(Context context, Intent intent) { 
    String act = "your package.ANY_NAME"; 
     if(intent.getAction().equals(act)){ 

      //your code here 
     } 
}}