应用程序打开前没有互联网连接的应用程序崩

时间:2016-10-30 11:21:25

标签: android

当我打开我的应用程序时,它会在吐司之前崩溃。我不知道应该如何使用我的方法isOnline()

public class Url_cont extends AsyncTask<String, Object, ArrayList<Movie>> {

    final String log_tag = Url_cont.class.getSimpleName();
    ArrayList<Movie> resultObj = new ArrayList<>();
    ICallBack myCallBack;
    private Context mContext;
    ProgressDialog progressDialog;

    public Url_cont(ICallBack NetworkCallBack, Context mContext) {
        myCallBack = NetworkCallBack;
        this.mContext = mContext;
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        return netinfo != null && netinfo.isConnectedOrConnecting();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (isOnline() != false) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setMessage("Please wait...");
            progressDialog.show();
        } else {
            Context context = mContext;
            CharSequence text = "check your internet connection!";
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }

    private ArrayList<Movie> formatMyJson(String jsonstr) throws JSONException {
        JSONObject object = new JSONObject(jsonstr);
        JSONArray mylist = object.getJSONArray("results");

        Movie mMovie;

        for (int i = 0; i < mylist.length(); i++) {
            mMovie = new Movie();
            JSONObject mynewob = mylist.getJSONObject(i);
            mMovie.setVote(mynewob.getString("vote_average"));
            mMovie.setTitle(mynewob.getString("original_title"));
            mMovie.setPoster_image(mynewob.getString("poster_path"));
            mMovie.setOverview(mynewob.getString("overview"));
            mMovie.setDate(mynewob.getString("release_date"));
            resultObj.add(mMovie);
        }
        return resultObj;
    }

    @Override
    protected ArrayList<Movie> doInBackground(String... params) {
        HttpURLConnection httpURLConnection = null;
        BufferedReader reader = null;
        String jsonstr = null;
        try {
            Uri builtUri = Uri.parse(params[0]).buildUpon().appendQueryParameter("api_key", BuildConfig.APIKRY).build();
            Log.i("url_site", builtUri.toString());
            URL uRl = new URL(builtUri.toString());
            httpURLConnection = (HttpURLConnection) uRl.openConnection();
            httpURLConnection.connect();

            int responseCode = httpURLConnection.getResponseCode();
            Log.i("ResponseCode", String.valueOf(responseCode));
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            jsonstr = response.toString();

        } catch (Exception e) {
            Log.e(log_tag, "this url has a problem 111");
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            return formatMyJson(jsonstr);
        } catch (Exception e) {
            Log.i(log_tag, "not thing work at alllllll");
        }
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Movie> strings) {
        progressDialog.dismiss();
        myCallBack.onPostExcuteCallBack(strings);
    }

}

此错误显示

10-30 07:11:44.420 3180-3180/com.massive.movieapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: com.massive.movieapp, PID: 3180
                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.massive.movieapp/com.massive.movieapp.MainActivity}: java.lang.SecurityException: ConnectivityService: Neither user 10060 nor current process has android.permission.ACCESS_NETWORK_STATE.
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                                    at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:136)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                    at java.lang.reflect.Method.invokeNative(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:515)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                    at dalvik.system.NativeStart.main(Native Method)
                                                                 Caused by: java.lang.SecurityException: ConnectivityService: Neither user 10060 nor current process has android.permission.ACCESS_NETWORK_STATE.
                                                                    at android.os.Parcel.readException(Parcel.java:1465)
                                                                    at android.os.Parcel.readException(Parcel.java:1419)
                                                                    at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.java:817)
                                                                    at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:565)
                                                                    at com.massive.movieapp.Url_cont.isOnline(Url_cont.java:41)
                                                                    at com.massive.movieapp.Url_cont.onPreExecute(Url_cont.java:49)
                                                                    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
                                                                    at android.os.AsyncTask.execute(AsyncTask.java:535)
                                                                    at com.massive.movieapp.FragmentForActivity.CallNetwork(FragmentForActivity.java:47)
                                                                    at com.massive.movieapp.FragmentForActivity.onCreate(FragmentForActivity.java:43)
                                                                    at android.app.Fragment.performCreate(Fragment.java:1678)
                                                                    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:859)
                                                                    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
                                                                    at android.app.BackStackRecord.run(BackStackRecord.java:684)
                                                                    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
                                                                    at android.app.Activity.performStart(Activity.java:5240)
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
                                                                    at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                    at android.os.Looper.loop(Looper.java:136) 
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5001) 
                                                                    at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                    at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
                                                                    at dalvik.system.NativeStart.main(Native Method) 

这是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.massive.movieapp">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@drawable/videoplayer"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

3 个答案:

答案 0 :(得分:1)

最后我解决了这个问题

    private void CallNetwork(String baseUrl) {
    if (NetworkUtils.isNetworkAvailable(getActivity())) {
        new Url_cont(this, getActivity()).execute(baseUrl);
    } else {
        CharSequence text = "check your internet connection!";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(getActivity(), text, duration);
        toast.show();
    }



 public static boolean isNetworkAvailable(Context mContext) {
    ConnectivityManager mConnectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    if (mNetworkInfo != null && mNetworkInfo.isConnected()) {
        return true;
    }
    return false;
}

我先把检查放在我的代码中做任何事情,谢谢你的帮助

答案 1 :(得分:0)

似乎,您忘记在android.permission.ACCESS_NETWORK_STATE中设置权限AndroidManifest.xml。你应该添加

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

与之相符。

答案 2 :(得分:0)

AndroidManifest.xml

中添加此行
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

以下是AndroidManifest.xml

的示例
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.new">

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

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon">

        <!-- Your Activities here -->
    </application>

</manifest>