2012-02-16 79 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);