Android Service学习(三)

文/大大大大峰哥

概述

现在我们使用服务的时候,有时候会遇到Android内存不足的情况,这个时候很有可能Service就被进行了内存回收了,如果我们希望我们的Service一直存在,就需要运用到前台服务的技术。使用该方法的APP比如:假装情侣,墨迹天气等等。

前台服务与普通服务最大的区别就是前台服务需要有一个通知信息栏也就是Notification。

代码

package com.example.demo5;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;

/**
 * Created by TangZhiFeng on 2016/12/26.
 */

public class ProService extends Service {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onCreate() {
        NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification=new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Title")
                .setContentText("ProService in Run")
                .build();
        notificationManager.notify(1,notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

上一篇Android Service学习(二)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容