原文:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=185702&fromuid=683562
最近一个项目中在service中使用handler的post方法写了个定时上传GPS位置和电量的功能,但测试的时候发现每当锁屏或者按电源键锁屏的时候都会出现,上传数据终端的情况,很是纠结,翻了好多资料,甚至电源键的监听都在考虑,后来发现努力的方向错了 bull shit...
下面说说 我采取的解决办法和另外一些别的办法
public abstract class HWBasicActivity extends BaiduMapActivity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
......
}
采取这个方法的原因是改起来方便(也可以说是偷懒...),因为项目已开始的时候我就做了一个BasicActivity只用在这个Activity中加上一个重写一下Oncreate方法加上一句话就O了 很爽 所以就用了 当然这种方法还有一个更简便的使用方式,就是在mainfast里边添加一句权限代码
下面是另一种方法 是修改自己的的service (这个会让大部分码农恶心。。。)
因为这个要动的东西太多
首先要去除handler.post定时延迟上传的部分代码 还要在项目启动的时候 添加这样的一段代码
PendingIntent sender = PendingIntent.getService(this, 0,new Intent(this,AlarmService.class), 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 5*1000, sender);
这里边不能使用 ELAPSED_REALTIME 开始不知道用的这个发现没什么效果 后来看了下注释,才知道大概是说
当屏幕在休眠状态下该提醒不会被唤醒,除非再次唤醒屏幕
而 ELAPSED_REALTIME_WAKEUP 是在任何状态下都会被唤醒! 下边是两个常量的注释
/**
* Alarm time in {<a href="\"http://www.eoeandroid.com/home.php?mod=space&uid=91636\"" target="\"_blank\"">@link</a> android.os.SystemClock#elapsedRealtime
* SystemClock.elapsedRealtime()} (time since boot, including sleep),
* which will wake up the device when it goes off.
*/
public static final int ELAPSED_REALTIME_WAKEUP = 2;
/**
* Alarm time in {@link android.os.SystemClock#elapsedRealtime
* SystemClock.elapsedRealtime()} (time since boot, including sleep).
* This alarm does not wake the device up; if it goes off while the device
* is asleep, it will not be delivered until the next time the device
* wakes up.
*/
public static final int ELAPSED_REALTIME = 3;