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 ファイルで宣言されており、コンパイラ エラーや実行時エラーはありません。

私の 2 番目の問題はsetLatestEventInfonew NotificationContructor が非推奨であることです。代わりに何を使用できますか?

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 に答える