Java 未连接充电器时的速度较慢?

Java 未连接充电器时的速度较慢?,java,android,multithreading,android-activity,Java,Android,Multithreading,Android Activity,我正在尝试开发一个简单的android应用程序,它使用http客户端监控指定的url,一旦满足定义的条件,它就应该执行通知操作 我有一个活动,它启动单独的线程,并通过静态值对其进行引用。(当重新创建活动时,我正在检查NOTNULL的引用,以确定子线程是否已经启动)。在这个子线程中,我有一个while循环,它从url获取json数据并对其进行解析 我注意到了奇怪的行为(可能是因为我是android开发新手)。一旦应用程序出现在前台,它的工作速度就相当快,当android设备进入睡眠模式时,它不会经

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

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

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

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

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

问题是,您的应用程序需要向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\u LOCK清单文件中的
权限

另一篇关于AlarmManager用法的帖子:

这是:

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