How to identify a change in the state of Internet connectivity to execute a method when connecting?

2

I'm trying to implement this train and not getting it. I wanted to do the same thing as the colleague who opened the thread, but I could not even follow these examples.

I have some questions: In what class do I set this Calendar bid? On the receiver itself? from what I understood from the example, it is calling itself in this example of the topic ( topic link ):

Intent tarefaIntent = new Intent(context, ExecutarTarefaProgramadaReceiver.class);

What I would like: I am developing together with facul colleagues, a localization system. The idea is to check from time to time if there is an internet connection. If you have unsent connection and information from our app, then we will send the data to a webservice or anywhere else we imagine. That way I did it, every time I unlock the cell phone screen it just opens the map. (but this is not what I want, as I want the service to remain active and to "wake up (check a condition and if it is true run") execute a method).

Summary:

I would like my service to start at the boot of the phone and stay "listening" until there is an internet connection. When it does, then it does something - in that case it executes a method that I determine (which I also do not know where it should be).

My Receive:

package com.teste.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.teste.MapsActivity;

/**
 * Created by Jaquisson on 17/09/2015.
 */
public class TbReceiver extends BroadcastReceiver {
    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {

            Intent intent = new Intent(context, MapsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);


        }
    }

}

MyService looks like this:

package com.teste.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.IBinder;

/**
 * Created by Jaquisson-SENAC on 17/09/2015.
 */
public class TbService extends Service {
    private BroadcastReceiver receiver;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

        //IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        //filter.addAction(Intent.ACTION_SCREEN_OFF);
        //filter.addAction(Intent.ACTION_USER_PRESENT);

        //receiver = new TbReceiver();

        //Log.d("service", "Receiver será iniciado");
        //registerReceiver(receiver, filter);

        //super.onCreate();

    }


}

And below is the excerpt from my manifesto:

<service
    android:name=".service.TbService"
    android:exported="false" >
</service>
<service
    android:name=".BuscaLocalizacao"
    android:exported="false" >
</service>

<receiver  android:name=".receiver.TbReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.SCREEN_ON" />
        <action android:name="android.intent.action.SCREEN_OFF" />
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>

Dude, I've researched in several places and I can not understand how I should do it. I looked at the documentation, but I did not understand either. I'm starting out and a little lost in it.

I'm sorry to post this bunch of stuff, but I'm a bit of a detail.

Thank you.

    
asked by anonymous 23.09.2015 / 20:05

4 answers

2

To be notified of a change in the state of network connectivity ( network ) you must declare a BroadcastReceive that responds to Action android.net.conn.CONNECTIVITY_CHANGE

In AndroidManifest.xml register BroadcastReceive : (See note)

<receiver android:name=".ConnectivityChangeReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

BroadcastReceive will be anything like this:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context ctx, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            if(isConnected(ctx)){
                //O código aqui é executado ao conectar
                Toast.makeText(ctx, "Conectado", Toast.LENGTH_SHORT).show();
            }else{
                //O código aqui é executado ao desconectar
                Toast.makeText(ctx, "Desconectado", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean isConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) 
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
             }
         }
        return false;
    }

}

Include this permission in manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Please note that having an active connection to the network does not guarantee that you have access to the internet, see Internet Connection Test Effective .

Note:

BroadcastReceiver's of applications with targetSdkVersion or higher than API Level 24 (Android 7) will not receive this notification if declared in AndroidManifest.xml.

Your registration needs to be done explicitly using Context.registerReceiver () .

IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
connectivityChangeReceiver = new ConnectivityChangeReceiver();
registerReceiver(connectivityChangeReceiver, intentFilter);
    
23.09.2015 / 21:03
1

You can add a method to check your connection in the tbReceiver class as follows:

private boolean isNetworkAvaliable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

and your mainfest should have this permission:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Then you can check if you have a connection to an if:

if(isNetworkAvaliable()){
   //seu código aqui
}
    
23.09.2015 / 20:32
1

Good morning everyone! It's 2:30 in the morning and I got to understand this bagasse (I do not know if with the best practice, but it worked). First, I do not know if it is right for me to answer my question myself. If not, I'll fix it.

Well, come on: Firstly, I tried to use NetworkInfo [], but it does not seem to be used any more.

It's hard to put the credits of the solution that I implemented, because I went after a lot and I understood how things worked.

Well, to summarize I understood that what I needed initially was only from BroadcastReceiver, because it is he who will be "listening" to the event that will make him complete my method:

package com.teste.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

public class TbReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean conectado;

        ConnectivityManager conectivtyManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conectivtyManager.getActiveNetworkInfo() != null
                && conectivtyManager.getActiveNetworkInfo().isAvailable()
                && conectivtyManager.getActiveNetworkInfo().isConnected()) {
            conectado = true; //Aqui chamo o serviço que envia dados, por exemplo



        } else {
            conectado = false; //não faço nada, ou faço, não decidi ainda. (risos).
        }

    }
}

My manifest (only the reference to BCR:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

        <receiver
            android:name=".receiver.TbReceiver"
            android:enabled="true"
            android:permission="android.permission.ACCESS_NETWORK_STATE">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>

                <action android:name="DISPARA_EVENTO_X" />
            </intent-filter>
        </receiver>

And finally, the method that I put in my Activity to call (that is, pass a message, according to my teacher) to create an AlarmManager from my BroadcastReceiver:

public void chamarBroadcastReceiver(){

    boolean alarmeAtivo = (PendingIntent.getBroadcast(this, 0, new Intent("DISPARA_EVENTO_X"), PendingIntent.FLAG_NO_CREATE) == null);

    if(alarmeAtivo){

        Intent intent = new Intent("DISPARA_EVENTO_X");
        PendingIntent p = PendingIntent.getBroadcast(this, 0, intent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 3);

        AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarme.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5000, p);
    }
    else{
        onDestroy(); // chama o método onDestroy @Override da minha Activity
    }

}

Well, I hope it's not all bad, because as I said at the beginning, I'm learning Java and mobile development.

Big hug.

    
25.09.2015 / 07:32
0

So the response from @Luiz dev is not complete, as it checks to see if there is CONNECTIVITY (WIFI Networking CONNECTED or 3G), but that does not mean that you are connected to the internet. For you to detect, you should send some packet or a ping to some service.

Suggestion:

  • Check out luiz.
  • If you are connected, try to send the package.
  • If you return Status OK, it means that it sent correctly to
  • Good luck!

        
    23.09.2015 / 20:48