美文网首页
Android使用前台服务

Android使用前台服务

作者: CalvinNing | 来源:发表于2016-08-10 16:21 被阅读151次

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通知栏的微技巧》

相关文章

  • Android使用前台服务

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

  • Android 服务的限制

    服务的分类 Google官网将Android服务分为了三种,前台服务,后台服务和绑定服务: 前台 前台服务执行一些...

  • Android启动Service系统适配演进

    Android8.0 后台服务限制:处于空闲状态时,应用可以使用的后台服务存在限制。 这些限制不适用于前台服务,因...

  • 【Android】Service前台服务的使用

    1.什么是前台服务 前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不允许系统杀死的服务。前台服...

  • Android 前台服务

    https://www.cnblogs.com/renhui/p/8575299.html

  • Media projections require a fore

    Android Q (Android10) 中,MediaProjection必须在前台服务中进行参考链接:htt...

  • Android 8.0 后台Service限制

    Android O 后台启动Service崩溃问题 在 Android 8.0 (API26)之前,创建前台服务的...

  • IntentService 源码阅读笔记

    Service 是 Android 四大组件之一,默默的工作在后台(当然也有前台服务),它的使用我这里就先不做详细...

  • android熄屏或退回后台持续定位方法

    一、根据android8.0的官方api说明 如果需要高频率定位,且用户正在与其他应用交互,需要使用前台服务,具体...

  • 开启前台服务

    我就是想做个笔记而已,给自己看看而已 第一步:面向Android 9(API级别28)或更高版本并使用前台服务的应...

网友评论

      本文标题:Android使用前台服务

      本文链接:https://www.haomeiwen.com/subject/mvrjsttx.html