2012-02-16 81 views
1

出于测试目的,我做了一个服务,每1分钟发出一次哔哔声 。 (没有客户端 - 服务器界面)。当屏幕开启时,它会发出哔哔声,但当它进入睡眠哔哔声停止状态时。屏幕锁定服务暂停

我正在制作一个应用程序,必须定期轮询服务器 的东西。

对于这一点,我想创建一个服务,它会不断地 在后台运行,轮询服务器每隔1分钟,然后根据从服务器应生成一个任务栏通知的答复 。

我有一个测试活动,两个按钮,1开始,另一个到 停止服务。并命名为S_PS_PollService

一个服务类的“启动活动”按钮setOnClickListener包含:

Thread pollServiceThread = new Thread() { 
    public void run() { 
    startService(new Intent(MM_MainMenu.this, 
    S_PS_PollService.class)); 
    } 
}; 

pollServiceThread.start(); 

的“停止活动”按钮,只需有:

stopService(new Intent(MM_MainMenu.this, S_PS_PollService.class)); 

以下是从S_PS_PollService类的方法:

public void onCreate() { 
pollSound = MediaPlayer.create(this, R.raw.chirp); 
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
Intent myIntent = new Intent(this, S_PS_PollService.class); 
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0); 
// for wake lock 
pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag") 
// for calendar 
calendar = Calendar.getInstance(); 
} 

Onstart:

public void onStart(Intent intent, int startId) { 
super.onStart(intent, startId); 

wl.acquire(); 

pollSound.start(); 

calendar.setTimeInMillis(System.currentTimeMillis()); 
calendar.add(Calendar.MILLISECOND, 60000); 
alarmManager.set(AlarmManager.RTC_WAKEUP, 
calendar.getTimeInMillis(), pendingIntent); 

wl.release(); 
} 

每当警报启动onStart()方法执行,使 蜂鸣和设置新的警报。但只有在屏幕开启的情况下,它才会起作用。

我试过了https://github.com/commonsguy/cwac-wakeful,但没有 明白了。相对较新的Android ...

请帮助我,我非常绝望:)谢谢!

回答

0

你必须使用AlarmManager,这里有很多帖子在stackoverflow上。

0

如代码所示,您想要获取部分唤醒锁定(只要在设备上输入了睡眠状态,CPU就会一直运行)。

问题是你大概会在启动时释放唤醒锁。你想在onDestroy中释放你的wakeLock ..一旦你的服务完成运行。

0

这终于为我工作。 从https://github.com/commonsguy/cwac-wakeful

下载CWAC-WakefulIntentService.jar添加类项目中的

import com.commonsware.cwac.wakeful.WakefulIntentService; 

public class WakeService extends WakefulIntentService { 

    public WakeService(String name) { 

     super(name); 

    } 
    @Override 
    protected void doWakefulWork(Intent intent) { 
    } 
} 

现在添加在下面一行代码在任何你想重复循环和唤醒设备

WakefulIntentService.sendWakefulWork(this, S_WS_WakeService.class);