Android使用前台服务

Android使用前台服务和普通服务在代码上的区别也就是一个Notification,代码如下:

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

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.t("MyService").i("onCreate");
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("title");
        builder.setContentText("text");
        builder.setWhen(System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pt = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pt);
        Notification notification = builder.build();
        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.t("MyService").i("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.t("MyService").i("onDestroy");
    }
}

要从前台删除服务,需要调用stopForeground()方法,这个方法需要一个布尔型参数,指示是否删除状态栏通知。这个方法不终止服务。但是,如果你终止了正在运行的前台服务,那么通知也会被删除。


下面谈谈这期间遇到的蛋疼的事,直接上图对比:

before.gif
after.gif

一开始我写完代码运行,一直是图before的效果,检查代码一遍又一遍,也没发现问题出在哪里,就在我几近崩溃的时候,想着是不是因为我没设置小图标,就试着设置了下图标,结果就ok了,之后我又复习了一下Notification的知识,原来不设置小图标Notification根本显示不出来,哎~

builder.setSmallIcon(R.mipmap.ic_launcher);

顺便附上学习Notification时参考过的好文一篇——郭神(郭霖)之《Android通知栏的微技巧》

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.什么是前台服务 前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不允许系统杀死的服务。前台服...
    紫豪阅读 68,026评论 31 130
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,175评论 25 708
  • 原文出处: http://www.androidchina.net/6174.html Notification在...
    木木00阅读 12,389评论 3 32
  • 转载自:http://blog.csdn.net/vipzjyno1/article/details/252480...
    HEXG_阅读 5,915评论 0 2
  • 是真的吗?你我将要永隔。你怎忍心,叫我如何不心痛? 还记得从他手上接下你的时候,我是何等地开心,像个小孩子,手舞足...
    西贝景阅读 360评论 0 1