从Android中的单独AsyncTask类连接WiFi Manager

时间:2014-09-13 22:19:03

标签: java android android-asynctask

我的应用程序使用AsyncTask使用WifiManager连接到WiFi 现在,我在我的MainActivity课程中使用此作为

public class connectWifi extends AsyncTask<Void, Void, Void> {
    private ProgressDialog dialog;

    public connectWifi(MyActivity activity) {
        dialog = new ProgressDialog(activity);
    }

    @Override
    protected void onPreExecute() {
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("Connecting to WiFi. Please Wait.");
        dialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        connected = true;
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo conn = wifi.getConnectionInfo();
        Context context = getApplicationContext();
        CharSequence wifi_on = "Connected to " + conn.getSSID();
        int duration = Toast.LENGTH_LONG;
        Toast responseToast = Toast.makeText(context, wifi_on, duration);
        responseToast.show();
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    protected Void doInBackground(Void... voids) {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(true);
        try {
            Thread.sleep(3000);
        } catch (Exception e) {

        }
        return null;
    }
}

现在,我有另一个类AlarmReceiver,它通过Broadcast调用。我正在该课程中执行一些基于网络的动作,这需要我先连接到WiFi 如何为connectWifi创建一个单独的类,该类不涉及首先运行MainActivity
我面临的问题是创建Context对象Non-static 'getApplicationContext()' cannot be referenced from static context 问题与getSystemService()相同。如何根据需要创建此类?


abcAsyncTaskAlarmReceiverBroadcastReceiver

我目前的控制流程如下:
开始程序
  - AlarmManager收到Broadcast
  - AlarmManager中的enableWifi()来电abc   - enableWifi()连接到WiFi   - AlarmManager检查连接状态
  - AlarmManager然后拨打new abc().execute("DATA1")
  - abc然后执行doInBackground任务(网络请求)
  - AlarmManagerdisableWifi()中拨打abc以结束WiFi 结束程序

1 个答案:

答案 0 :(得分:1)

您可以创建一个取决于Context的分隔类。 ActivityBroadcastReceiver都可以为此类提供Context

ActivityContext的子类,因此您可以将Activity作为参数传递。 来自onReceive的{​​{1}}的第一个参数是BroadcastReceiver

因此,您可以创建一个接收Context实例的类,并使用Context

WifiManager

您可以使用此类检测何时启用// This can run outside UI Thread public static void enableWifi(Context context) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(true); } // This must run on UI Thread public static void verifyWifi(Context context) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo conn = wifi.getConnectionInfo(); CharSequence wifi_on = "Connected to " + conn.getSSID(); int duration = Toast.LENGTH_LONG; Toast.makeText(context, wifi_on, duration).show(); } 或更改其状态。

Wifi

有了这个,我需要public class NetworkChangeReceiver extends BroadcastReceiver { // Static Listener, you can change this static OnNetworkConnectionChangedListener mListener; // Service to check if Wifi is connected or not ConnectivityManager mConnectivityManager; @Override public void onReceive(Context context, Intent intent) { if(mListener != null) { if(mConnectivityManager == null) { mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } mListener.onConnectionChanged(NetworkStatusHelper.getConnectivityStatus(mConnectivityManager) != NetworkStatusHelper.TYPE_NOT_CONNECTED); } } public static boolean isConnected(Context context) { return NetworkStatusHelper.getConnectivityStatus((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)) != NetworkStatusHelper.TYPE_NOT_CONNECTED; } public static void setOnNetworkConnectionChangedListener(OnNetworkConnectionChangedListener listener) { mListener = listener; } public interface OnNetworkConnectionChangedListener { public void onConnectionChanged(boolean connected); } } 权限。

ACCESS_NETWORK_STATE

我需要为<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> receiver

添加CONNECTIVITY_CHANGE
WIFI_STATE_CHANGED

通过此功能,您可以跟踪<receiver android:name="yourpackage.NetworkChangeReceiver" android:label="NetworkChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> 何时更改其连接并已连接。