前台服务不持续运行

2024-05-02

在我的应用程序中,我使用必须不断运行的前台服务。有时前台服务会停止。 在什么情况下操作系统会终止我的服务(即使有足够的内存、电池已充满、手机正在充电也会发生)?

到目前为止,我的代码是这样的:

public class ServiceTest extends Service {

    public static Thread serverThread = null;
    public Context context = this;

    public ServiceTest(Context context) {
        super();
        this.context = context;
    }

    public ServiceTest() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        if (this.serverThread == null) {
            this.serverThread = new Thread(new ThreadTest());
            this.serverThread.start();
        }

        return START_STICKY;
    }

    private class ThreadTest implements Runnable {

        @Override
        public void run() {
            Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle("Notification title")
                .setContentText("Notification text")
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .setSmallIcon(R.drawable.android)
                .setOngoing(true).build();

                startForeground(101, notification);

                while(true){
                    //work to do
                }
        }


    }

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

}

没有一个...Many problems在你的代码中......你可能会得到“0错误”,因为它在语法上是正确的,但它是androidicaly错了,你的basics很穷,读书android documentation and implementation很穷。 Android从来不会运行非常糟糕的东西......

问题:1

您是否知道按照惯例您应该获得一项服务override onCreate, onStartCommand, onBind, onDestroy方法....?

我在那里没有看到 onDestroy...!!

问题:2

你知道如何通知...?你的onStartCommand实施再次毫无意义。

保持为空只需返回 START_STICKY

问题:3

您希望如何在后台执行限制下运行它......?首先通过在中进行通知来通知androidoncreate仅且与startforeground如果需要的话...

我在那里看不到它......你试图这样做onstartcommand再说一遍,它非常糟糕......

好吧...看看下面的工作代码:

public class RunnerService extends Service
{
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
NotificationChannel notificationChannel;
String NOTIFICATION_CHANNEL_ID = "1";

public RunnerService() { }

@Override
public void onCreate()
{
    super.onCreate();

    Log.d("RUNNER : ", "OnCreate... \n");

    Bitmap IconLg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);

    mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this, null);
    mBuilder.setContentTitle("My App")
            .setContentText("Always running...")
            .setTicker("Always running...")
            .setSmallIcon(R.drawable.ic_menu_slideshow)
            .setLargeIcon(IconLg)
            .setPriority(Notification.PRIORITY_HIGH)
            .setVibrate(new long[] {1000})
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setOngoing(true)
            .setAutoCancel(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{1000});
        notificationChannel.enableVibration(true);
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        mNotifyManager.createNotificationChannel(notificationChannel);

        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        startForeground(1, mBuilder.build());
    }
    else
    {
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotifyManager.notify(1, mBuilder.build());
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.d("RUNNER : ", "\nPERFORMING....");

    return START_STICKY;
}

@Override
public void onDestroy()
{
    Log.d("RUNNER : ", "\nDestroyed....");
    Log.d("RUNNER : ", "\nWill be created again automaticcaly....");
    super.onDestroy();
}


@Override
public IBinder onBind(Intent intent)
{
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("NOT_YET_IMPLEMENTED");
}
}

如何检查....???

从最近使用的列表中删除该应用程序,您应该在日志中看到“Performing” 消息中logcat...

在什么情况下它会停止...?

它永远不会停止(直到下次启动..!!)...是的,当用户强制停止应用程序时它会停止。而且很少有系统发现它的资源非常低......这是一种非常罕见的情况,因为 android 随着时间的推移已经有了很大的改进......

怎么开始呢....????

无论它来自哪里mainactivity或来自receiver或来自任何class :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            context.startForegroundService(new Intent(context, RunnerService.class));

        }
        else
        {
            context.startService(new Intent(context, RunnerService.class));

        }

如何检查服务是否启动......?

根本不...即使您启动服务多少次...如果它已经在运行...那么它不会再次启动...如果没有运行那么...将开始它...!!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

前台服务不持续运行 的相关文章

随机推荐

  • x 或 y:可接受的习语,还是混淆?

    我必须从可能为 None 的变量中提取值 并考虑一些默认值 我首先写了这段代码 if self maxTiles is None maxX maxY 2 2 else maxX maxY self maxTiles 然后我意识到我可以将其缩
  • 如何以编程方式重新启动 Windows 资源管理器进程

    我正在开发 Windows shell 扩展 不幸的是 在更改 DLL 时 我必须重新启动 Windows 资源管理器 因为它将 DLL 保留在内存中 我从 Dino Esposito 找到了这个程序 但它对我不起作用 void SHShe
  • 如何替换 iOS 6 上 UIWebView 键盘下工具栏上的按钮?

    如何替换工具栏上的按钮UIWebViewiOS 6 上有键盘吗 以下代码在 iOS 5 1 上运行良好 但在 iOS 6 上不起作用 UIWindow keyboardWindow nil for UIWindow testWindow i
  • 获取类中的字段数

    有没有办法获取一个类的字段数量 struct Base char a int b struct Derived Base std string c static assert num fields value 2 static assert
  • JavaScript 日期 + 7 天

    这个脚本有什么问题 当我将时钟设置为 29 04 2011 时 它会添加2011年4月36日在星期输入 但正确的日期应该是6 5 2011 var d new Date var curr date d getDate var tomo da
  • 第 n 行到最后一行的总和

    我想在电子表格顶部创建一个 TOTAL 行 在此行中 每个单元格应为 TOTAL 行下方列中的值的总和 例如 如果总行数是第 1 行 则单元格 A1 应该是 A2 到 A 列最后一行的总和 电子表格中的行数会随着时间的推移而增长 所以我不能
  • SpringBoot @SqsListener - 不工作 - 有异常 - TaskRejectedException

    我有一个 AWS SQS 队列中已有 5000 条消息 示例消息类似于 Hello 1 我创建了一个 SpringBoot 应用程序 并在其中一个组件类中创建了一个从 SQS 读取消息的方法 package com example aws
  • 自动完成请求/服务器响应是什么样的?

    这似乎是一个黑洞 经过一个小时的搜索jQuery用户界面 http en wikipedia org wiki JQuery UI网站 Stack Overflow 和谷歌搜索 我还没有找到如何编写的最基本信息服务器端自动完成的 向服务器传
  • 根据 ID 更新 React.js 中的特定组件实例

    在react js应用程序中 我想知道为每个组件提供一个ID的最佳实践是什么 该ID可用于根据需要仅更新该组件的信息 例如 如果我们有一个显示销售信息的组件 并且我们创建并显示其中 20 个组件 因为我们有 20 个产品 那么我们会每隔一段
  • 拆分 MS Access 数据库 - 前端部分位置

    最佳实践之一按照微软的规定 http msdn microsoft com en us library dd942824 aspx odc ac2007 ta PerformanceTipsToSpeedUpYourAccessDB Mul
  • jQuery 的 event.stopPropagation() 导致 Rails 出现问题:remote => true

    我创建了一些自定义 弹出窗口 最初使用 display none 样式 它们通过相邻的 popup trigger 链接进行切换 具有以下汇总功能 public javascripts application js jQuery docum
  • ClientDataset 索引更改时不计算 TAggregateField

    我正在使用连接到 DBGrid 的 TClientDataset 和几个聚合字段 用于计算其他几个浮点字段的总和 所有字段均已在设计时创建 一切都按预期工作 直到 ClientDataset 的 IndexName 使用自定义索引更改 以便
  • Wordpress 主题管理面板显示本地服务器中的致命错误

    我有一个 WordPress 项目 这里我们使用主题jupiter 当我在本地 XAMPP 服务器上设置它时 它的主题选项不起作用 这个问题出在我的电脑上 但在另一台电脑上却正常 My XAMPP是最新版本 它显示的错误 Fatal err
  • 如何在指令中插入 $compile 的 HTML 代码而不出现 $digest 递归错误?

    我有一个指令 根据ng repeat项目数据 来自数据库 使用 switch case 构建自定义 HTML app directive steps function compile return restrict A template h
  • 在 aws-elasticache 上使用 memcached 或 Redis

    我正在 AWS 上开发一个应用程序 并使用 AWS elasticache 进行缓存 我对使用 memcached 或 redis 感到困惑 我阅读了有关 redis 3 0 2 更新以及它现在如何等同于 memchached 的文章 ht
  • 有没有办法“source()”并在错误后继续?

    我有一个大型 R 脚本 其中包含 142 个小部分 如果某一部分因错误而失败 我希望脚本继续而不是停止 这些部分不一定相互依赖 但有些部分确实相互依赖 如果中间的一个失败了也没关系 我不想在这个脚本中加入try 来电 而且我不想将文件分成许
  • 确保在 ServerName 上启用默认 admin$ 共享

    运行 psexec 命令在同一网络上的服务器上远程安装或执行某些内容时 显示以下错误 无法访问服务器名称 找不到网络名称 确保在 ServerName 上启用默认 admin 共享 大多数参考文献建议您将以下内容添加到注册表中 但在我的例子
  • 当我启动程序时,Arduino IDE (Win10) 崩溃

    我的 Arduino IDE Win10 上的版本为 1 8 12 在启动时崩溃 运行arduino debug exe我收到此错误消息 C Program Files x86 Arduino gt arduino debug exe Se
  • CKEditor 4 构建(缩小和丑化)

    在我们的构建过程中 使用 grunt 我们将所有脚本连接 缩小和丑化为一个脚本 也意味着仅一个请求 现在 CKEditor 4 似乎正在使用模块样式加载方法 谁能告诉我如何将 CKEditor 4 包含到包含所有必需源的项目中 这样以后就不
  • 前台服务不持续运行

    在我的应用程序中 我使用必须不断运行的前台服务 有时前台服务会停止 在什么情况下操作系统会终止我的服务 即使有足够的内存 电池已充满 手机正在充电也会发生 到目前为止 我的代码是这样的 public class ServiceTest ex