【问题标题】:BroadcastReceiver Intent filter for network operator change用于网络运营商更改的 BroadcastReceiver 意图过滤器
【发布时间】:2015-07-30 17:59:34
【问题描述】:

在我想说什么之前,我确实搜索过这个。 我的目标是检测智能手机是否正在漫游以触发向用户发送通知。我希望在设备移交给外国移动提供商时触发通知。

我的第一个想法是使用适当的意图过滤器注册一个 BroadcastReceiver,因为我确信操作系统会检测到 SIM 何时漫游。

根据 stackoverflow 上的其他帖子,我编写了以下代码:

在 AndroidManifest.xml 上

<receiver android:name="(...).RoamingBrocastReceiver">
   <intent-filter>
       <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

我的 RoamingBrocastReceiver 类是这样的:

public class RoamingBrocastReceiver extends BroadcastReceiver {

    public static final String TAG = RoamingBrocastReceiver.class.getSimpleName();
    private NotificationManager mNotificationManager;
    private Context context;


    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "onReceive()");
        this.context = context;
        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephony.isNetworkRoaming()) {
            String notificationTitle = "Sample title";
            showNotification(notificationTitle);
            String contryIso = telephony.getNetworkCountryIso();
            Log.v(TAG, "Roaming is on: country ISO: " + contryIso);
        }
    }

}

根据我的测试,android.net.conn.CONNECTIVITY_CHANGE 操作仅在数据连接发生变化时触发(例如 wifi、3g/4g 数据),但在网络发生变化时不会触发。 我使用本地和外国 SIM 卡进行了一些测试,当我在设备开启的情况下更改 Nexus 5 上的 SIM 卡时,从未触发此操作。

有我需要的操作吗?

【问题讨论】:

    标签: android android-intent broadcastreceiver


    【解决方案1】:

    您正在使用正确的操作android.net.conn.CONNECTIVITY_CHANGE

    但是要检查漫游使用这个

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    
    if(ni != null && ni.isRoaming()) {
      // device is in roaming state
    }
    

    注意:在某些版本上似乎存在一个错误,如果漫游,getActiveNetworkInfo() 会返回 null。见这里:http://code.google.com/p/android/issues/detail?id=11866

    【讨论】:

    • 不,当设备切换到外部网络时,不会触发该操作。漫游部分对我来说工作正常。
    • 我的 BroadcastReceiver 构建良好。我知道这一点,因为当我激活/停用我的 wifi 天线或 3g/4g 数据时,它会收到一个意图。 @Rami Jarrar 我不确定你想让我从那个帖子中得到什么。虽然当我们通常继续漫游时,设备会收到一条警告短信,我可以用它来检查我是否正在漫游。但我认为这不是最好的方法,因为每次收到短信时我都必须检查。
    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 2017-02-20
    • 2020-12-16
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多