android - 为特定活动实现广播接收器
问题描述
我正在构建一个 android 应用程序,用于为一组问题提供反馈。问题的数量每次根据服务器数据而有所不同。在下面的代码中,我在 QuestionAnswerActivity 中实现了提交按钮,它可以保存数据在线和离线。我想实现一个广播接收器,它应该检测 QuestionAnswerActivity 中的网络变化并提交存储在本地数据库(离线)中的数据(答案)。它还应该显示适当的 toast 消息。例如:“没有互联网连接”或“互联网”连接的”。
解决方案
在清单中注册广播并使用下面的代码。
public class NetworkReceiver extends BroadcastReceiver {
Cursor cursor;
SQLHelper helper;
Boolean IsSubmitted=false;
Context c;
@Override
public void onReceive(Context context, Intent intent) {
helper = new SQLHelper(context);
this.c = context;
pt = new ProcessTask();
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.d("Network", "Internet YAY");
// Code when internet is connected
cursor = helper.getProcessTask(context);
getdataFromSql(cursor,context);
} else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
Log.d("Network", "No internet :(");
}
}
}
在清单中添加
<receiver
android:name=".NetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
推荐阅读
- javascript - 如何创建一个每次都生成一个新变量的 for 循环
- presto - Presto SQL 是否像 SQL Server 一样支持使用 CTE 进行递归查询?例如员工层级
- twilio - 添加 Studio Flow 后,Twilio REST 客户端停止工作?
- python-3.x - 没有名为“bitmex_websocket”的模块
- python - 查找更改整数以匹配列表中其他人的最小移动次数
- c# - Telerik WinForm RadGridView 清除过滤
- javascript - 故事书行动——他们到底在叫什么?
- python - 如何将两个列表的子列表作为单个实体进行比较?
- tensorflow-federated - Tensorflow Federated 是否支持强化学习
- java - 为什么在演示中同步工作时 ReentrantLock 不起作用?