开发者

android service running on a separate thread

开发者 https://www.devze.com 2023-01-24 01:11 出处:网络
I have an application that starts on boot using a broadcast receiver, also I have an activity and a process, because the service must run always on the background I am starting the service on it\'s ow

I have an application that starts on boot using a broadcast receiver, also I have an activity and a process, because the service must run always on the background I am starting the service on it's own process using the android:process manifest tag.

The ui is only for presentational needs and I would like the user to be able to run the service even if the activity is not active.

I am starting the service using this extra parameter:

intent.putExtra(Intent.EXTRA_DONT_KILL_APP, true);

the problem is that when I press the back button or the h开发者_JAVA技巧ome button the activity's on destroy method is called and the service although seems its running (it appears on the task manager) its not behaving as supposed, it should connect to the net and send some data but every X time using an timer task but the task never fires so the data are never send.


because the service must run always on the background

Please don't do that. For starters, it is impossible, since Android will kill you off, and users will kill you off. Considering how much RAM you are wasting with your current implementation, both will attempt to kill you off much more quickly.

I am starting the service on it's own process using the android:process manifest tag.

Please don't do that either. You are wasting RAM to no benefit. You do not need a separate process for this service.

I am starting the service using this extra parameter:

That parameter does not do what you think it does. It is not used with starting services.

it should connect to the net and send some data but every X time using an timer task but the task never fires so the data are never send.

Step #1: Get rid of your existing service.

Step #2: Use AlarmManager and a WakefulIntentService. Schedule an alarm (perhaps using your boot-time receiver) to be invoked "every X time". Have the WakefulIntentService "connect to the net and send some data".


I fully agree with CommonsWare's answer. But, if you really want to bother users with yet-another-useless-service-which-sits-in-the-background-just-eating-memory you could use the following:

In your activity:

Intent serviceIntent = new Intent(this, UpdateService.class);
serviceIntent.setAction(Intent.ACTION_MAIN);
startService(serviceIntent);

In your service:

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        .. do something here
    }
    return Service.START_STICKY;
}

Again, please DO NOT do this just to execute some action periodically. PLEASE use the AlarmManager!

0

精彩评论

暂无评论...
验证码 换一张
取 消