如何从android中的其他类检查套接字状态?

时间:2016-06-10 05:42:07

标签: android sockets wifi

任何人都可以帮助我检查wifi套接字状态,即它是否与其他类/其他类服务连接。如果没有连接,那么如何连接到服务器。 以及如何检查wifi是否启用,如果没有,那么如何从其他服务类启用wifi。



package com.example.pci.calling;

import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    static   ToggleButton WiFiONOFFButton,ConnectWiFi;
     WifiManager wifi;
    WifiScanReceiver wifiReciever;
    String networkSSID = "EasyControl";
    String networkPass = "easy1234";

    static Button Asend,Vsend,Dsend,Connect;


    static    InputStream nis;
    static    OutputStream nos;

    static public      Socket socket;
    EditText editSend;
    static   TextView receivedata,Status;
    public    static Boolean socket_connect=false;
    public    static Boolean wifi_connect=false;

    TextView textInfo;


    final Context context = this;
    Dialog dialog;
    private PendingIntent pendingIntentOn,pendingIntentOff;
    Calendar calOn,calOff;

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

        ConnectWiFi = (ToggleButton) findViewById(R.id.connectwifi);
        WiFiONOFFButton = (ToggleButton) findViewById(R.id.toggleButton);
        Connect = (Button) findViewById(R.id.btnConnect1);
        Vsend = (Button) findViewById(R.id.btnVsend);
        Dsend = (Button) findViewById(R.id.btnDsend);
        Asend = (Button) findViewById(R.id.btnAsend);


        editSend = (EditText) findViewById(R.id.editSend);
        Status = (TextView) findViewById(R.id.status);
        receivedata = (TextView) findViewById(R.id.textView);

        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(true);
        wifiReciever = new WifiScanReceiver();
        wifi.startScan();



        ConnectWiFi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {


                    MyClienttask outer = new MyClienttask();
                    outer
                            .execute();


                } else {

                    try {
                        nis.close();
                        nos.close();
                        socket.close();
                    } catch (Exception e) {
                    }
                }

            }
        });
        Vsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    datasend();
                } catch (Exception e) {
                }
            }
        });


        Vsend.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                timer();
                Intent myIntentOn = new Intent(MainActivity.this, AlarmDetails.class);
                pendingIntentOn = PendingIntent.getService(MainActivity.this, 0, myIntentOn, 0);
                Intent myIntentoff = new Intent(MainActivity.this, AlarmDetailsoff.class);
                pendingIntentOff = PendingIntent.getService(MainActivity.this, 0, myIntentoff, 0);

                return false;
            }
        });

        if (wifi_connect==true){
            wifiReciever = new WifiScanReceiver();
        }
    }



    void datasend() throws IOException
    {
        nos.write("V".getBytes());
    }

    public void timer(){

        dialog = new Dialog(context);
        dialog.setContentView(R.layout.custom);
        dialog.setTitle("Set Prefer Time And Date");

        final RadioButton RadiobuttonOn = (RadioButton)dialog.findViewById(R.id.btn_radio_dialog_on);
        final RadioButton RadiobuttonOff = (RadioButton)dialog.findViewById(R.id.btn_radio_dialog_off);
        Button dialogOKbutton = (Button) dialog.findViewById(R.id.btn_dialog_ok);
        Button dialogCANCELbutton = (Button) dialog.findViewById(R.id.btn_dialog_cancel);
        final EditText txttime = (EditText) dialog.findViewById(R.id.dialog_time);
        final EditText txtdate = (EditText) dialog.findViewById(R.id.dialog_date);
        final Calendar newCalendar = Calendar.getInstance();

        if(RadiobuttonOn.isChecked()==true) {

            txtdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //  Calendar newCalendar = Calendar.getInstance();

                    DatePickerDialog mDatePicker;
                    mDatePicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                            Calendar calNow = Calendar.getInstance();
                            calOn = (Calendar) calNow.clone();
                            calOn.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                            calOn.set(Calendar.MONTH, monthOfYear);
                            calOn.set(Calendar.YEAR, year);
                            txtdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                        }
                    }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
                    mDatePicker.setTitle("Select Date");
                    mDatePicker.show();

                }
            });

            txttime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Calendar mycalender = Calendar.getInstance();
                    int hour = newCalendar.get(Calendar.HOUR_OF_DAY);
                    int minute = newCalendar.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker;

                    mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            txttime.setText(selectedHour + ":" + selectedMinute);

                            calOn.set(Calendar.HOUR_OF_DAY, selectedHour);
                            calOn.set(Calendar.MINUTE, selectedMinute);
                            calOn.set(Calendar.SECOND, 0);

                        }
                    }, hour, minute, true);//Yes 24 hour time
                    mTimePicker.setTitle("Select Time");
                    mTimePicker.show();
                }
            });

        }
        if (RadiobuttonOff.isChecked()==true){

            txtdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //  Calendar newCalendar = Calendar.getInstance();

                    DatePickerDialog mDatePicker;
                    mDatePicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                            Calendar calNow = Calendar.getInstance();
                            calOff = (Calendar) calNow.clone();
                            calOff.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                            calOff.set(Calendar.MONTH, monthOfYear);
                            calOff.set(Calendar.YEAR, year);
                            txtdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                        }
                    }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
                    mDatePicker.setTitle("Select Date");
                    mDatePicker.show();

                }
            });

            txttime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Calendar mycalender = Calendar.getInstance();
                    int hour = newCalendar.get(Calendar.HOUR_OF_DAY);
                    int minute = newCalendar.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker;

                    mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            txttime.setText(selectedHour + ":" + selectedMinute);

                            calOff.set(Calendar.HOUR_OF_DAY, selectedHour);
                            calOff.set(Calendar.MINUTE, selectedMinute);
                            calOff.set(Calendar.SECOND, 0);

                        }
                    }, hour, minute, true);//Yes 24 hour time
                    mTimePicker.setTitle("Select Time");
                    mTimePicker.show();
                }
            });

        }



        dialogOKbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
                //    Intent myIntent = new Intent(MainActivity.this, AlarmDetails.class);
                //   pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
                if (RadiobuttonOn.isChecked()==true) {
                    //   Intent myIntent = new Intent(MainActivity.this, AlarmDetails.class);
                    //   pendingIntentOn = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calOn.getTimeInMillis(), pendingIntentOn);
                }
                if (RadiobuttonOff.isChecked()==true) {
                    //    Intent myIntentoff = new Intent(MainActivity.this, AlarmDetailsoff.class);
                    //    pendingIntentOff = PendingIntent.getService(MainActivity.this, 0, myIntentoff, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calOn.getTimeInMillis(), pendingIntentOff);
                }





            }
        });
        dialogCANCELbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
                if (RadiobuttonOn.isChecked()==true){
                    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                    alarmManager.cancel(pendingIntentOn);
                }
                if (RadiobuttonOff.isChecked()==true){
                    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                    alarmManager.cancel(pendingIntentOff);
                }




            }
        });
        dialog.show();
    }



    public class WifiScanReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {
            List<ScanResult> wireless = wifi.getScanResults(); // Returns a <list> of scanResults
            for (ScanResult scan : wireless) {
                if (scan.SSID.equals("EasyControl")) {
                    boolean cont = true;
                    // WiFiONOFFButton.setChecked(true);

                    if (cont) {
                        WifiConfiguration wc = new WifiConfiguration();
                        wc.SSID = String.format("\"%s\"", networkSSID);
                        wc.preSharedKey = String.format("\"%s\"", networkPass);
                        wc.hiddenSSID = true;
                        wc.priority = 1;
                        wc.status = WifiConfiguration.Status.ENABLED;

                        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

                        int netid = wifi.addNetwork(wc);
                        wifi.enableNetwork(netid, true);
                        wifi.reconnect();
                    }
                }
            }

        }
    }

    protected void onPause() {
        unregisterReceiver(wifiReciever);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

 /*   public  void disableWifi(Context context,  Boolean bool) {
      //  WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if(bool)
            wifi.setWifiEnabled(false);
        else
            wifi.setWifiEnabled(true);


    public static boolean IsWiFiConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getTypeName().equals("WIFI")
                            && info[i].isConnected())
                        return true;
                }
            }
        }

        return false;
    } }*/


}
&#13;
&#13;
&#13;

