How to identify changing the state of connectivity to the Internet to perform a method when connecting?

Asked

Viewed 1,275 times

3

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

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

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

What I would like: I am developing together with colleagues from the facul, a localization system. The idea is to check from time to time if there is an internet connection. If you have connection and information from our app not sent, then we will send the data to a webservice or anywhere else we imagine. This way I did, every time I unlock the screen of the phone it just opens the map. (but that’s not what I want, because I want the service to remain active and when "waking up(check a condition and if it is true executes)" perform a method).

Summary:

I would like my service to start on the phone boot and be "listening" until there is an internet connection. When there is, then do something - in that case, perform a method that I determine (which I also don’t know where to stand).

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);


        }
    }

}

Meuservice is 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 down the stretch of my manifest:

<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 done a lot of research and I can’t figure out how to do it. I’ve looked at the documentation, but I don’t get it either. I’m starting out and a little lost in it.

I’m sorry to post this bunch of stuff, but I’m kind of detail-oriented.

Thank you.

  • I’ve done something similar and used the Observer design, will have to create a class that will be updated every time there is no internet connection or vice versa. Something of this kind of implementation : http://www.devmedia.com.br/padrao-projection-observer-java/26163

4 answers

3

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

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

and in your mainfest must have this permission:

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

Then you just check if you have connection with an if:

if(isNetworkAvaliable()){
   //seu código aqui
}
  • I couldn’t do it that way. I actually did, but it didn’t work. While I "wait" for more suggestions, I’ll keep looking on the internet. If I find something I put here. If anyone has any more tips I appreciate.

2

To be notified when a network connectivity status change(network) shall declare a Broadcastreceveir to respond to Action android.net.conn.CONNECTIVITY_CHANGE


On Androidmanifest.xml log the Broadcastreceveir: (See note)

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

The Broadcastreceveir will be something like:

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 network connection does not guarantee that you have access to the internet, see Test effective internet connection.

Note:

Broadcastreceiver’s of applications with targetSdkVersion equal to or above the Level 24 API (Android 7) will not receive this notification if declared on Androidmanifest.xml.

Your registration must be made explicitly using Context.registerReceiver().

IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
connectivityChangeReceiver = new ConnectivityChangeReceiver();
registerReceiver(connectivityChangeReceiver, intentFilter);
  • Good night! It didn’t work. Nothing happens. I implemented this way, deactivated or active the internet and just nothing happens.

  • In <receiver android:name=".ConnectivityChangeReceiver"> was missing the. before the class name, be sure to include the permission.

2

Good morning, you guys! It is 2:30 in the morning and I was able to understand this bagasse (I do not know if with the best practice, but it worked). First of all, I don’t know if it’s right for me to answer my question myself. If it’s not, I correct.

All right, here we go: First, I tried using Networkinfo[], but it seems not used anymore.

It is difficult to put the credits of the solution I implemented, because I went after a lot and I understood how things worked.

Well, to summarize I understood that what I initially needed was just the Broadcastreceiver, because it is he who will be "listening" to the event that will make him amaze 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 excerpt ref. 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 I put in my Activity to call (I mean, pass a message, according to my teacher) to create an Alarmmanager of 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.

  • Look man I tested your code n worked here not

1

So, the answer of @Luiz dev is not complete, because it checks if THERE IS CONNECTIVITY (WIFI NETWORK CONNECTED or 3G), but this does not mean that you are connected on the internet. In order for you to detect, you must send some package or ping to some service.

Suggestion:

  1. Do the Luiz check.
  2. If connected, try sending the package.
  3. If Return Status OK, it means that it sent correctly to

Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.