从GCM Service Android更新用户界面

时间:2015-11-17 20:12:17

标签: android android-layout android-fragments service

我有一个list的片段。我想在每次GCM通知时插入一个新行。

第1部分

我很困惑我应该在哪里附加数组适配器:

listView.setAdapter(user_adapter); //this code
  1. 在我的片段中
  2. in GCM Service
  3. 如果我选择在GCM服务中实现它,我怎样才能获得片段中夸大的布局参考?

    我的代码

    ArrayList<Add_Friend> array_of_friends = new ArrayList<Add_Friend>();
        User_Adapter user_adapter = new User_Adapter(getContext(),1,array_of_friends);
        ListView listView = (ListView)v.findViewById(R.id.list_1);
        listView.setAdapter(user_adapter);
    

    为服务撰写的代码

    public class MyGcmListenerService extends GcmListenerService {
    
    private static final String TAG = "MyGcmListenerService";
    Update_Friend_Req_List update_friend_req_list;
    
    /**
     * Called when message is received.
     *
     * @param from SenderID of the sender.
     * @param data Data bundle containing message data as key/value pairs.
     *             For Set of keys use data.keySet().
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        Log.d(TAG, "From: " + from);
        Log.d(TAG, "Message: " + message);
        Log.d(TAG, "DATA: " + data);
        //Log.d(TAG, "Message: " + message);
        String senders_email = data.getString("senders_email");
    
        if(message.equals("New Friend Req")){
            //Use Array Adapter to make friends list
            //Use a broadcast receiver to update list
            //register_broadcast_update_friend_req();
    
            //Directly update UI
    
        }
    
        if (from.startsWith("/topics/")) {
            // message received from some topic.
        } else {
            // normal downstream message.
        }
    
    
    }
    

1 个答案:

答案 0 :(得分:0)

您可能不希望直接访问布局,但有几种方法可以解决这个问题。我认为最简单的方法是在Fragment中设置一个BroadcastReceiver,您可以注册并取消注册片段的生命周期。在您的服务中,您然后广播可能包含新数据的自定义Intent,最好使用LocalBroadcastManager来保持所有内部广播。这样,您的片段就可以使用接收器监听消息,并且只有在片段处于活动状态时才会收听消息。

如果您确实想要在收到消息时未启动某个视图,则需要在服务中对startActivity执行某些操作。

相关问题