2012-08-03 39 views
1

我希望我的應用程序能夠檢查移動數據是否已啓用製作線程循環的最佳方法是什麼?

只需單擊一個按鈕,但它只會在點擊後只刷新一次信息,而不會自動在「實時」時正常工作。

threadCheck = new Thread(new Runnable() { 

     public void run() { 
      // TODO Auto-generated method stub 

       try { 
        setTextfield(isMobileDataEnabled()); 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 

    }); 



    this.startbutton.setOnClickListener(new OnClickListener() { 

     public void onClick(View arg0) { 

      threadCheck.run(); 

     } 

    }); 

什麼是最好的,CPU最友好的方式,使此線程「循環」? 我試圖遞歸調用isMobileDataEnabled(),但最終發生了一個stackoverflow錯誤。

誠懇, 沃爾芬

回答

2

我覺得你最好的選擇實際上是ConnectivityManager廣播聽衆。它會告訴你網絡何時可用或不可用。註冊廣播並在聽衆中更新您的按鈕。這樣就沒有循環,你的CPU大部分空閒。當網絡發生變化時,它會在沒有任何必要輪詢的情況下通知廣播公司。這是相當快,所以我不會擔心「實時」;)

這些應該幫助你開始。

http://developer.android.com/reference/android/net/ConnectivityManager.html

http://developer.android.com/reference/android/content/BroadcastReceiver.html

public class MyActivity extends Activity { 

    public void onCreate(Bundle b) { 
     mButton = (Button) findViewById(R.id.button); 
     registerReceiver(mBroadcastReceiver, new IntentFilter(ConnectivityMananger.CONNECTIVITY_ACTION)); 
     ..... 
    } 
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      if (ConnectivityMananger.CONNECTIVITY_ACTION.equals(intent.getAction()) { 
       boolean connectionLost = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); 
       mButton.setText("Network Enabled:" + ! connectionLost); 
       // or whatever else you want to callback. 
      } 
     } 
    }; 
+0

來獲取信息的移動數據狀態是否已經改變,你必須使用反射:方法M = c.getDeclaredMethod( 「getMobileDataEnabled」);我不認爲這將適用於ConnectivityManager。 – Wolfen 2012-08-03 03:42:08

+0

你爲什麼需要反射方法?我會用一些示例代碼更新我的答案。 – 2012-08-03 03:43:18

+0

我期待着您的代碼。謝謝:) – Wolfen 2012-08-03 03:49:36

0
public void run() { 
      // TODO Auto-generated method stub 

       try { 

while (isMobileDataEnabled()) { 
      // do something in the loop 
      } 

} catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 

    }); 
+0

謝謝。但是當移動數據不活躍時,這會阻止我的線程。所以,如果我關閉移動數據,然後重新激活它,它將不再工作。 – Wolfen 2012-08-03 03:44:41

相關問題