如何将Activity传递给服务

时间:2015-06-28 21:06:36

标签: android android-activity service param

如何将活动作为特定服务的参数传递:

这是服务:

每5秒我想要发生这个动作:(对于messanger updte)

        channel_id = intent.getStringExtra("channelID");
        if (MapWithMarkers.channels_map.get(channel_id).getChannel_messages().size()
                > ChatActivity.last_given_size_of_messages) {
            if (activity != null) {

                ((ChatActivity) activity).updateNewMessagesOnScreen(); // THIS MUST ACCEPT ACTIVITY!!!
            }


        }

现在我想从调用服务的活动中调用它:

public void updateNewMessagesOnScreen() {
    List<MessageItem> messages = MapWithMarkers.channels_map.get(channelId).getChannel_messages();
    int max_size = messages.size();

    for (int i = last_given_size_of_messages; i < max_size; i++) {
        if (messages.get(i).getUser_id().equals("me")) {
            adp.add(new ChatMessage(false, messages.get(i).getText()));
        } else {
            adp.add(new ChatMessage(true, messages.get(i).getText()));
        }
    }
    last_given_size_of_messages = max_size;
}

package com.ap2.demo;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.ap2.demo.enumPackage.Constants;

import java.util.Timer;
import java.util.TimerTask;

public class ChatService extends Service {
    private Timer timer = new Timer();
    String channel_id ="";
    Activity activity = null;
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

    @Override
    public void onCreate() {
        // code to execute when the service is first created
        int x = 10;

    }

    @Override
    public void onDestroy() {if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startid) {

        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                channel_id = intent.getStringExtra("channelID");
                // Check if there are updates here and notify if true
                // new ServerSamples().execute(Constants.SERVER_REQUESTS.GET_SERVERS);
                if (MapWithMarkers.channels_map.get(channel_id).getChannel_messages().size()
                        > ChatActivity.last_given_size_of_messages) {
                    if (activity != null) {
                        ((ChatActivity) activity).updateNewMessagesOnScreen();
                    }


                }


            }
        }, 0, 1000);
        return START_STICKY;
    }


    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        ChatService getService() {
            // Return this instance of LocalService so clients can call public methods
            return ChatService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {

        return mBinder;
    }
    /** method for clients */
    public void setActivity (Activity activity, String channel_id) {
        this.activity = activity;
        // Check if there are updates here and notify if true

        if (MapWithMarkers.channels_map.get(channel_id).getChannel_messages().size()
                > ChatActivity.last_given_size_of_messages) {
            if (activity != null) {
                ((ChatActivity) activity).updateNewMessagesOnScreen();
            }
        }
    }

    private void stopService() {
        if (timer != null) timer.cancel();
    }


}

在我的活动中:

 @Override
    protected void onResume() {
        super.onResume();
        // Bind to ChatService
        Intent intent = new Intent(ChatActivity.this, ChatService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;

        }
    }
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
        ChatService.LocalBinder binder = (ChatService.LocalBinder) service;
        chatService = binder.getService();
        chatService.setActivity(ChatActivity.this, channelId);
        mBound = true;

    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};

1 个答案:

答案 0 :(得分:0)

可能最好的解决方案是使用Bound Service

  

绑定服务是客户端 - 服务器接口中的服务器。一个约束   service允许组件(例如活动)绑定到服务,   发送请求,接收响应,甚至执行进程间   通信(IPC)。绑定服务通常仅在其中生存   提供另一个应用程序组件,但不运行   背景无限期。

您也可以send messages through broadcast

  

您使用MessageApi发送消息并将以下项目附加到消息:

     

任意有效负载(可选)唯一标识的路径   消息的操作与数据项不同,它们之间没有同步   掌上电脑和可穿戴应用程序。消息是单向通信   适用于远程过程调用(RPC)的机制,例如   向可穿戴者发送消息以开始活动。