首页 > 其他分享 >android 前台保活 service

android 前台保活 service

时间:2023-04-23 10:58:10浏览次数:37  
标签:service 保活 Intent Build import android intent public

引用:https://blog.csdn.net/qq_34195507/article/details/103634396

1.DeskService 前台服务

package com.cpsc.livedemo;

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 androidx.annotation.Nullable;  //原文引用高版本已不可用,已修改
import android.util.Log;


public class DeskService extends Service {

    private static final String TAG = "DaemonService";
    public static final int NOTICE_ID = 100;

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "DaemonService---->onCreate被调用,启动前台service");
        //如果API大于18,需要弹出一个可见通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle("KeepAppAlive");
            builder.setContentText("DaemonService is runing...");
            startForeground(NOTICE_ID, builder.build());
            // 如果觉得常驻通知栏体验不好
            // 可以通过启动CancelNoticeService,将通知移除,oom_adj值不变
            Intent intent = new Intent(this, CancelNoticeService.class);
            startService(intent);
        } else {
            startForeground(NOTICE_ID, new Notification());
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 如果Service被终止
        // 当资源允许情况下,重启service
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 如果Service被杀死,干掉通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mManager.cancel(NOTICE_ID);
        }
        Log.d(TAG, "DaemonService---->onDestroy,前台service被杀死");
        // 重启自己
        Intent intent = new Intent(getApplicationContext(), DeskService.class);
        startService(intent);
    }

}

 

2 移除前台Service通知栏标志

package com.cpsc.livedemo;

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.os.SystemClock;
import androidx.annotation.Nullable;


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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            startForeground(DeskService.NOTICE_ID, builder.build());
            // 开启一条线程,去移除DaemonService弹出的通知
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 延迟1s
                    SystemClock.sleep(1000);
                    // 取消CancelNoticeService的前台
                    stopForeground(true);
                    // 移除DaemonService弹出的通知
                    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    manager.cancel(DeskService.NOTICE_ID);
                    // 任务完成,终止自己
                    stopSelf();
                }
            }).start();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

 

3  注册服务到AndroidManifest.xml

<service
    android:name=".DeskService"
    android:enabled="true"
    android:exported="true"
    android:process=":daemon_service" />


<service
    android:name=".CancelNoticeService"
    android:enabled="true"
    android:exported="true"
    android:process=":service" />

4  启动服务

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_child_light_sensor);
      //启动服务
        startService(new Intent(this, DeskService.class));


    }

 

标签:service,保活,Intent,Build,import,android,intent,public
From: https://www.cnblogs.com/cwxkurenoki/p/17345820.html

相关文章

  • Appium-Server-GUI、Appium-Inspector、Android (SDK tools package)commandlinetools
    公众号回复中增加了最新版Appium和安卓SDK下载链接Appium-Server-GUI-mac-1.22.3-4.dmgAppium-Server-GUI-windows-1.22.3-4Appium-Inspector-mac-2023.4.1Appium-Inspector-windows-2023.4.1(SDKtoolspackage)commandlinetools-mac-9477386_latest(SDKtoolspackage)co......
  • golang net/rpc inject data to service function
    在golang中,net/rpc库比较牛,只需要写函数,然后使用现成的ServerCodec就可以完成rpc服务了。但是有个问题,service函数的参数都是来自客户端的,如果服务器想为某个特殊的函数注入一些配置或状态参数,就不好弄了。解决方案:修改service函数,比如原来的参数是FuncArgs结构体,现在改成t......
  • ReactNative 打包发布 Android 应用
    一、创建应用签名1、在AndroidStudio菜单栏中,依次点击Build >GenerateSignedBundle/APK 2、在Generate SignedBundleorAPK对话框中,选择APK,点击Next按钮 3、在Keystorepath字段下,点击Createnew按钮 4、在NewKeyStore窗口中,点击右侧文件......
  • 读书笔记 - 《Monolith to Microservices》
    如果你的产品目前是B/S或者C/S架构,想要考虑重构成微服务,这本书绝对是一个很好的参考,作者通过自己的实践经历,详述了以下几个方面:不要因为别人都做微服务,你就想要把自己的系统转成微服务,首先需要分析自己系统碰到的问题,找到最适合的解决办法,微服务不是万能的,不能解决所有问题考虑......
  • com.android.tools.r8.internal.Jc: Absent Code attribute in method that is no
    AbsentCodeattributeinmethodthatisnotnativeorabstract背景:在导入framework.jar时,报错。一般这种问题就是对应的jar包有问题。解决方式:将implementationfiles('libs\\framework.jar')修改为compileOnlyfiles('libs\\framework.jar')作者:黄志成_链接:https://ww......
  • Android Studio Gradle Download 慢/卡问题解决
    build.gradlebuildscript{repositories{//jcenter()//jcenter(){url'http://jcenter.bintray.com/'}maven{url'http://maven.aliyun.com/nexus/content/groups/public/'}maven{url"https://jitpac......
  • Android Studio类名冲突快捷键
    AndroidStudio类名搜索快捷键Ctrl+N。1.遇到问题2.解决问题直接在jar包里面把冲突的类删掉。......
  • android 打包版本说明
    个人经验之谈,不对之处,也不用留言,我的知识都是实战中积累,别给我整那么多虚的理论#编译应用程序所采用的版本#人话:你的安卓包包含什么样的字节码,不做兼容,可能会崩溃PROP_COMPILE_SDK_VERSION=31#应用程序对系统的要求最低21#人话:你的应用对设备的最低要求PROP_MIN_SDK_VERSION=......
  • android系统adb对时//京鸿通信/www.kyohoon.com/15507589165
    目录1、远程连接设备2、设置地区3、设置对时服务器4、重启设备5、查看对时服务器是否设置成功1、远程连接设备adbconnectxxx.xxx.xxx.xxx2、设置地区adbshellsetproppersist.sys.timezoneAsia/Shanghai3、设置对时服务器adbshellsettingsputglobalntp_server172.16.......
  • Android性能优化—StrictMode的使用
    原文地址zhuanlan.zhihu.com残枫cps原文地址juejin.cnStrictMode是Android开发过程中一个必不可缺的性能检测工具,他能帮助开发检测出一些不合理的代码块。策略分类StrictMode分为线程策略(ThreadPolicy)和虚拟机策略(VmPolicy)线程策略(ThreadPolicy)线程策略主要包含了以......