English 中文(简体)
英语中的活动与服务交流方式
原标题:Communication Approaches Between Activity and Service in Android

这里的新安乐方案家。 我有一个服务处负责袖珍管理,并作为I/O,我需要在其与活动之间建立沟通渠道。

The current approach is to equip both the Service and Activity with BroadcastReceivers and use them to send command Intents from the Activity to the Service, and to send alert Intents from the Service to the Activity.

我的服务处有可操作的,即:当收到数据时,可操作性向该处发送了新数据意图,然后提醒该处注意:

    @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            if (m_IsRunning == false) {
                m_IsRunning = true;
                (new Thread(new Runnable() {
                    byte[] inputBuffer = new byte[512];
                    public void run() {
                        while (m_IsRunning) {
                            if (m_IsConnected) {
                                try {
                                    m_Nis = m_Socket.getInputStream();
                                    m_Nis.read(inputBuffer, 0, 512);
                                    Intent broadcast = new Intent();
                                    Bundle bun = new Bundle();
                                    bun.putString("ServiceCmd", "ALERT_INCOMING_DATA");
                                    bun.putByteArray("MsgBuffer", inputBuffer);
                                    broadcast.putExtras(bun);
                                    broadcast.setAction(BROADCAST_TO_SERVICE);
                                    sendBroadcast(broadcast);
                                } catch (IOException e) {
                                    // Send fault to activity
                                }
                            }
                        }
                    }
                })).start();
            }
            return START_STICKY;
        }

My approach with the BroadcastReceiver looks like this:

        private BroadcastReceiver serviceReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle bun = intent.getExtras();
                String cmdString = bun.getString("ServiceCmd");

                if (cmdString.equals("CMD_SETHOSTINFO")) {
                    // The activity has requested us to set the host info
                    String hostAddr = bun.getString("HostAddressString");
                    int hostPort = bun.getInt("HostPortNumber");
                    processSetHostInfoCommand(hostAddr, hostPort);
                }
                else if (cmdString.equals("CMD_CONNECT")) {
                    // The activity has requested us to connect
                    if ((m_IsRunning) && (m_IsConnected == false)) {
                        // Attempt to connect
                        processConnectCommand();
                    }
                }
                else if (cmdString.equals("CMD_DISCONNECT")) {
                    // The activity has requested us to disconnect
                    if ((m_IsRunning) && (m_IsConnected == true)) {
                        // Attempt to disconnect
                        processDisconnectCommand();
                    }
                }
                else if (cmdString.equals("CMD_SENDDATA")) {
                    // The activity has requested us to send data
                    if ((m_IsRunning) && (m_IsConnected == true)) {
                        // Attempt to send data
                        byte[] msgBuffer = bun.getByteArray("MsgBuffer");
                        processSendDataCommand(msgBuffer);
                    }
                }
                else if (cmdString.equals("ALERT_INCOMING_DATA")) {
                    // Our TCP receiver thread has received data
                    if (m_IsRunning) {
                        byte[] msgBuffer = bun.getByteArray("MsgBuffer");
                        processIncomingDataAlert(msgBuffer);
                    }
                }
            }
        };

(Those process Whatever() methods in general do the socket management and data transfer.)

Like I said, it seems to work fine, but I m wondering if this isn t a case where using Messages and Handlers wouldn t be more appropriate.

因此,具体问题是:

  1. 在决定何时使用广播电视接收器/分机或操作员/职业时,什么是安康?

  2. 在决定采用哪一种方法时是否有任何交叉考虑?

