【发布时间】: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