Amrutha Desai
Amrutha Desai

Reputation: 101

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. 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".

Upvotes: 0

Views: 45

Answers (1)

Manzoor Ahmad
Manzoor Ahmad

Reputation: 541

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>

Upvotes: 1

Related Questions