Android:保持服务运行,在应用关闭时停止(从应用托盘中移除)
创始人
2024-10-13 09:00:55
0

要保持Android服务在应用关闭时继续运行,并从应用托盘中移除,你可以按照以下步骤进行操作:

  1. 创建一个Service类,继承自android.app.Service,并重写onStartCommand方法。在onStartCommand方法中返回START_STICKY,以确保服务在被系统杀死后可以重新启动。
public class MyService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 在此执行你的服务逻辑
        
        // 返回START_STICKY以确保服务在被系统杀死后可以重新启动
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
  1. 在 AndroidManifest.xml 文件中声明你的服务。

  1. 在你的应用关闭时(如在MainActivity的onDestroy方法中),通过startService方法启动你的服务。
@Override
protected void onDestroy() {
    super.onDestroy();
    Intent serviceIntent = new Intent(this, MyService.class);
    startService(serviceIntent);
}
  1. 使用NotificationManager将你的应用从应用托盘中移除。
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

这样,即使你的应用在后台被系统杀死,你的服务仍然会继续运行,并且应用图标会从应用托盘中移除。

相关内容

热门资讯

解密关于!aapoker透视脚... 解密关于!aapoker透视脚本入口,wepoker有什么规律,插件教程(有挂透视)1、点击下载安装...
今日科普!wpk辅助软件,hh... 今日科普!wpk辅助软件,hhpoker有没有作弊辅助,系统教程(有挂攻略)这是由厦门游乐互动科技有...
揭秘一下!wepoker辅助脚... 揭秘一下!wepoker辅助脚本,hhpoker底牌透视脚本,解密教程(有挂教程);人气非常高,ai...
专业讨论!hhpoker的辅助... 专业讨论!hhpoker的辅助是真的吗,hhpoker免费透视脚本,黑科技教程(有挂技巧)是由北京得...
科普分享!wepoker安装教... 科普分享!wepoker安装教程,德州机器人代打脚本,黑科技教程(有挂透视);小薇(透视辅助)致您一...
实测揭晓!wepoker透视苹... 实测揭晓!wepoker透视苹果系统,wepoker怎么设置盖牌,详细教程(有挂教程)1、玩家可以在...
攻略讲解!聚星ai辅助工具收费... 攻略讲解!聚星ai辅助工具收费多少,sohoopoker辅助,技巧教程(有挂神器);支持多人共享记分...
一分钟揭秘!aa poker辅... 这是一款非常优秀的wepoker私人定制透视 ia辅助检测软件,能够让你了解到wepoker私人定制...
2分钟细说!wepoker游戏... 2分钟细说!wepoker游戏的安装教程,wepoker透视脚本,插件教程(有挂辅助);wepoke...
推荐十款!aapoker怎么选... 推荐十款!aapoker怎么选牌,we-poker辅助,教你攻略(有挂技巧)是一款可以让一直输的玩家...