17

我尝试使用此代码创建通知:

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 文件中声明,没有编译器或运行时错误。

我的第二个问题是,setLatestEventInfoContructornew Notification已被弃用。我可以用什么来代替它?

4

3 回答 3

9

我认为你需要使用

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

代替getService

于 2013-05-10T22:27:09.597 回答
8

您可以使用

Intent switchIntent = new Intent(BROADCAST_ACTION);

而不是使用

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

在这里 BROADCAST_ACTION 是您在清单中定义的操作

<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
        }
}}
于 2015-05-22T09:59:05.163 回答
3

Notification.Builder现在用于构建通知,并且待处理的意图需要PendingIntent.getBroadcast()

于 2013-05-10T22:28:52.117 回答