Create a background service in Android

Resume

While developing Android applications, sometimes we expect our app to have a background service for sending and handling data. We expect this service will not be kill after our main activity has been killed. This passage will lead you to create such a service.


AndroidManifest.xml

First of all, just like we should do for Activity, we also need to add our service to our AndroidManifest.xml. So that Android can figure out we have added a service and handle our service.

Add the following codes to your AndroidManifest.xml.

<service
            android:name=".BgService"
            android:exported="false" />

Attention: I found that the answer here from stack overflow is not correct.
According to the official document, android:isolatedProcess means the service will run under a special process that is isolated from the rest of the system. So that it’s impossible to send notifications.


Service

We should create our service which extends Service like this:

public class BgService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        final Context bgService = this;

        Thread thread = new Thread() {
            public void run() {
                while (true) {
                    Notification notification = new NotificationCompat
                            .Builder(bgService)
                            .setTicker("Ticker")
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setContentTitle("Title")
                            .setContentText("Text")
                            .setAutoCancel(true)
                            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                            .build();

                    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    notificationManager.notify(0, notification);

                    try {
                        this.sleep(5000);
                    } catch (InterruptedException e) {
                        Log.d("Interrupted", e.getMessage());
                    }
                }
            }
        };

        thread.start();

        return START_STICKY; //START_STICKY means our service should not be killed after our main activity has quitted.
    }
}

The code above illustrates that we have to override public IBinder onBind(Intent intent) while creating our own service.

Moreover, public int onStartCommand(Intent intent, int flags, int startId) is the first function to be called after our service has been created. So we put our implementations in this function.

Finally, return START_STICKY means our service should keep alive even if our activity has been killed. (If our service’s process is killed, later the system will try to re-create the service)

Here’s the description of START_STICKY from official document.

START_STICKY

int START_STICKY

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Constant Value: 1 (0x00000001)

Start our service

Finally, we can start our service by calling startService(Intent) like:

    Intent myBgService = new Intent(this, BgService.class);
    startService(myBgService);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值