我希望我的应用程序检查移动数据是否已启用
只需单击一个按钮即可正常工作,但只会在点击后刷新一次信息,而不是“实时”自动刷新信息。
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错误。
诚恳, Wolfen的
答案 0 :(得分: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.
}
}
};
答案 1 :(得分: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();
}
}
});