unfortunately app is getting stopped while checking for network
Asked Answered
D

3

19

I am using the following code to check for the internet connection through out my app.

public class ConnectionChangeReceiver extends BroadcastReceiver
{
  @Override
  public void onReceive( Context context, Intent intent )
  {
    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService( Context.CONNECTIVITY_SERVICE );
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE );

    if (activeNetInfo != null)
    {
        Toast.makeText( context, "Active Network Type : " + 
                       activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
    if(mobNetInfo != null)
    {
        Toast.makeText( context, "Mobile Network Type : " + 
                          mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
    }
  }
}

And I have defined required permission in the manifest file.

Whenever I try to disconnect / connect the network using F8 key I will receive "UNFORTUNATELY APP HAS STOPPED", and I am not getting any print in logcat.

Can I know what is the mistake I am doing?

Dumbwaiter answered 21/3, 2013 at 11:50 Comment(2)
post your logcat error.Carty
@Carty no logcat error i am gettingDumbwaiter
C
65

NOTE: If you're targeting android N Preview. Above receiver will not work as per constrained restricted by Google.

Link: https://developer.android.com/preview/features/background-optimization.html#connectivity-action

Use: WorkManager or JobScheduler for same.


Have you added this in AndroidManifest.xml?

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

if you have added above then check this code:

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

and

public class UpdateReceiver extends BroadcastReceiver {

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

          ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE );
          NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
          boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();   
          if (isConnected)       
              Log.i("NET", "Connected" + isConnected);   
          else 
              Log.i("NET", "Not Connected" + isConnected);
    }
}

Calvaria answered 21/3, 2013 at 11:58 Comment(10)
i have added the below statements in my manifest file. <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> But still getting that problemDumbwaiter
it's same problem.. i have added reciever in manifest file before onlyDumbwaiter
now in logcat i got the following error '03-21 12:13:01.340: E/chromium(801): external/chromium/net/disk_cache/entry_impl.cc:904: [0321/121301:ERROR:entry_impl.cc(904)] Failed to save user data 03-21 12:13:01.340: E/chromium(801): external/chromium/net/disk_cache/entry_impl.cc:904: [0321/121301:ERROR:entry_impl.cc(904)] Failed to save user data 'Dumbwaiter
its working fine at my END. i have checked your code. check log : 03-21 18:03:42.795: I/NET(1607): connectetrue 03-21 18:04:08.415: I/NET(1607): not connectefalse 03-21 18:04:17.295: I/NET(1607): connectetrueCalvaria
thanks it's working now. but once if disconnect and connect i am not getting any logs in logcat and each time i need to close the old AVD and need to open new AVD. why is this problem?.Dumbwaiter
i have used the above code. but the toast message is getting displayed in other apps also. how can i avoid it. thanks:)Dumbwaiter
thanks:). but if i remove toast will i be notified about the status of network in my entire application?Dumbwaiter
i have made something similar.. like public class MyApplication extends Application { private static Context context; public void onCreate(){ super.onCreate(); MyApplication.context = getApplicationContext(); } public static Context getAppContext() { return MyApplication.context; } } and displaying toast as Toast.makeText(MyApplication.getAppContext(), "net Connected", Toast.LENGTH_LONG) .show(); but still i am facing that problem.Dumbwaiter
yu have to make one static class in your app. in that class create one variable.. like appisrunning = false; now, in your all activity oncreate do myclassname.appisrunning = true; and in onDestroy myclassname.appisrunning = false; and in broadcast if(myclassname.appisrunning){ show toast }.Calvaria
'public boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } return false; }'Spurgeon
P
6

The above code was not properly working for wi-fi connection. This is the Modified

SIMPLE ONE

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

inside application tag of androidmanifest.xml

<receiver android:name="android.YOUR-JAVA-CLASS-PATH.BackgroundSync" android:enabled="true">
      <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
      </intent-filter>
</receiver>

BackgroundSync.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager; 
import android.util.Log;
import android.widget.Toast;

public class BackgroundSync extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { 
        ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo()!=null){
            Toast.makeText(context, "Connected to Internet", Toast.LENGTH_LONG).show();
        }
        else Log.i("INTERNET","---------------------> Internet Disconnected. ");
    }
}
Phebe answered 6/5, 2016 at 7:7 Comment(0)
G
1

Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

https://developer.android.google.cn/reference/android/net/ConnectivityManager.html?hl=zh-cn#CONNECTIVITY_ACTION

Gilmour answered 5/7, 2017 at 4:4 Comment(1)
Please don't post the same answer to more than one question. If the questions are basically the same, flag them as duplicates. Otherwise, customize the answer to the question. (Also, posts that are nothing but a quote are often less than helpful. Also also, all quotes must be formatted so it's clear what you're quoting; otherwise you're plagiarizing by misrepresenting what you wrote.)Morelock

© 2022 - 2024 — McMap. All rights reserved.