(安道尔,虽然它是一个非议题,但最后一个问题是:

  1. Is a Service suited to do the kind of socket-based I/O I m trying to do?
最佳回答

www.un.org/spanish/ecosoc 广播意向、意向和操作者之道

广播的意向是一对一的公众/次假想,其中一部分人想让世界了解所发生的事情,但是,如果有人/多少有这么多的听众,或者他们目前是否在运行,则不予以注意。

通常的用意是一对一的设想,其中某一部分要求代表它进行特定处理,但若有能够这样做的特定组成部分,或这些组成部分目前是否正在运行,则不提供护理/知识。

而另一方面,当双方都知道并且正在运行时,手指一对一对一对一对一的同yn。

www.un.org/spanish/ecosoc 以上与您的设想有关的情况

在最简单的执行中,你迫切地需要意图或手稿,你可以直接从可操作的背景中向您提供服务,例如:

MyService.this.processIncomingDataAlert(inputBuffer);

请注意,这将在背景线索上实施这种方法,并将阻碍听众在处理数据时。 让我们看看你所问的可怕考虑。

如果你想揭开笔记本和(或)处理有关国际笔记的数据,你就可以在上创建一名手记员,并使用该密码,从可以操作到另一个可以操作的背信于国际笔迹:

myServiceHandler.post(new Runnable() {
    public void run() {
        MyService.this.processIncomingDataAlert(inputBuffer);
    }
};

请注意,这将导致种族状况,从国际宇宙航行联合会处理可操作的电话(oninnas)到背景阅读器(可更新inputBufffer)到你可能希望制作一份复印件。

当然,现在还出现了在统一调查线上进行处理的问题,这一处理工作与活动是共有的。 因此,如果你的数据处理工作进展缓慢,就会影响贵组织的回应。

If you want to make sure both the background socket listener -and_ the UI thread are responsive, you should process your data on (yet) another thread. You could start a new thread for each Runnable, but that will result in bunch of threads created quickly, and waste system resources. Not to mention that creating separate threads will lead to race conditions between processing multiple chunks of your data, which can make your app logic too complex.

Fortunately, Android offers AsyncTask for such scenarios.

AsyncTask有一组背景线索,在那里,它通过它安排了可移动的床位。 如果你在GingerBread或下台,或者在ICS或更高版本上工作,AsyncTask还将将其编成册,同时只执行一次任务。

rel=“nofollow”>this article for a nice introduction on threads, Handrs and AsyncTask. 请注意,本条显示了亚历亚列克塔克和执行<条码>的示例,但对于你来说,高技能的比照;静态<条码>execute(Runnable)方法将仅对你进行罚款。

www.un.org/spanish/ecosoc 适合您的情况:

这个问题有些直观。 你们需要一个背景来聆听所介绍的议事情况。 但是,你不需要一个服务机构。

如果申请需要进行背景处理,而不需要通过用户调查与用户接触,或者在用户转向另一种应用后继续处理,则服务就是这种情况。

因此,如果你的设想要求你在屏幕上显示你的活动,而且用户积极与之接触,那么你就不需要服务。 你只能从你的活动中开始背景,并使用手把新数据寄给你们或上文所讨论的阿斯恩茨·塔克。

然而,如果你确实需要继续听取用户在结束活动之后的袖珍(你是否应当是一个单独的题目:-)的话,你需要服务处。

The main issue here is the process lifecycle in Android. In order to manage the device resources properly, the OS will kill processes it considers idle. A process is considered idle, if there is no activity or a service running in it. Mere starting a background thread is not enough to let the OS know the process is still busy. So, if you don t have a service, once you activity is closed, from the Android point view, your process is doing nothing, and it can kill it.

希望这一帮助。

问题回答

确实,你不需要使用服务。 如果所有网络都在同一过程中运行,那么,仅仅把网络代码变成一个单一州,而且其活动直接使用方法。 就通知而言,你只能开展某种接口(onData(String data)等)的活动,并在网络类别上登记。 当某项活动消失时,仅对未婚夫妇给予照顾(onStop()。 另一方面,如果网络代码需要运行,而没有识别符号(例如,有不同的数据线),那么就需要使用一种服务。

Messages and intents are actually different: you use handlers.messages to communicate with a particular thread, while intents are actually IPC -- they could be delivered to a different app/process. The benefit of using a broadcast receivers is that Android will create a process to handle the incoming intent if one is not currently running.

Don t 知道这是否是道教,但一般是:

  • if you need to run something without a UI, use a service (scheduled network IO, etc.)
  • if a UI is present, just have it run in a different thead (AscynTask offers a handy way to do this)
  • if you are communicating with your own app (in a single process), use handlers/messages
  • if you need cross-app (process) communication, use intents
  • if you need to handle some async event, and there is a chance that the app to handle it won t be running, use a broadcast receiver. Then you might want to start a service (IntentService does processing in a worker thread) to do the actual work if it takes sometime. Additionally, you may need to acquire a wakelock to keep the device from falling asleep again, while you are performing your work (network IO, etc.)




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签