Java 使用BroadcastReceiver | Android检查何时连接移动数据

Java 使用BroadcastReceiver | Android检查何时连接移动数据,java,android,mobile,broadcastreceiver,Java,Android,Mobile,Broadcastreceiver,我想知道如何使用BroadcastReceiver检查移动数据何时连接 以下是我目前掌握的情况: private BroadcastReceiver MobileDataStateChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra

我想知道如何使用BroadcastReceiver检查移动数据何时连接

以下是我目前掌握的情况:

    private BroadcastReceiver MobileDataStateChangedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int state = intent.getIntExtra(TelephonyManager.EXTRA_STATE,
                TelephonyManager.DATA_DISCONNECTED);

        if (state == TelephonyManager.DATA_CONNECTED) {
            mobileStatus.setText("Connected");
        } else if (state == TelephonyManager.DATA_DISCONNECTED) {
            mobileStatus.setText("Disconnected");
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.status_page);

    mobileStatus = (TextView) this.findViewById(R.id.textView4);

    registerReceiver(MobileDataStateChangedReceiver, new IntentFilter(
            TelephonyManager.ACTION_PHONE_STATE_CHANGED));
}
我在这里做错了什么

我在Wi-Fi检查中使用了相同的概念,效果很好? 我正在使用以下权限:

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

电话管理器.ACTION\u PHONE\u STATE\u CHANGED似乎不起作用,因为我可以读取它,它只能通过呼叫触发,而不能通过网络或移动数据触发。 与此相反,我建议您尝试设置一个侦听器。应该是这样的:

1) 使用
TelephonyManager tm=(TelephonyManager)Context.getSystemService(Context.TELEPHONY\u service)获取服务

2) 使用
tm.listen(myCustomPhoneStateListener,PhoneStateListener.listen\u DATA\u CONNECTION\u STATE)设置侦听器


3) 一旦你有了监听器,你就可以向你的广播接收器发送定制的意图,如果你还想这样做的话。

电话管理器。操作(电话)状态(状态)发生了变化
似乎不起作用,因为我可以阅读它,它只会在通话中触发,而不会在网络或移动数据中触发。 与此相反,我建议您尝试设置一个侦听器。应该是这样的:

1) 使用
TelephonyManager tm=(TelephonyManager)Context.getSystemService(Context.TELEPHONY\u service)获取服务

2) 使用
tm.listen(myCustomPhoneStateListener,PhoneStateListener.listen\u DATA\u CONNECTION\u STATE)设置侦听器


3) 一旦你有了监听器,你就可以向你的广播接收器发送定制的意图,如果你还想这样做的话。

非常感谢。。它成功了,在你说了之后,我搜索了PhoneStateListener.LISTEN\u DATA\u CONNECTION\u STATE,也得到了这样的信息:欢迎你。我也在为我的Android应用程序寻找类似的东西,以防止长时间下载:)非常感谢。。它成功了,在你说了之后,我搜索了PhoneStateListener.LISTEN\u DATA\u CONNECTION\u STATE,也得到了这样的信息:欢迎你。为了防止长时间下载,我还在为我的Android应用程序寻找类似的东西:)