在MyClienttask中

&#13;
&#13;
package com.example.pci.calling;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;


public class MyClienttask extends AsyncTask<Void, byte[], Void> {

    String dstAddress = "192.168.4.1";
    int dstPort = 666;
    String response = "";



    @Override
    protected Void doInBackground(Void... arg0) {

         MainActivity.socket = null;

        try {
            MainActivity.socket = new Socket(dstAddress, dstPort);

            if (MainActivity.socket.isConnected()) {
                MainActivity.socket_connect=true;
                //    Connect();
                //  Connect.setText("Disconnect");
            MainActivity.    nis = MainActivity.socket.getInputStream();
           MainActivity.     nos = MainActivity.socket.getOutputStream();
          MainActivity.      nos.write("A".getBytes());
                byte[] buffer = new byte[4096];
                int read =MainActivity. nis.read(buffer, 0, 4096);
                while (read != -1) {
                    byte[] tempdata = new byte[read];
                    System.arraycopy(buffer, 0, tempdata, 0, read);
                    publishProgress(new byte[][]{tempdata});
                    read = MainActivity.nis.read(buffer, 0, 4096);
                }
                //    datasend2();

            } else {
                MainActivity.socket_connect=false;
                //  Disconnect();
                // Status.setText("Disconnected");
                // btnConnect.setText("Disconnect");
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } finally {
            if (MainActivity.socket != null) {
                try {
                    MainActivity. socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    protected void onProgressUpdate(byte[]... values) {
        String toReceive;// = new String();

        try {
            toReceive = new String(values[0], "ISO-8859-1");
            MainActivity.receivedata.setText(toReceive);


        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
    }
}
&#13;
&#13;
&#13;

在AlarmDetails中

&#13;
&#13;
package com.example.pci.calling;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;


public class AlarmDetails extends Service {

    final Handler handler = new Handler();
    private Boolean stage =false;
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    String networkSSID = "EasyControl";
    String networkPass = "easy1234";
    WifiScanReceiver   wifiReciever;


    // Connection detector class
    ConnectionDetector cd;
    WifiManager wifi;

    @Override
    public void onCreate() {

// TODO Auto-generated method stub

        Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();

        MainActivity.Vsend.setText("OnCreate");


     //   cd = new ConnectionDetector(getApplicationContext());
    //    isInternetPresent = cd.isConnectingToInternet();
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        //   Intent intent = new Intent(this, MainActivity.class);
        //   PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// build notification
// the addAction re-use the same intent to keep the example short








    }



    @Override

    public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

        Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();

        return null;

    }







    @Override

    public void onStart(Intent intent, int startId) {

// TODO Auto-generated method stub

        super.onStart(intent, startId);

        if (wifi.isWifiEnabled()){

           MainActivity. wifi_connect=false;
        }else{
            wifi.setWifiEnabled(true);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 800ms



                }
            }, 100000);
           // MainActivity. wifi_connect=true;

        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 800ms

                wifiReciever = new WifiScanReceiver();
                wifi.startScan();

            }
        }, 100000);

        if (MainActivity.ConnectWiFi.isChecked()) {
            //  MainActivity.ConnectWiFi.setChecked(true);
            Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 800ms


                    MainActivity.Vsend.setText("OnStart");
                    MainActivity.Vsend.performClick();
                }
            }, 1000);


        }else {
            MainActivity.ConnectWiFi.performClick();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 800ms


                    MainActivity.Vsend.setText("OnStart1");
                    MainActivity.Vsend.performClick();
                    stage=true;
                }
            }, 1000);
        }

   /*     if (isInternetPresent) {
            MainActivity.Asend.setText("Hoche");
        }else{
            MainActivity.Asend.setText("Onno Vabe");
        }*/

        if (MainActivity.socket_connect == true){
            MainActivity.Asend.setText("Hoche");
        }else{
            MainActivity.Asend.setText("Onno Vabe");
        }

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        // .setSmallIcon(R.drawable.btswon)
                        .setContentTitle("My Notification Title")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("Something interesting happened");
        int NOTIFICATION_ID = 12345;

        Intent targetIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(NOTIFICATION_ID, builder.build());

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 800ms
                if(stage==false){
                    MainActivity.ConnectWiFi.setChecked(true); stopSelf();
                }else{
                    MainActivity.ConnectWiFi.setChecked(false); stopSelf();
                }


            }
        }, 1000);




    }



    @Override

    public boolean onUnbind(Intent intent) {

// TODO Auto-generated method stub

        Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();

        return super.onUnbind(intent);

    }


    @Override

    public void onDestroy() {

// TODO Auto-generated method stub

        super.onDestroy();



        Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
        MainActivity.Vsend.setText("Done");




    }

    public class WifiScanReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {
            List<ScanResult> wireless = wifi.getScanResults(); // Returns a <list> of scanResults
            for (ScanResult scan : wireless) {
                if (scan.SSID.equals("EasyControl")) {
                    boolean cont = true;
                    // WiFiONOFFButton.setChecked(true);

                    if (cont) {
                        WifiConfiguration wc = new WifiConfiguration();
                        wc.SSID = String.format("\"%s\"", networkSSID);
                        wc.preSharedKey = String.format("\"%s\"", networkPass);
                        wc.hiddenSSID = true;
                        wc.priority = 1;
                        wc.status = WifiConfiguration.Status.ENABLED;

                        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

                        int netid = wifi.addNetwork(wc);
                        wifi.enableNetwork(netid, true);
                        wifi.reconnect();
                    }
                }
            }

        }
    }


}
&#13;
&#13;
&#13;

这可能来自****公共类AlarmDetails扩展服务**** 1.连接特定的WiFi AP。 2.使用Alarm Manager我想向服务器发送一些数据,那时我怎么知道我的手机连接了特定的SSID,如果没有如何连接公共类AlarmDetails extends Service class

1 个答案:

答案 0 :(得分:0)

您可以使用ConnectivityManager检查wifi是否已连接,您必须在最清晰的文件中添加权限:

ConnectivityManager manager = (ConnectivityManager) this.getSystemService(this.CONNECTIVITY_SERVICE);
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
            if (isWifi) {

            }

清单中的权限:

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