gpt4 book ai didi

java - 连接改变时显示 toast

转载 作者:行者123 更新时间:2023-11-29 08:00:46 26 4
gpt4 key购买 nike

我构建了一个使用 WebView 流式传输音频的应用程序。现在我添加了一个检查是否有连接(或没有)。使用 toast 我显示一 strip 有“真”或“假”的消息,但我只想在连接发生变化时显示 toast 。我该怎么办?

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

update();

private void update() {
new Thread() {
public void run() {
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
isOnline();
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}


public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {

Toast.makeText(getApplicationContext(), "true",Toast.LENGTH_LONG).show();
return true;
}
Toast.makeText(getApplicationContext(), "false",Toast.LENGTH_LONG).show();
return false;

最佳答案

试试这个:

public class BroadCastSampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

if(currentNetworkInfo.isConnected()){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}

在您的 list 中添加此权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

关于java - 连接改变时显示 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com