首页 > 解决方案 > 为特定活动实现广播接收器

问题描述

我正在构建一个 android 应用程序,用于为一组问题提供反馈。问题的数量每次根据服务器数据而有所不同。在下面的代码中,我在 QuestionAnswerActivity 中实现了提交按钮,它可以保存数据在线和离线。我想实现一个广播接收器,它应该检测 QuestionAnswerActivity 中的网络变化并提交存储在本地数据库(离线)中的数据(答案)。它还应该显示适当的 toast 消息。例如:“没有互联网连接”或“互联网”连接的”。

标签: androidbroadcastreceiverandroid-broadcastreceiver

解决方案


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

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>

推荐阅读