[英]Implementing Broadcast reciever for a particular activity
I am building an android app, which is meant for giving feedback for a set of questions.The no of questions vary each time depending on the server data.In the code below I have the implementation of the submit button in my QuestionAnswerActivity which saves data both online and offline. 我正在构建一个Android应用程序,旨在为一组问题提供反馈。问题的数量根据服务器数据的不同而有所不同。在下面的代码中,我在QuestionAnswerActivity中实现了Submit按钮,以保存数据在线和离线。 I want to implement a BroadcastReceiver which should detect the network changes in the QuestionAnswerActivity and submit the data(answers) stored in the local database(offline).It should also show appropriate toast messages.for ex:"No internet connection" or "Internet connected".
我想实现一个BroadcastReceiver,它应该检测QuestionAnswerActivity中的网络变化并提交存储在本地数据库(脱机)中的数据(答案)。它还应该显示适当的Toast消息。例如:“无互联网连接”或“互联网连接的”。
Register a broadcast in manifest and use the code below. 在清单中注册广播,并使用下面的代码。
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 :(");
}
}
}
in Manifest add 在清单中添加
<receiver
android:name=".NetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.