gpt4 book ai didi

ANDROID - 当我调用 sendBroadcast 检查网络时崩溃

转载 作者:行者123 更新时间:2023-12-01 19:26:41 25 4
gpt4 key购买 nike

我有一个广播来检查网络,当网络改变状态时,我用 onNetworkActivated() 或 onNetworkInactivated() 通知我的 Activity :

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();
}
}

在我的 Activity 中,当我由于各种原因需要第一次调用 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");
}
}

问题是什么?

提前谢谢

最佳答案

https://stackoverflow.com/a/17906435/2201919作者:@JoxTraex

您无权发送此广播。如果应用程序可以发送此广播,则可能会导致设备出现问题。这是 protected 系统广播。

请以不同的方式解决您的问题。

引用:http://developer.android.com/reference/android/net/ConnectivityManager.html

请注意,只有少数方法使用该操作。这意味着您无法发送此广播。

关于ANDROID - 当我调用 sendBroadcast 检查网络时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15006105/

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