我已经完成了利用广播接收器的代码,以便在连接状态更改时调用 Receive 上的方法并显示指示更改的 toast。从这个意义上说,我有一个单独的类,其中以这种方式实现广播接收器:
public class Receiver extends BroadcastReceiver {
private static final String DEBUG_TAG = "NetworkStatusExample";
@Override
public void onReceive(Context context, Intent intent) {
// Shows a toast when the connectivity state change
Toast.makeText(context, "stato wifi cambiato",
Toast.LENGTH_LONG).show();
Log.d("prova", "action: "
+ intent.getAction())
}
}
当网络状态发生变化并显示 toast 时,它可以正确调用 OnReceive() 方法。
在主文件中,我放置了一个代码,一旦按下按钮,它就会验证 Wifi 是否已连接,在这种情况下,也会根据连接的存在与否显示带有消息“Wifi connected:true/false”的 toast . 在这种情况下也有效的代码是:
public class MainActivity extends Activity {
private static final String DEBUG_TAG = "NetworkStatusExample";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final boolean isWifiConn = networkInfo.isConnected();
String wifiStateText = "No State";
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Button prova = (Button) findViewById(R.id.button1);
prova.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Wifi connected: " + isWifiConn;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
现在我正在尝试将代码的最后一部分嵌入到上面定义的方法 OnReceive() 中,以便在网络连接发生变化时自动执行所有操作,所以我得到的广播接收器代码是这样的:
public class Receiver extends BroadcastReceiver {
private static final String DEBUG_TAG = "NetworkStatusExample";
// Verifica se il wifi è connesso
@Override
public void onReceive(Context context, Intent intent) {
// Shows a toast when the connectivity state change
Toast.makeText(context, "stato wifi cambiato",
Toast.LENGTH_LONG).show();
Log.d("prova", "action: "
+ intent.getAction());
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final boolean isWifiConn = networkInfo.isConnected();
String wifiStateText = "No State";
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
// Toast that shows if the wifi is connected
CharSequence text = "Wifi connected: " + isWifiConn;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
在这种情况下,我收到此错误:
the method getsystemservice(string) is undefined for the type Receiver
在这条线上:
getSystemService(Context.CONNECTIVITY_SERVICE);
怎么了?我该怎么做才能修复它?