我知道 onCreateOptionsMenu 只在活动上调用一次,但是否可以在 onOptionsItemSelected 上设置网络检查?
我曾尝试在选择项目时使用 ConnectivityManager 网络检查,但它总是返回 true ......我不确定它是否在调用 onCreateOptionsMenu 然后锁定网络状态时设置。
这是我的代码:
public void refreshCheck(){
try
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm == null)
isAvailable = false;
else
isAvailable = cm.getActiveNetworkInfo().isAvailable();
}
catch(Exception e){}
if(isAvailable == true)
{
listDataPopulate();
}
else
{
Toast refresherror = Toast.makeText(this, "Connection interrupted. Unable to refresh.", duration);
refresherror.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.news_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId())
{
case R.id.aboutMenuItem:
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setTitle("About App").setMessage("About this app....").setNeutralButton("OK", null).show();
break;
case R.id.refreshNewsMenuItem:
refreshCheck();
break;
default:
}
{
}
return super.onOptionsItemSelected(item);
}