为特定活动实施广播接收器

时间:2018-09-04 11:56:50

标签: android broadcastreceiver android-broadcastreceiver

我正在构建一个Android应用程序,旨在为一组问题提供反馈。问题的数量每次都取决于服务器数据。在下面的代码中,我在QuestionAnswerActivity中实现了Submit按钮可以在线和离线保存数据。我想实现一个BroadcastReceiver,它应该检测QuestionAnswerActivity中的网络变化并提交存储在本地数据库(脱机)中的数据(答案)。它还应该显示适当的Toast消息。例如:“无互联网连接”或“互联网已连接”。

1 个答案:

答案 0 :(得分:1)

在清单中注册广播并使用下面的代码。

impl<'a> SimpleMessage<'a>

在清单中添加

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 :(");


        }
    }
}