简体   繁体   中英

Android service in background

I have created a webservice and I want to use a android phone as a terminal. The phone has to check for messages on the webservice every now and then.

Is it possible to create a "background task" or service, that checks a specific webservice every now and then? Isn't this the way email is working? Should be possible. If not, how can I create a "push" service, that reaches the android phone?

I have created a simple service, but it only runs for some minutes, and then "stops" talking to the server. Looks like it happens when the screen locks.

I have a class, that extends service. And I override following method.

@Override
public void onStart(Intent intent, int startId) {
    Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
    Log.d(_TAG, "onStart");
    timer.scheduleAtFixedRate( new TimerTask() {
        public void run() {
            Log.d(_TAG, "running task!! Hello :)");
            try {
                sendSMS();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, 0, 60000);
}

Works like a charm, until the display gets locked.

The phone is a HTC Desire S

I'm pretty new to android developement, and don't know the framework therefor.

Regards..

As the other posters have pointed out it would be more optimal for your app to receive intents via a push based approach, so you're not wasting resources constantly polling.

But if you need to poll and/or execute some code at some specified intervals than the Alarm Manager is what you want. You register your app to be invoked at certain points in time, which is when you then fire up your Service to poll for data.

http://developer.android.com/reference/android/app/AlarmManager.html

First you need to decide on Pushing data to device or Pulling it from device. Depending upon your decision implementation changes.

You can create Background Service which will keep polling after every x minutes and pulls your data,

Try this blog post http://www.zubha-labs.com/android-services-101-part-1 to learn more about services and also have source code to actually execute.

Or

Use android C2DM http://code.google.com/android/c2dm/ for Pushing it from your server.

It's entirely possible to create a background Service .

However, if the main purpose of the service is to periodically check the server for new messages, it's much better for battery life to use a push service. Google has one called C2DM , which is currently free.

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