2016-05-30 116 views
1

在我開發的應用程序中,我需要在活動之間運行計時器以跟蹤OAuth令牌的持續時間。爲此,我實施了一項服務。Xamarin Android後臺計時器服務

這裏的服務代碼:

[return: GeneratedEnum] 
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) 
{ 
    // Gets the token duration in seconds 
    tokenDuration = Convert.ToInt32(intent.GetStringExtra("tokenDuration")); 

    tokenStart = Convert.ToDateTime(intent.GetStringExtra("tokenStart")); 
    tokenEnd = Convert.ToDateTime(tokenStart.AddSeconds(tokenDuration)); 
    t = new Thread(() => 
    { 
     timer = new Timer(tokenDuration); 
     timer.Interval = 60000; 
     timer.Elapsed += OnTimedEvent; 
     timer.Enabled = true; 

    }); 
    t.Start(); 

    return StartCommandResult.Sticky; 
    //return base.OnStartCommand(intent, flags, startId); 
} 

private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) 
{ 
    timeElapsed++; 
    System.Diagnostics.Debug.WriteLine("Minute elapsed, Total Token duration {0}s, Total time elapsed {1}min", tokenDuration, timeElapsed); 


    if (tokenEnd.Add(new TimeSpan(0, -3, 1)) == tokenStart.AddMinutes(timeElapsed)) 
    { 
     timer.Stop(); 

     Intent intent = new Intent(); 
     intent.SetAction(action); 
     intent.PutExtra("AskRefreshToken", true); 
     SendBroadcast(intent); 
    } 
} 

我對於這個問題是我怎麼能得到這些信息在活動令牌時需要更新,這樣我就可以更新視圖模型。 有沒有更好的方法來解決這個問題? 請注意,我是Android開發初學者。 預先感謝您。

回答

2

我會去使用messenger插件進行消息傳遞。 https://github.com/MvvmCross/MvvmCross-Plugins/tree/master/Messenger

創建一個特殊的消息

public class TokenRefreshedMessage 
    : MvxMessage 
{ 
    public TokenRefreshedMessage(object sender) 
     : base(sender) 
    { 
    } 
} 

發佈消息在您的服務

Mvx.Resolve<IMvxMessenger>().Publish(new TokenRefreshedMessage(this)); 

訂閱消息

public class MyViewModel : MvxViewModel 
{ 
    private readonly MvxSubscriptionToken _token; 

    public LocationViewModel(IMvxMessenger messenger) 
    { 
     _token = messenger.Subscribe<TokenRefreshedMessage>(OnTokenRefreshed); 
    } 

    private void OnTokenRefreshed(TokenRefreshedMessage locationMessage) 
    { 
     // update properties 
    } 
} 
+0

謝謝,稍後會檢查出來:) –