2014-04-22 113 views
-1

我有一個簡單的Android應用程序,我草擬了一個循環中的數學計算一定的秒數(在本例中爲100)。但是,當我運行應用程序時,因爲程序中沒有任何內容要在循環之後完成,所以在寫入已完成計算的次數時,它會顯示爲未響應。有一個簡單的方法可以解決這個問題嗎?如何阻止此應用程序顯示爲未響應?

回答

1

您必須在另一個線程中執行此操作,這樣用戶界面不會被阻止,也不會變得不響應。

同時,您可以使用進度對話框顯示活動指示器。當這個過程完成後就隱藏它。

注意交叉線程中的UI操作。

0

使用異步等待並在任務中運行數學。如果你從一個活動開始任務,不要忘記取消它,如果由於某種原因活動被破壞。

這是應該讓你開始一個快速的樣品(替代註釋掉):

[Activity (Label = "AsyncSample", MainLauncher = true)] 
public class MainActivity : Activity 
{ 
    private CancellationTokenSource cancellation; 
    private Button button; 
    private Task task; 

    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate (bundle); 

     // Set our view from the "main" layout resource 
     SetContentView (Resource.Layout.Main); 

     // Get our button from the layout resource, 
     // and attach an event to it 
     button = FindViewById<Button> (Resource.Id.myButton); 

     button.Enabled = false; 
     this.cancellation = new CancellationTokenSource(); 
     this.task = RunTask(this.cancellation.Token, new Progress<int> (a => this.button.Text = string.Format ("Progress {0}", a))); 
    } 

    protected override void OnDestroy() 
    { 
     this.cancellation.Cancel(); 
     base.OnDestroy(); 
    } 

//  protected override void OnStop() 
//  { 
//   base.OnStop(); 
//   this.cancellation.Cancel(); 
//  } 
// 
//  protected override async void OnStart() 
//  { 
//   base.OnStart(); 
// 
//   this.cancellation = new CancellationTokenSource(); 
//   await RunTask (this.cancellation.Token, new Progress<int> (a => this.button.Text = string.Format ("Progress {0}", a))); 
//  } 

    private Task RunTask(CancellationToken cancelToken, IProgress<int> progress) 
    { 
     return Task.Factory.StartNew(()=> 
     { 
      for (var n = 0; n < 100 && !cancelToken.IsCancellationRequested;) 
      { 
//     await Task.Delay (1000); 
       Thread.Sleep(1000); 
       progress.Report (++n); 
      } 
     }); 
    } 
}