我正在尝试开发简单的android应用程序,它使用http客户端监视指定的url,一旦满足了定义的条件,就应该执行通知操作。
我有一个活动,它启动单独的线程,并通过静态值对其进行引用。(在重新创建活动时,我将签入null的引用,以确定是否已经启动子线程)。在这个子线程中,我有while循环,它从url获取json数据并解析它。
我注意到了奇怪的行为(可能是因为我是android新手)。一旦应用程序进入前台,它的工作速度相当快,当android设备进入睡眠模式时,它不会经常执行请求。(也许是一些能源安全政策?)最奇怪的是,一旦我通过usb电缆将手机连接到计算机上,就能快速工作(即使应用程序在后台,手机也有黑色屏幕)。
是否与激活基于连接充电器的/disactivating应用程序有关?我无法调试它,因为一旦我连接了电缆,它就能正常工作,而且如果不连接到计算机,我就无法调试。
发布于 2014-11-22 17:47:07
问题可能是手机进入睡眠模式时,它几乎停止了几乎所有的活动,并减慢了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_LOCK在Manifest文件中的权限。
关于AlarmManager使用的另一篇文章:安卓:如何使用AlarmManager
第一个链接上的文章说,最好为此目的使用同步适配器,但我自己还没有使用它们。
https://stackoverflow.com/questions/27080444
复制相似问题