0

コードの一部を実行する前に、ユーザーがインターネット接続を利用できるかどうかを確認する簡単な方法があるかどうかを知りたいです。

インターネット接続を有効にせずに「壁紙の設定」をクリックすると、実行するものが何もないため「Nullpointerexception」が原因でアプリがクラッシュするため、これを知りたいです。

壁紙をダウンロードして設定する非同期タスククラスを開く前に、ユーザーがインターネット接続を有効にしているかどうかを確認するにはどうすればよいですか?

コード:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.SetWallpaper:

//Do something here that checks if the user has connection so if they don't, it won't execute this code here.

        new SaveWallpaperAsync(getActivity()).execute(mImageUrl);

        break;

    case R.id.SaveWallpaper:

//Do something here that checks if the user has connection so if they don't, it won't execute this code here.

        new SetWallpaperAsync(getActivity()).execute(mImageUrl);

        break;
    }
    return super.onOptionsItemSelected(item);
} 
4

5 に答える 5

0

これが私がした方法です。onCreate()インターネット接続を確認するアクティビティに次のコードを記述します。

        NetworkConnectivity.sharedNetworkConnectivity().configure(this); 
        NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor(); 
        NetworkConnectivity.sharedNetworkConnectivity() 
                .addNetworkMonitorListener(new NetworkMonitorListener() { 
                    @Override
                    public void connectionCheckInProgress() { 
                        // Okay to make UI updates (check-in-progress is rare) 
                    } 

                    @Override
                    public void connectionEstablished() { 
                        // Okay to make UI updates -- do something now that 
                        // connection is avaialble 


                    } 

                    @Override
                    public void connectionLost() { 
                        // Okay to make UI updates -- bummer, no connection 

                        Toast.makeText(getBaseContext(), "Connection lost. You cannot use Voice Input method.", Toast.LENGTH_LONG).show(); 


                    } 
                }); 

2 つの Java ファイルを作成します。

NetworkConnectivity.java

package com.connectivity; 

import java.util.ArrayList; 
import java.util.List; 

import android.app.Activity; 
import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.Handler; 

public class NetworkConnectivity { 

    private static NetworkConnectivity sharedNetworkConnectivity = null; 

    private Activity activity = null; 

    private final Handler handler = new Handler(); 
    private Runnable runnable = null; 

    private boolean stopRequested = false; 
    private boolean monitorStarted = false; 

    private static final int NETWORK_CONNECTION_YES = 1; 
    private static final int NETWORK_CONNECTION_NO = -1; 
    private static final int NETWORK_CONNECTION_UKNOWN = 0; 

    private int connected = NETWORK_CONNECTION_UKNOWN; 

    public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000; 
    public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000; 

    private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>(); 

    private NetworkConnectivity() { 
    } 

    public synchronized static NetworkConnectivity sharedNetworkConnectivity() { 
        if (sharedNetworkConnectivity == null) { 
            sharedNetworkConnectivity = new NetworkConnectivity(); 
        } 

        return sharedNetworkConnectivity; 
    } 

    public void configure(Activity activity) { 
        this.activity = activity; 
    } 

    public synchronized boolean startNetworkMonitor() { 
        if (this.activity == null) { 
            return false; 
        } 

        if (monitorStarted) { 
            return true; 
        } 

        stopRequested = false; 
        monitorStarted = true; 

        (new Thread(new Runnable() { 
            @Override
            public void run() { 
                doCheckConnection(); 
            } 
        })).start(); 

        return true; 
    } 

    public synchronized void stopNetworkMonitor() { 
        stopRequested = true; 
        monitorStarted = false; 
    } 

    public void addNetworkMonitorListener(NetworkMonitorListener l) { 
        this.networkMonitorListeners.add(l); 
        this.notifyNetworkMonitorListener(l); 
    } 

    public boolean removeNetworkMonitorListener(NetworkMonitorListener l) { 
        return this.networkMonitorListeners.remove(l); 
    } 

    private void doCheckConnection() { 

        if (stopRequested) { 
            runnable = null; 
            return; 
        } 

        final boolean connectedBool = this.isConnected(); 
        final int _connected = (connectedBool ? NETWORK_CONNECTION_YES 
                : NETWORK_CONNECTION_NO); 

        if (this.connected != _connected) { 

            this.connected = _connected; 

            activity.runOnUiThread(new Runnable() { 
                @Override
                public void run() { 
                    notifyNetworkMonitorListeners(); 
                } 
            }); 
        } 

        runnable = new Runnable() { 
            @Override
            public void run() { 
                doCheckConnection(); 
            } 
        }; 

        handler.postDelayed(runnable, 
                (connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS 
                        : MONITOR_RATE_WHEN_DISCONNECTED_MS)); 
    } 

    public boolean isConnected() { 
        try { 
            ConnectivityManager cm = (ConnectivityManager) activity 
                    .getSystemService(Context.CONNECTIVITY_SERVICE); 
            NetworkInfo netInfo = cm.getActiveNetworkInfo(); 

            if (netInfo != null && netInfo.isConnected()) { 
                return true; 
            } else { 
                return false; 
            } 
        } catch (Exception e) { 
            return false; 
        } 
    } 

    private void notifyNetworkMonitorListener(NetworkMonitorListener l) { 
        try { 
            if (this.connected == NETWORK_CONNECTION_YES) { 
                l.connectionEstablished(); 
            } else if (this.connected == NETWORK_CONNECTION_NO) { 
                l.connectionLost(); 
            } else { 
                l.connectionCheckInProgress(); 
            } 
        } catch (Exception e) { 
        } 
    } 

    private void notifyNetworkMonitorListeners() { 
        for (NetworkMonitorListener l : this.networkMonitorListeners) { 
            this.notifyNetworkMonitorListener(l); 
        } 
    } 

} 

NetworkMonitorListener.java

package com.connectivity; 

public interface NetworkMonitorListener { 

    public void connectionEstablished(); 
    public void connectionLost(); 
    public void connectionCheckInProgress(); 
} 

最後に、次の 2 行を に追加しますmanifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
于 2013-11-12T11:38:48.053 に答える
0

以下のようにしてみてください:

public static boolean IsNetConnected() {
    boolean NetConnected = false;

    try {
        ConnectivityManager connectivity = (ConnectivityManager) m_context
                .getSystemService(m_context.CONNECTIVITY_SERVICE);

        if (connectivity == null) {
            NetConnected = false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();

            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetConnected = true;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        NetConnected = false;
    }

    return NetConnected;
}

また、マニフェストにアクセス許可を追加します。

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

コードでは、次のようにします。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.SetWallpaper:

//Do something here that checks if the user has connection so if they don't, it won't execute this code here.
        if( IsNetConnected())
        {
            new SaveWallpaperAsync(getActivity()).execute(mImageUrl);
         }
        break;

    case R.id.SaveWallpaper:

//Do something here that checks if the user has connection so if they don't, it won't execute this code here.
        if( IsNetConnected())
        {
            new SetWallpaperAsync(getActivity()).execute(mImageUrl);
          }
        break;
    }
    return super.onOptionsItemSelected(item);
} 
于 2013-11-12T11:34:48.027 に答える
0

この方法を使用する

public static boolean checkInternetConnection(Context context)
{
    try
    {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        // ARE WE CONNECTED TO THE NET

        if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return false;
}

権限を追加します

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

あなたのマニフェストファイルで

于 2013-11-12T11:33:46.357 に答える