2016-07-21 5 views
0

나는 android chat 앱을 가지고 있으며 taskfragment라는 한 조각에 알림 카운터가있는 대화 목록이 있습니다.서비스에서 활동 gui 변경

알림을 처리하는 chatService 클래스가 있는데, 알림이 채팅 서비스를 통해 들어올 때마다 db를 업데이트하여 특정 작업의 알림 번호를 증가시킵니다.

taskfragment가 열리면 refreshTasks()라는 함수가 호출되어 DB에서 gui를 업데이트합니다.

내 문제는 사용자가 taskfragment에 있고 알림을 받으면 chatservice에서 refreshtasks를 호출해야한다는 것입니다. 어떻게해야합니까?

감사합니다.

답변

1

LocalBroadcastManager을 사용할 수 있습니다.
아이디어는 새로운 메시지가 수신 될 때 서비스에서 방송을 보내

class YourService extends GcmListenerService{ 
@Override 
public void onMessageReceived(String from, Bundle bundle) { 
    ... 
    Intent pushNotification = new Intent("pushNotification"); 
    //put any extra data using Intent.putExtra() method   
    LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 
    ... 
    } 
} 

지금 당신의 조각에 그것을받을 당신의 조각에를받을 수 있습니다 :

class TaskFragment extends Fragment{ 
private BroadcastReceiver mBroadcastReceiver; 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    ... 
     mBroadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (intent.getAction().equals("pushNotification")) { 
       // new push message is received 
       //update UI 
       handlePushNotification(intent); 
      } 
     } 
    }; 
    ... 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    // registering the receiver for new notification 
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mBroadcastReceiver, 
      new IntentFilter("pushNotification")); 
} 

@Override 
protected void onDestroy() { 
    //unregister receiver here 
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mBroadcastReceiver); 
    super.onDestroy(); 
    } 
} 

당신이 gist를 참조하거나 찾을 수 있습니다 그것에 관한 웹 튜토리얼.

+0

큰 건 아니지만 (이) getActivity()로 변경해야합니다. –

+0

지적 해 주셔서 감사합니다. 답변이 업데이트되었습니다. –