简体   繁体   English

尝试更改Android网络连接时应用崩溃

[英]App Crashes while trying to change the network connectivity android

In my app, I have created an activity where I am using a webview to show one web page. 在我的应用程序中,我创建了一个活动,正在使用Webview显示一个网页。 I have created a class named NetworkReceiver which extends BroadcastReceiver. 我创建了一个名为NetworkReceiver的类,该类扩展了BroadcastReceiver。 I am using this class to notify the user when there is no internet connection or when connecting again a mobile network or wifi connection. 我正在使用此类通知没有互联网连接或再次连接移动网络或wifi连接时的用户。 But the problem I am getting the app crashes for this network receiver when changing the network connectivity. 但是更改网络连接时,我遇到的问题是此网络接收器的应用程序崩溃。 Most surprising thing is this does not happen all the time. 最令人惊讶的是,这并非一直发生。 sometimes the app is completely closed and that time when I try to connect the internet, I am getting app crashing. 有时应用程序已完全关闭,而当我尝试连接互联网时,我崩溃了。 Here is my complete code for webview activity with network receiver class 这是我与网络接收器类进行webview活动的完整代码

public class JobPage extends AppCompatActivity {

public static WebView webView;
private static final String URL = "https://.....";


public static boolean refreshDisplay = true;

// The BroadcastReceiver that tracks network connectivity changes.
private NetworkReceiver receiver = new NetworkReceiver();

Constant constant;
SharedPreferences app_preferences;
int appTheme;
int themeColor;
int appColor;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.job_layout);

    webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl(URL);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient());

    // Registers BroadcastReceiver to track network connection changes.
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    receiver = new NetworkReceiver();
    this.registerReceiver(receiver, filter);

}

@Override
protected void onStop()
{
    unregisterReceiver(receiver);
    super.onStop();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == android.R.id.home) {
        finish();
    }
    return super.onOptionsItemSelected(item);
}

/**
 * Created by mnowshin on 16/08/2017.
 */

public static class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager conn = (ConnectivityManager)
                context.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conn.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // If device has its Wi-Fi connection, sets refreshDisplay
            // to true. This causes the display to be refreshed when the user
            // returns to the app.

            Toast.makeText(context, "Wi-fi is connected", Toast.LENGTH_SHORT).show();
            //JobPage.refreshDisplay = true;
            webView.reload();

            // If the setting is ANY network and there is a network connection
            // (which by process of elimination would be mobile), sets refreshDisplay to true.
        } else if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            Toast.makeText(context, "Mobile is connected", Toast.LENGTH_SHORT).show();
            //JobPage.refreshDisplay = true;
            webView.reload();

            // Otherwise, the app can't download content--either because there is no network
            // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
            // is no Wi-Fi connection.
            // Sets refreshDisplay to false.
        }
        else if (networkInfo != null &&  networkInfo.isConnectedOrConnecting()) {
            Toast.makeText(context, "Data is connected", Toast.LENGTH_SHORT).show();
            //JobPage.refreshDisplay = true;
            webView.reload();
        }
        else {
            refreshDisplay = false;
            Toast.makeText(context, "Your internet connection is not availbale", Toast.LENGTH_SHORT).show();
        }
    }
}

} }

 09-21 15:03:57.500 12346-12346/demo.app.com.bluapp_client_and D/TimaKeyStoreProvider: TimaSignature is unavailable
09-21 15:03:57.500 12346-12346/demo.app.com.bluapp_client_and D/ActivityThread: Added TimaKeyStore provider
09-21 15:03:57.650 12346-12346/demo.app.com.bluapp_client_and D/AndroidRuntime: Shutting down VM
09-21 15:03:57.650 12346-12346/demo.app.com.bluapp_client_and E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: demo.app.com.bluapp_client_and, PID: 12346
                                                                                java.lang.RuntimeException: Unable to start receiver demo.app.com.bluapp_client_and.activity.job.JobPage$NetworkReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.reload()' on a null object reference
                                                                                    at android.app.ActivityThread.handleReceiver(ActivityThread.java:3641)
                                                                                    at android.app.ActivityThread.access$2000(ActivityThread.java:221)
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                    at android.os.Looper.loop(Looper.java:158)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.reload()' on a null object reference
                                                                                    at demo.app.com.bluapp_client_and.activity.job.JobPage$NetworkReceiver.onReceive(JobPage.java:174)
                                                                                    at android.app.ActivityThread.handleReceiver(ActivityThread.java:3634)
                                                                                    at android.app.ActivityThread.access$2000(ActivityThread.java:221) 
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876) 
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                    at android.os.Looper.loop(Looper.java:158) 
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:7225) 
                                                                                    at java.lang.reflect.Method.invoke(Native Method) 
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Manifest 表现

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="demo.app.com.bluapp_client_and">
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="23" />

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



....

    <receiver android:name="demo.app.com.bluapp_client_and.activity.job.JobPage$NetworkReceiver">
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
</application>

I use this for internet connection 我用这个来上网

Create a class... 建立课程...

    public class InternetStatus {
    private static InternetStatus instance = new InternetStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static InternetStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

Then I can call it where ever in the app. 然后,我可以在应用程序中的任何位置调用它。

    if (InternetStatus.getInstance(getApplicationContext()).isOnline()) {
        //User is online
    } else {
        //User is not online
    }

It says Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.reload()' on a null object reference 它说原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.webkit.WebView.reload()'

May be this line is casusing problem.Check if the id is proper 可能是这行引起了问题。请检查ID是否正确

webView = (WebView) findViewById(R.id.webView);

Check for NullPointerException before loading webview befor doing operation 在执行操作之前加载webview之前检查NullPointerException

if(null!=webView){
 //Do the operation     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM