ネットワークをチェックするためのブロードキャストがあります。ネットワークの状態が変化すると、onNetworkActivated() または onNetworkInactivated() でアクティビティに通知します。
public class NetworkBroadcastReceiver extends BroadcastReceiver
{
private OnNetworkListener currentActivity = null;
public NetworkBroadcastReceiver(FragmentActivity activity)
{
try
{
currentActivity = (OnNetworkListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " doit implémenter OnNetworkListener");
}
}
@Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
currentActivity.onNetworkInactivated();
return;
}
else
{
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.getState() == NetworkInfo.State.CONNECTED)
{
currentActivity.onNetworkActivated();
return;
}
}
currentActivity.onNetworkInactivated();
}
public interface OnNetworkListener
{
public void onNetworkActivated();
public void onNetworkInactivated();
}
}
私のアクティビティでは、さまざまな理由でsendBroadcastを初めて呼び出す必要があるときに、Androidがクラッシュします:s
public class Earthquake extends FragmentActivity implements OnNetworkListener
{
private FragmentManager fragmentManager;
private NetworkBroadcastReceiver networkbroadcastreceiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragmentManager = getSupportFragmentManager();
networkbroadcastreceiver = new NetworkBroadcastReceiver(Earthquake.this);
this.registerReceiver(networkbroadcastreceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
this.sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
protected void onDestroy()
{
this.unregisterReceiver(networkbroadcastreceiver);
super.onDestroy();
}
public void onNetworkActivated()
{
Log.e("onNetworkActivated", "onNetworkActivated");
}
public void onNetworkInactivated()
{
Log.e("onNetworkInactivated", "onNetworkInactivated");
}
}
何が問題ですか ?
前もって感謝します