简体   繁体   English

创建客户端服务

[英]Creating a client side service

I have written a client-server application, where the client side is an Android app, and the server side is written in pure java. 我已经编写了一个客户端-服务器应用程序,其中客户端是一个Android应用程序,而服务器端则是用纯Java编写的。

What I would like to do, is create a service on the client app. 我想做的是在客户端应用程序上创建服务。 This service should always listen for messages from the server (obviously on a different thread, not the main - what's the point in doing a service which runs on the main thread anyway?) and be able to send responses, even when the application is in standby or closed (The same way as Whatsapp or Facebook receive messages even when the app is closed). 该服务应始终侦听来自服务器的消息(显然是在不同的线程上,而不是在主线程上–做在主线程上运行的服务的意义何在?)并且即使在应用程序处于运行状态时也能够发送响应待机或关闭状态(即使关闭应用程序,与Whatsapp或Facebook接收消息的方式相同)。

The service will communicate with the Activity by broadcasting intents which the Activity will listen for via a BroadcastReceiver . 服务将通过广播意图与活动进行通信,活动将通过BroadcastReceiver监听这些意图。

What I have done is implemented: 我所做的是实现的:

public class ServerProxy extends Service

public void startClientActionListener() {
    new Thread() {

        public void run() {

            MessageToClient msgTC;

            try {
                while ((msgTC = (MessageToClient) genConnection
                        .getMessage()) != null) {
                    EventReport eventReport = msgTC
                            .doClientAction(serverProxy);
                    Intent i = new Intent(Event.EVENT_ACTION);
                    i.putExtra("eventreport", eventReport);
                    sendBroadcast(i);
                }

            }
      }

which listens for incoming messages from the server. 侦听来自服务器的传入消息。

I also added this to AndroidManifest.xml: 我还将此添加到AndroidManifest.xml中:

        <service            
        android:enabled="true"
        android:name="com.android.services.ServerProxy" >
    </service>  

    <intent-filter>             
        <action android:name="com.android.services.ServerProxy" />                      
    </intent-filter> 

But when I exit the application, it seems the service is also terminated and the connection is closed. 但是,当我退出该应用程序时,该服务似乎也终止了并且连接已关闭。

To sum up, what is the right way to create a service that will listen for messages and awaken/interact with the application activity even if it is in closed/standby state? 综上所述,创建服务来监听消息并唤醒/与应用程序活动进行交互(即使处于关闭/待机状态)的正确方法是什么?

If you kill the process, you kill all activities and services. 如果您终止了该过程,那么您将终止所有活动和服务。 Service is working in background, so you haven't to kill process, just hide your application to background. 服务在后台运行,因此您不必终止进程,只需将应用程序隐藏到后台即可。

Try START_NOT_STICKY in your service. 在您的服务中尝试START_NOT_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM