Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android后台服务无限循环,电池耗尽问题?_Android_Performance_Service_Infinite Loop - Fatal编程技术网

android后台服务无限循环,电池耗尽问题?

android后台服务无限循环,电池耗尽问题?,android,performance,service,infinite-loop,Android,Performance,Service,Infinite Loop,我正在编写一个应用程序,其中一个功能是通过通知每天通勤的人们,如果他们通常乘坐的公共交通工具出现某种延误,就会通知他们 我曾考虑使用AlarmManager实现此功能,但我发现与选择了多少公共交通工具以及用户决定在几天内接收通知有关的问题太多 因此,我想出了另一个解决方案:将用户首选项保存到一个文件中,并启动一个后台服务,每5分钟检查一次该文件,如果条件得到满足,它将显示通知: @Override public int onStartCommand(Intent intent, int flag

我正在编写一个应用程序,其中一个功能是通过通知每天通勤的人们,如果他们通常乘坐的公共交通工具出现某种延误,就会通知他们

我曾考虑使用AlarmManager实现此功能,但我发现与选择了多少公共交通工具以及用户决定在几天内接收通知有关的问题太多

因此,我想出了另一个解决方案:将用户首选项保存到一个文件中,并启动一个后台服务,每5分钟检查一次该文件,如果条件得到满足,它将显示通知:

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

    while(true){
        try{              
            if (fileCheck()){
                Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.avanti).setContentTitle(getString(R.string.app_name)).setSound(alarmSound);
                mBuilder.setContentText("Test");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(0, mBuilder.build());
                Thread.sleep(300000)
            }
        } catch (Exception ignored){}
    }
}

这是可行的,但我有一个疑问:这会导致性能或电池耗电问题吗?或者它大部分时间都在睡觉,所以安全吗?

您的第一个问题是它会崩溃,背景相当于ANR。您正试图在主应用程序线程上睡眠5分钟,这将不起作用。您的第二个问题是,您的进程最终将被终止,并且您将不再每隔5分钟获得控制权。@Commonware那么您认为我应该尝试将其移动到IntentService吗,或者找到一种方法来解决我的问题并使用AlarmManager?最好的答案是将大部分代码移动到服务器,并在满足用户需要了解的条件时使用Google Cloud Messaging(GCM)。如果
minSdkVersion
为21或更高,则下一个最佳答案是使用
JobScheduler
。下一个最好的答案是使用
AlarmManager
@commonware。我会接受下一个最好的答案,谢谢你的帮助!