0

I am newbie about sending notification. I have knowledge on AlarmManager and on showing notification when AlarmManager fires. I fetch some websites, collect information from that websites and insert them into my database on my hosting.

I plan to create an android application that sends some of these inserted information to users as soon as they have internet connection. Actually, what I want to achive exactly is sending notification like Facebook, Twitter or Instagram (You know, when you turn on your connection, comments, retweets, likes, mentions etc. notifications are sent in a minute ). I thought this can be done by checking user's connection every 2 or 5 minutes with a background task in AlarmManager but it doesn't look like good for battery. There should be some more professional or logical solution. Can you show me a way to achive this?

NOTE: I do not need connection control code. I just need to know which time range should i choose to check. Should I use alarmmanager or are there something else to manage the time range in background?

umitkilic
  • 327
  • 1
  • 4
  • 17
  • please have a look an previous answer , https://stackoverflow.com/questions/17053996/android-notification-at-time?rq=1 – Hemant Mali Nov 24 '17 at 11:52

3 Answers3

1

`You can add these lines to your manifest and make a receiver

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

and make a class as below

public class NetworkChangeReceiver extends BroadcastReceiver {

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

    if(checkInternet(context))
    {
        Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
    }

}

boolean checkInternet(Context context) {
    ServiceManager serviceManager = new ServiceManager(context);
    if (serviceManager.isNetworkAvailable()) {
        return true;
    } else {
        return false;
    }
}

}

public class ServiceManager {

Context context;

public ServiceManager(Context base) {
    context = base;
}

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}
  • Indeed, there is no need to perform a check every few minutes. By implementing the `BroadcastReceiver ` the `onReceive` method will be called every time a connection change is detected (every time the user connects or disconnects from a wireless network or mobile data). – Vlad Nov 24 '17 at 11:58
  • This will work for checking if there is network connection. But not if the network connection is connected to the internet. – ישו אוהב אותך Nov 24 '17 at 12:04
  • Yessss, this is what i looking for :) I will have to change "android.net.conn.connectivity_change" for N or higher android version. It is deprecated for N and higher one. Thanks for your code, you saved my day :) – umitkilic Nov 24 '17 at 12:20
0

You can check internet connectivity by adding this lines of code, and for better understanding, you should create a parent class of all activities and place this code there and extend Base Activity(Parent) in all child activities and every time it will execute when any activity gets created.

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

  • Actually, I want to know how i manage the checking time range. With AlarmManager every a few minutes or are there any way better. But thanks for code example. – umitkilic Nov 24 '17 at 11:22
0

Try the following code, I hope it will resolve your issue.

For reference: https://github.com/oscarjiv91/Android-Check-Internet-Connection

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

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class ConnectionService extends Service {

    // Constant
    public static String TAG_INTERVAL = "interval";
    public static String TAG_URL_PING = "url_ping";
    public static String TAG_ACTIVITY_NAME = "activity_name";

    private int interval;
    private String url_ping;
    private String activity_name;

    private Timer mTimer = null;

    ConnectionServiceCallback mConnectionServiceCallback;

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

    public interface ConnectionServiceCallback {
        void hasInternetConnection();
        void hasNoInternetConnection();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        interval = intent.getIntExtra(TAG_INTERVAL, 10);
        url_ping = intent.getStringExtra(TAG_URL_PING);
        activity_name = intent.getStringExtra(TAG_ACTIVITY_NAME);

        try {
            mConnectionServiceCallback = (ConnectionServiceCallback) Class.forName(activity_name).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new CheckForConnection(), 0, interval * 1000);

        return super.onStartCommand(intent, flags, startId);
    }

    class CheckForConnection extends TimerTask{
        @Override
        public void run() {
            isNetworkAvailable();
        }
    }

    @Override
    public void onDestroy() {
        mTimer.cancel();
        super.onDestroy();
    }

    private boolean isNetworkAvailable(){
        HttpGet httpGet = new HttpGet(url_ping);
        HttpParams httpParameters = new BasicHttpParams();

        int timeoutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        int timeoutSocket = 7000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        try{
            httpClient.execute(httpGet);
            mConnectionServiceCallback.hasInternetConnection();
            return true;
        }
        catch(ClientProtocolException e){
            e.printStackTrace();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        mConnectionServiceCallback.hasNoInternetConnection();
        return false;
    }

}

In your activity, where you want to start this service:

Intent intent = new Intent(this, ConnectionService.class);
    // Interval in seconds
    intent.putExtra(ConnectionService.TAG_INTERVAL, 100);
    // URL to ping
    intent.putExtra(ConnectionService.TAG_URL_PING, "http://www.google.com");
    // Name of the class that is calling this service
    intent.putExtra(ConnectionService.TAG_ACTIVITY_NAME, this.getClass().getName());
    // Starts the service
    startService(intent);

Implement ConnectionService.ConnectionServiceCallback on your activity and override the methods:

@Override
public void hasInternetConnection() {
   // has internet
}

@Override
public void hasNoInternetConnection() {
   // no internet :(
}

Stop the service

stopService(new Intent(this, ConnectionService.class));
Pankaj Mundra
  • 1,401
  • 9
  • 25
  • Actually, I want to know how i manage the checking time range. With AlarmManager every a few minutes or are there any way better. But thanks for code example. – umitkilic Nov 24 '17 at 11:22
  • @umitkilic please check my updated answer, and let me know this is what you are looking for. – Pankaj Mundra Nov 24 '17 at 11:33