2016-09-07 5 views
1

私のすべてのビューには、ユーザーに通知があると赤いドットが付いたアイコンがあるので、常時(数分ごとに)ポーリングを行い、通知があるかどうかを確認するクラスを作成しました。 @Subscrtibeがトリガーされることはありません。私が考えたことの一つは、HomeActivityが登録される前に私が投稿を開始することですが、それは問題であるとは思っていませんでした。ユーザーがログインに成功するとOttos busを '通知ポーリング'に使用

public class NotificationUtils { 

    private static Timer timer; 

    private static final int MINUTES = 1000 * 60; 
    private static Context applicationContext; 

    public static void startTask(Context context){ 
     checkNotifications(); 
     applicationContext = context; 
     timer = new Timer(); 
     timer.schedule(task, 0L, MINUTES); 
    } 

    public static void killTask(){ 
     timer.cancel(); 
     timer.purge(); 
    } 

    static TimerTask task = new TimerTask() { 
     @Override 
     public void run() { 
      checkNotifications(); 
     } 
    }; 

    private static void checkNotifications(){ 
     RestInterface service = RestService.getRequestInstance(applicationContext); 
     Call<Boolean> call = service.hasNotificatrions(SessionUser.getInstance().getUser().getId()); 
     call.enqueue(new Callback<Boolean>() { 
      @Override 
      public void onResponse(Call<Boolean> call, Response<Boolean> response) { 
       sendNotificationImage(response.body()); 
      } 

      @Override 
      public void onFailure(Call<Boolean> call, Throwable t) { 
       Log.w("TimerTask", "Failed"); 
      } 
     }); 
    } 

    private static void sendNotificationImage(boolean hasUnreadNotifications){ 
     if(hasUnreadNotifications) { 
      BusProvider.getInstance().post(R.drawable.notification_alert_icon); 
     } else { 
      BusProvider.getInstance().post(R.drawable.notification_icon); 
     } 
    } 
} 

が、私はポーリングを開始... ​​

はその後、私のHomeActivityは、私が追加..

public class HomeActivity extends AppCompatActivity { 
    .... 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_home); 
     BusProvider.getInstance().register(this); 
    } 
    .... 
    @Subscribe 
    public void setNotification(int imageResource){ 
     notificationButton.setImageResource(imageResource); 
     Log.w("HomeActivity", "Setting resource"); 
    } 
} 

編集クラスを登録し、サブスクライブBusProviderクラス

public final class BusProvider { 
    private static final Bus bus = new Bus(); 

    public static Bus getInstance(){ 
     return bus; 
    } 

    private BusProvider(){} 
} 

答えて

2

イベントクラスとしてJava primitive typesを使用しないでください。

public class DisplayNotification { 
    private int resourceId 

    public DisplayNotification(int resourceId){ 
     this.resourceId = resourceId; 
    } 

    public int getResourceId(){ 
     return this.resourceId; 
    } 
} 

変更あなたの関数のシグネチャが

@Subscribe 
public void setNotification(DisplayNotification event){...} 

すると、このようにそれを投稿:あなたは使用することができます

BusProvider.getInstance().post(new DisplayNotification (R.drawable.notification_icon)); 
+0

は、私はそれを逃した信じることができません!ありがとう、今すぐうまくいく! – John