I need a service in the background that constantly pings google. But I have no idea how to do it. I am new here. My method does not work does not repeat. It only works once and it always returns "false" .
isConnectedToServer function
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}}
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectedToServer("http://www.google.com",3000)){
Toast.makeText(this, "Okay", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Not Okay", Toast.LENGTH_SHORT).show();
}}
Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
I see Not Okay once on the screen. Only once. Even when I have an internet connection. What can I do about it?
try this create a class that extends AsyncTask
public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "CheckInternet";
private Context context;
public CheckInternet(Context context) {
this.context = context;
}
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "doInBackground: ");
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
if ( executeCommand()) return true;
}
return false;
}
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
Related
When I start the app I only see a white screen for about 15 seconds. I think this is because the asynctask is still trying to reach the server in the background although it is currently not online. Is there any way to solve the problem that the user gets a message saying that an attempt is being made to connect to the server or that a time limit is being introduced?
I have built this up so that at the beginning of the app a file is downloaded in which the latest version of a database is stored if it is larger than the one currently installed daas is downloaded in downloadAvailableDatabase() (I still have to do the last one).
Here are the important parts of the two files:
MainActivity.java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialization();
DataManager.Initialization(context);
}
DataManager.java
public static void Initialization(Context context){
try {
if (isNetworkAvailable(context)){
files_path = Objects.requireNonNull(context.getExternalFilesDir("")).toString();
IntegerDownloadTask integerDownloadTask = new IntegerDownloadTask();
Integer database_version = getDatabaseVersion(context);
Integer available_database_version = integerDownloadTask.execute(database_version_download_url).get();
if (database_version < available_database_version){
downloadAvailableDatabase();
}
}
} catch (Exception e){
Log.i("Error", e.toString());
}
}
private static Integer getDatabaseVersion(Context context){
File versionFile = new File(files_path, database_version_filename);
if(versionFile.exists()){
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(versionFile));
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
br.close();
return Integer.parseInt(stringBuilder.toString());
}
catch (Exception e) {
try {
FileOutputStream stream = new FileOutputStream(versionFile);
stream.write("0".getBytes());
stream.close();
} catch (Exception ignored){}
return 0;
}
} else {
try {
FileOutputStream stream = new FileOutputStream(versionFile);
stream.write("0".getBytes());
stream.close();
} catch (Exception ignored){}
return 0;
}
}
private static void downloadAvailableDatabase(){
}
private static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
} catch (Exception e){
return false;
}
}
you can do it by adding the progressBar in your activity
In your activity xml file add the following code:
<ProgressBar
android:id="#+id/simpleProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
then in OnCreate function in your activity initialise the progressBar and set the visibility as visible
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialization();
progressbar=findViewById(R.id.simpleProgressBar)
progressbar.setVisibility(View.VISIBLE)
DataManager.Initialization(context);
}
then in your async Task set the visibility of the progressBar to gone in onPostExecute Method
on Signin Button click I am performing the active internet connection check. But the Visibility is not working for the layout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
bar = (ProgressBar) this.findViewById(R.id.progressBar);
linearlayout = (LinearLayout) findViewById(R.id.SignInLinearLayout);
signin = (Button) findViewById(R.id.btn_signin);
user_name = (EditText) findViewById(R.id.Txt_Signin_Email);
user_password = (EditText) findViewById(R.id.Txt_signIn_Password);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearlayout.setVisibility(View.GONE);
bar.setVisibility(View.VISIBLE);
if (CommonFunctions.hasActiveInternetConnection(getBaseContext())) {
params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("username", user_name.getText().toString()));
params.add(new BasicNameValuePair("password", user_password.getText().toString()));
// Calling async task to get json
new GetLogIn_Details().execute();
} else {
bar.setVisibility(View.GONE);
linearlayout.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Network Not Available... \n Please check Your Wifi Connection or Mobile Network", Toast.LENGTH_LONG).show();
}
}
}
);
}
Here is the network check code
public abstract class CommonFunctions {
private static String LOG_TAG = "Network Message";
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
Boolean aResultM = isOnline();
return aResultM;
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Context _context) {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public static Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
The visibility is not working. But if i remove the network check code from the click event the visibility is working. How can i solve this issue. I found some hints like using delay method.But I don't want to use delay or timer method.Because the network check method itself take some time to execute.
I have an app that crashes when the wifi on phone goes out of range. It gets strings from an online txt mainly and I do disconnect the HTTPURLConnection after it gets done, so I was not expecting the crash. Below is the relevant code;
To check network availablity(all code that uses an internet connection gets checked by this first):
public boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
My checkForPromptPassword asynctask that runs on onResume:
private class CheckForPromptPasswordAgain extends AsyncTask<Void, Void, Boolean>
{
// ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
// pdLoading.setMessage("\tFetching Database...");
// pdLoading.show();
}
#Override
protected Boolean doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
//view GONE by default of update button
if (isNetworkAvailable()){
if (PromptForPasswordAgain()){
//TODO: //show update button or dialog
return true;
}else{
//TODO: //proceed as normal
return false;
}
}
return false;
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//this method will be running on UI thread
if (result==true){
promptForPassword();
}else{
// showDialog("string", "string",0);
}
// pdLoading.dismiss();
}
}
My checkForUpdate AsyncTask that runs on OnResume():
Private class CheckForUpdate extends AsyncTask<Void, Void, Boolean>
{
// ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
// pdLoading.setMessage("\t string.");
// pdLoading.show();
}
#Override
protected Boolean doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
//view GONE by default of update button
if (fileExistance("data.txt")){
try {
if (isNetworkAvailable()){
if (isDatabaseContentDifferent()){
//TODO: //show update button or dialog
return true;
}else{
//TODO: //proceed as normal
return false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.i("error","file data.txt does not exist in internal");
return false;
}
return false;
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//this method will be running on UI thread
Button updateButton = (Button) findViewById(R.id.UpdateDatabase);
updateButton.setVisibility(View.GONE);
if (result==true){
showDialog("Database Updated On Server", "The Database App has detected a change in the database, press \"Update Database\" to account for the change(s). ",0);
updateButton.setVisibility(View.VISIBLE);
}else{
updateButton.setVisibility(View.GONE);
// showDialog("No Update Detected", "The Database App has detected a change in the database, press \"Update Database\" to account for the change(s). ",0);
}
// pdLoading.dismiss();
}
}
Example of the HTTPURLClient that I am using, many functions but this is the basic structure:
public boolean isDatabaseContentDifferent() throws IOException{
String page = null;
try{
URL url = new URL(_data);
HttpURLConnection.setFollowRedirects(true);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(false);
con.setReadTimeout(20000);
con.setRequestProperty("Connection", "keep-alive");
//get etag for update check
//String etag= "";
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
((HttpURLConnection) con).setRequestMethod("GET");
//System.out.println(con.getContentLength()) ;
con.setConnectTimeout(5000);
BufferedInputStream in = new BufferedInputStream(con.getInputStream());
//make seperate function for etag it doesn't work with GET
//String etag = con.getHeaderField("etag");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println(responseCode);
}
StringBuffer buffer = new StringBuffer();
int chars_read;
//int total = 0;
while ((chars_read = in.read()) != -1)
{
char g = (char) chars_read;
buffer.append(g);
}
page = buffer.toString();
//create password.txt to internal
//TODO: checkkk
con.disconnect();
}catch(Exception e){
showDialog("Database Fetch Failure","Unable to Fetch Password Database, check your internet" +
" connection and try again later.",0);
Log.i("Page", "Error in isDatabaseContentDifferent()");
return false;
}
if (fileExistance("data.txt")){
if (isTextInFileDifferent(page,"data.txt")){
return true;
}else{
return false;
}
}else{
Log.i("Page","file data.txt does not exist IN isDatabaseContentDifferent()");
return false;
}
}
Any help will be highly appreciated. Thanks.
I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active Wifi connection is pretty simple using the connection manager however every time I try to test if I can connect to a website when the Wifi is connected but there is no internet connection I end up in an infinite loop.
I have tried to ping google however this ends up the same way:
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
returnVal = p1.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;
I also tried this code:
if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{ }
else
{ }
but I could not get isReachable to work.
It does works for me:
To verify network availability:
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
To verify internet access:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
I use this:
public static void isNetworkAvailable(Context context){
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try{
Log.d(TAG, "Checking network connection...");
httpClient.execute(httpGet);
Log.d(TAG, "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.d(TAG, "Connection unavailable");
}
It comes from an other stackoverflow answer but I can't find it.
EDIT:
Finally I found it: https://stackoverflow.com/a/1565243/2198638
Here is some modern code that uses an AsynTask to get around an issue where android crashes when you try and connect on the main thread and introduces an alert with a rinse and repeat option for the user.
class TestInternet extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("An internet connection is required.");
builder.setCancelable(false);
builder.setPositiveButton(
"TRY AGAIN",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new TestInternet().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
doMyStuff();
}
}
}
...
new TestInternet().execute();
To check if the android device is having an active connection, I use this hasActiveInternetConnection() method below that (1) tries to detect if network is available and (2) then connect to google.com to determine whether the network is active.
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
if (connectGoogle()) {
return true;
} else { //one more try
return connectGoogle();
}
} else {
log("No network available! (in hasActiveInternetConnection())");
return false;
}
}
public static boolean isNetworkAvailable(Context ct) {
ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
log("IOException in connectGoogle())");
return false;
}
}
Query a website like this:
Make your class implement AsyncTaskCompleteListenere<Boolean> by adding the following method to your class:
#Override
public void onTaskComplete(Boolean result) {
Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show();
// continue your job
}
Add a simple testConnection method to your class to be called when you want to check for your connectivity:
public void testConnection() {
URLExistAsyncTask task = new URLExistAsyncTask(this);
String URL = "http://www.google.com";
task.execute(new String[]{URL});
}
And finally the URLExistAsyncTask class which perform the connectivity test as an asynchronous (background) task and calls back your onTaskComplete method once done:
public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> {
AsyncTaskCompleteListenere<Boolean> callback;
public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) {
this.callback = callback;
}
protected Boolean doInBackground(String... params) {
int code = 0;
try {
URL u = new URL(params[0]);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
code = huc.getResponseCode();
} catch (IOException e) {
return false;
} catch (Exception e) {
return false;
}
return code == 200;
}
protected void onPostExecute(Boolean result){
callback.onTaskComplete(result);
}
}
I did use this method. It worked for me! For people who want to get the real Internet!
public boolean isOnline() {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
httpURLConnection.setRequestProperty("User-Agent", "Test");
httpURLConnection.setRequestProperty("Connection", "close");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.connect();
return (httpURLConnection.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
For doing this method every time! Just use a receiver
and =>
httpURLConnection.getResponseCode() == 200
This means the Internet is connected!
You can do it by create new parallel thread that count time :
final class QueryClass {
private int responseCode = -1;
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if(url == null) {
return null;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000 );
urlConnection.setConnectTimeout(5000 );
Thread thread = new Thread() {
#Override
public void run() {
super.run();
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(responseCode == -1) {
//Perform error message
Intent intent = new Intent(context,ErrorsActivity.class);
intent.putExtra("errorTextMessage",R.string.errorNoInternet);
intent.putExtra("errorImage",R.drawable.no_wifi);
context.startActivity(intent);
}
}
};
thread.start();
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
i want to ask a question which may is very simple for some of you.
How can i figure out, whether my Application has an internet connection?
I want to connect to an MySQL Database and when there is no Internet, there should be an AlertDialog.
new AsyncTask() {
ProgressDialog dialog = ProgressDialog.show(AppActivity.this, "Lade", "Daten werden abgerufen...", true);
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
max = Name.size()-1;
kontrolle = new boolean [max*2];
pb.setMax(max/2);
java.util.Arrays.fill(kontrolle, false);
bilder();
}
#Override
protected Object doInBackground(Object... arg0)
{
// TODO Auto-generated method stub
dialog.show();
getData();
return null;
}
}.execute();
private void getData()
{
String result = "";
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://.../read.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = "";
while((line= reader.readLine())!=null)
{
sb.append(line+"n");
}
is.close();
result = sb.toString();
result.trim();
}
catch(Exception e)
{
Log.e("log-tag","Error"+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
ID.add((String) json_data.get("id"));
Name.add((String) json_data.get("name"));
Pts.add((String)json_data.get("pts"));
}
}
catch(Exception e)
{
Log.e("log-tag","Error2"+e.toString());
}
}
How can i achieve that? i have no idea
i thought this
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
would do the work, but when i have no connection (because i set my phone in flight mode) there is just an endless ProgressDialog :(
As Jon Taylor mentioned this is a duplicate question
you can use the following code to do this
this method checks whether mobile is connected to internet and returns true if connected and displays an alert box if not:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
AlertDialog.Builder altDialog= new AlertDialog.Builder(this);
altDialog.setMessage("No network connection!");
return false;
} else
return true;
}
add this to the manifest file,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
EDIT: To get the network type you can use this code snippet:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}