简体   繁体   中英

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.

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).

The service will communicate with the Activity by broadcasting intents which the Activity will listen for via a 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:

        <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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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