首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当没有连接到充电器的时候,更慢的android?

当没有连接到充电器的时候,更慢的android?
EN

Stack Overflow用户
提问于 2014-11-22 17:42:36
回答 1查看 981关注 0票数 0

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

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

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-22 17:47:07

问题可能是手机进入睡眠模式时,它几乎停止了几乎所有的活动,并减慢了CPU。它用来节省电池。例如,Handler.postDelayed()上的计时器不能正常工作(不能按时调用)。关于这个问题有一个特殊的概念需要在睡眠模式下执行的活动,您需要使用AlarmManager,请参阅调度重复报警器

问题是,您的应用程序需要在AlarmManager注册,然后当手机从睡眠模式中醒来时,它将接收预定的事件。您的应用程序需要锁定PowerManager来执行活动(在您的示例中是从网络下载JSON ),您不希望在执行这些活动时被睡眠模式打断。考虑一下这个例子:

代码语言:javascript
复制
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_LOCKManifest文件中的权限。

关于AlarmManager使用的另一篇文章:安卓:如何使用AlarmManager

这个:当应用程序运行时,防止移动进入睡眠模式

第一个链接上的文章说,最好为此目的使用同步适配器,但我自己还没有使用它们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27080444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档