2013-05-10 13 views
12

との通知を作成します。私はこのコードの通知を作成しようとしましたBroadcastReceiver

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 Notificationコントラクトは廃止されました。私はそれの代わりに何を使うことができますか?あなたが使用することができます

答えて

9

は、私はあなたが

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

の代わりに、あなたが今の通知を構築するためにNotification.Builderを使用getService

+0

大丈夫感謝のためにそのアクション名を使用して、それをキャッチすることができますが、マニフェスト

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

に定義されているアクションですそれ。上記のコードを更新しました。今は何も起こりません... – Cilenco

+1

BroadcastReceiversは一般的に何らかのアクションを行います。あなたの放送受信機が動作するアクションを定義し、そのアクションをマニフェスト&インテントに追加します。詳細はこちら[こちら](http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html) –

3

を使用する必要があると思うし、保留中の意図はPendingIntent.getBroadcast()

6

にする必要がある

Intent switchIntent = new Intent(BROADCAST_ACTION);

代わりに、ここでBROADCAST_ACTIONに

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

を使用しての

は、あなたが

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 
     } 
}} 
関連する問題