2016-12-12 18 views
0

我對這個社區並不陌生,但我經常在這個地方查找我的問題很久,並且從未失望!但是這次我很難找到完美的方式/答案/解決方案來解決我的問題,所以我第一次不得不自己去問。創建一個檢查常量更新的服務

我創造了一個類似Quizduell的遊戲,它運行流暢,我已經和一些朋友一起玩了很多回合。唯一不起作用的是「檢查更新並通知我,如果從應用程序啓動到關閉」部分。

我有一臺服務器在互聯網上運行的所有時間。客戶端,如果有新聞,Android服務器應該在服務器上請求,應用程序將會話ID和播放器的ID發送到服務器,並取回一個名稱(以保持數據量小)。該服務通過SharedPreferences獲取ID和SessionID,因爲我與Intents有一些爭執。該服務現在顯示通知,這部分工作得很好。沒有連接到App,它完全地運行在自己的(除了SharedPreferences)

的問題是,我只是不知道如何把事情開始:

我有一個廣播,這應該開火引導(但即時通訊不舒服,如果它確實,我用Airplanemodechange測試過它,但它只有在應用程序運行時,這不是我想要的)它啓動一個AlarmManager,並且每隔一段時間觸發一次服務:

[BroadcastReceiver(Enabled = true, Process = ":remote", Name = "Broadcasts.UpdateBroadcast")] 
[IntentFilter(new[] { Intent.ActionBootCompleted, Intent.ActionAirplaneModeChanged})] 
public class UpdateBroadcast : BroadcastReceiver 
{ 

public static readonly String TAG = "com.JonQse.Schlauweia.UpdateBroadcast"; 

    public override void OnReceive(Context context, Intent intent) 
{ 

     var updateService = new Intent(context, typeof(UpdateService)); 
     //context.StartService(updateService); 
     PendingIntent _mAlarmSender = PendingIntent.GetService(context, 0, updateService, 0); 
     var am = (AlarmManager)context.GetSystemService(Context.AlarmService); 
     long interval = 1000 * (int)(60 * 0.2); 
     am.SetRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + interval, interval, _mAlarmSender); 

    } 
} 

所以這根本不起作用。我不知道爲什麼。接下來的事情是,我只是不能火,當我啓動應用程序,以便它至少運行廣播manualy:

  bool alarmUp = (PendingIntent.GetBroadcast(this, 0, 
    new Intent(this, typeof(UpdateService)), 
    PendingIntentFlags.NoCreate) != null); 

     if(!alarmUp) 
     { 
      var intent = new Intent("Broadcasts.UpdateBroadcast"); 
      SendBroadcast(intent); 
     } 

我希望你能幫助我。如果我不會對這個問題瘋狂的話,我不會在這裏寫。

謝謝你們!

回答

0

這是什麼適用於我的應用程序。 清單中

允許啓動完成接收
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

你的功能應該是這樣的

[BroadcastReceiver] 
    [IntentFilter(new[] { Intent.ActionBootCompleted }, Categories = new[] { Intent.CategoryDefault })] 
    public class BootCompletedIntentReceiver : BroadcastReceiver 
    { 
     public override void OnReceive(Context context, Intent intent) 
     { 
      if (intent.Action == Intent.ActionBootCompleted) 
      { 
       context.StartService(new Intent(context, typeof(YourService))); 
      } 
     } 
    } 

內,您的服務

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) 

啓動任務Task.Run。做你的事情在這個任務。確保在服務被破壞時停止它。您可以在服務「完成」中創建一個變量,並在您的任務循環中對其進行檢查。如果您不需要帶循環的任務,則可以在OnStartCommand中啓動警報管理器。如果您不需要單獨的服務,那麼只需使用指定的啓動接收器定義,並且應該始終啓動