我正在制作一个Android应用程序
1)循环开始并检查是否存在连接
2)如果是,则执行TASK A并退出
3)如果不是,则显示TOAST消息 然后转到第1步
为了实现这一点,我尝试将Toast消息放入循环并尝试
1)创建一个扩展Asynch Tasks并在doBackground()中显示Toast的类
2)创建一个处理程序。我在postDelayed中显示了Toast消息
3)在runOnUiThread()
中显示toast所有人都遇到了同样的命运
对于较小的值(<10s),应用程序将无限期停止
对于较大的值(= 30秒),应用程序会强制关闭
int t=0;
while (!t=1)
{
ConnectionCheck2 cd = new ConnectionCheck2(mContext);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent)
{
//TASK A
t=1;
}
else
{
//made call to Handler, Asynch Tasks and runOnUiThread here to display the Toast message below
Toast.makeText(MainActivity.this,"Internet is NOT connected",
Toast.LENGTH_SHORT).show();
}
}
类ConnectionCheck构造函数使用显示toast消息的类的上下文进行初始化。它有一个名为isConnectingToInternet()的方法,它检查是否存在互联网连接。该类和功能的真实性已得到确认。
我试过
public void doSomeWork()
{
final Timer someTimer= new Timer ();
someTimer.schedule (new TimerTask () {
@Override
public void run()
{
ConnectionCheck2 cd = new ConnectionCheck2(MainActivity.this.getApplicationContext());
final Boolean isInternetPresent = cd.isConnectingToInternet();
runOnUiThread (new Thread(new Runnable() {
public void run()
{
if (isInternetPresent)
{
Change();
someTimer.cancel();
}
Toast.makeText(MainActivity.this.getApplicationContext(),"NOT Connected",Toast.LENGTH_SHORT).show();
}
}));
}
}, 1000, 5000);
if (g==1)
{
Toast.makeText(MainActivity.this.getApplicationContext(), "Internet is connected", Toast.LENGTH_SHORT).show();
}
}//doSomeWork
public void Change()
{
g=1;
}
//g is declared as a global variable
但是,如果我最初关闭网并将其打开,则互联网连接不会显示
我把toast消息放在runOnUithread()但是我的问题是,如果我删除控制条件然后,控件首先进入,toast消息说&#34;互联网连接&#34; (定时器后面的语句)然后到&#34; NOt connected&#34;一。此外,当找到Internet连接并执行timer.cancel()时,控件不会转到计时器后面的语句,而是退出。按照我的想法,首先应该执行定时器模块,然后应该执行它后面的语句,iff timer.cancel()condition是真的
答案 0 :(得分:1)
虽然循环不是一个好方法,但您可以运行TimerTask以在每个指定的时间值之后运行。
Timer someTimer= new Timer ();
someTimer.schedule (new TimerTask () {
@Override
public void run () {
// do your Checking here, for toast use runOnUIThread() or handler.
}
}, 0, 100);
备注:强>
<强>更新强>
final Timer someTimer = new Timer ();
someTimer.schedule (new TimerTask () {
@Override
public void run () {
ConnectionCheck2 cd = new ConnectionCheck2 (MainActivity.this.getApplicationContext ());
final Boolean isInternetPresent = cd.isConnectingToInternet ();
runOnUiThread (new Thread (new Runnable () {
public void run () {
if (isInternetPresent) {
Change ();
someTimer.cancel ();
return;
}
Toast.makeText (MainActivity.this.getApplicationContext (), "NOT Connected", Toast.LENGTH_SHORT).show ();
}
}));
}
}, 0, 5000);
if (g == 1) {
Toast.makeText (MainActivity.this.getApplicationContext (), "Internet is connected", Toast.LENGTH_SHORT).show ();
}
}