有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

未连接充电器时的java 安卓?

我正在尝试开发一个简单的安卓应用程序,它使用http客户端监控指定的url,一旦满足定义的条件,它就应该执行通知操作

我有一个活动,它启动单独的线程,并通过静态值引用它。(当重新创建活动时,我会检查not null的引用,以确定子线程是否已经启动)。在这个子线程中,我有一个while循环,它从url获取json数据并对其进行解析

我注意到了奇怪的行为(可能是因为我是安卓开发新手)。一旦应用程序出现在前台,它的运行速度就相当快,当安卓设备进入睡眠模式时,它不会经常执行请求。(也许是一些能源安全政策?)。最奇怪的是,一旦我通过usb线将手机连接到电脑上,就可以快速工作(即使应用程序在后台,手机有黑屏)

是否与基于连接的充电器激活/禁用应用程序有关? 我无法调试它,因为一旦我连接了电缆,它就可以正常工作,而且如果不连接到计算机,我就无法调试


共 (1) 个答案

  1. # 1 楼答案

    问题可能是,当手机几乎停止所有活动并降低CPU速度时,它会进入睡眠模式。它是用来节省电池的。例如Handler.postDelayed()上的计时器将无法正常工作(未按时调用)。 这方面有一个特殊的概念——对于需要在睡眠模式下执行的活动,您需要使用AlarmManager,请参见Scheduling Repeating Alarms

    问题是,你的应用程序需要向AlarmManager注册,然后当手机从睡眠模式唤醒时,它会收到预定的事件。你的应用程序需要获得PowerManager的锁定才能执行活动(在你的情况下,它是从网络下载JSON),你不想在执行活动时被睡眠模式打断。考虑这个例子:

    public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
    
        /**
         * This method is called when we are waking up by AlarmManager
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pulse app");
            //Acquire the lock
            wl.acquire();
    
            //You can do the processing here.
    
            //Release the lock
            wl.release();
        }
    
        /**
         * Register our app with AlarmManager to start receiving intents from AlarmManager
         */
        public static void setAlarm(Context context)
        {
            int interval = 10; // delay in secs
            AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
            am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval*1000 , pi);
        }
    
        /**
         * Unregister the app with AlarmManager, call this to stop receiving intents from AlarmManager
         */
        public static void cancelAlarm(Context context)
        {
            Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
            PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(sender);
        }
    
    }
    

    此代码需要清单文件中的android.permission.WAKE_LOCK权限

    另一篇关于AlarmManager用法的帖子:Android: How to use AlarmManager

    还有这个:prevent mobile from going into sleep mode when app is running

    第一个链接上的文章说,出于这种目的,最好使用同步适配器,但我自己没有使用过