安卓传感器+WIFI+GPS

来源:互联网 发布:mac系统下载栏 编辑:程序博客网 时间:2024/06/09 22:56
package com.cnlgming.sensorsdemo;import android.Manifest;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.location.Criteria;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.location.LocationProvider;import android.net.Uri;import android.net.wifi.ScanResult;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.os.Build;import android.os.Bundle;import android.os.Environment;import android.os.SystemClock;import android.provider.Settings;import android.support.v4.app.ActivityCompat;import android.support.v7.app.AppCompatActivity;import android.widget.TextView;import android.widget.Toast;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import static android.content.Context.MODE_WORLD_READABLE;public class MainActivity extends AppCompatActivity implements SensorEventListener {    private TextView mTvOrientation;    private TextView mTvGyroscope;    private TextView mTvMagnetic;    private TextView mTvGravity;    private TextView mTvLinearAcceleration;    private TextView mTvProximity;    private TextView mTvLight;    private TextView mTvPressure;    private TextView mTvGps;    ///    WifiManager wifi;    List list;    TextView show;    String csum;    // Sensor 管理服务    private SensorManager mSensorManager;    int count =0;    /////////////////    File extDir= Environment.getExternalStorageDirectory() ;    String fileName1="fangXiangSensor.txt";    File fullFilename1 =new File(extDir,fileName1);    String fileName2="tuoLuoYiSensor.txt";    File fullFilename2 =new File(extDir,fileName2);    String fileName3="diCiSensor.txt";    File fullFilename3 =new File(extDir,fileName3);    String fileName4="zhongLiSensor.txt";    File fullFilename4 =new File(extDir,fileName4);    String fileName5 = "wifiInformation.txt";    File fullFilename5 = new File(extDir, fileName5);    String fileName6="xianJiaSuDuSensor.txt";    File fullFilename6 =new File(extDir,fileName6);    String fileName7="juLiSensor.txt";    File fullFilename7 =new File(extDir,fileName7);    String fileName8="guangXianSensor.txt";    File fullFilename8 =new File(extDir,fileName8);    String fileName9="qiYaJi.txt";    File fullFilename9 =new File(extDir,fileName9);    String fileName10="myGPS.txt";    File fullFilename10 =new File(extDir,fileName10);    //时间    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    private SimpleDateFormat sdfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");    private SimpleDateFormat sdfymd = new SimpleDateFormat("yyyyMMddHHmm");    //////    private LocationManager locationManager;    private String locateType;    private TextView textLocationShow;    /////    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        assignViews();        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);        //////        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);        textLocationShow = (TextView) findViewById(R.id.text_location_show);        getLocation();        //////    }    //////    private void getLocation() {        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {            // TODO: Consider calling            //    ActivityCompat#requestPermissions            // here to request the missing permissions, and then overriding            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,            //                                          int[] grantResults)            // to handle the case where the user grants the permission. See the documentation            // for ActivityCompat#requestPermissions for more details.            return;        }        locateType=locationManager.GPS_PROVIDER;        Location location = locationManager.getLastKnownLocation(locateType); // 通过GPS获取位置        if (location != null) {            updateUI(location);        }else{            updateUI2();        }        // 设置监听*器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米        locationManager.requestLocationUpdates(locateType, 500,0,locationListener);    }    private LocationListener locationListener = new LocationListener() {        @Override        public void onLocationChanged(Location location) {            //Toast.makeText(MainActivity.this, "位置更新", Toast.LENGTH_SHORT).show();            updateUI(location);        }        @Override        public void onStatusChanged(String provider, int status, Bundle extras) {            switch (status) {                //GPS状态为可见时                case LocationProvider.AVAILABLE:                    //Toast.makeText(MainActivity.this, "onStatusChanged:当前GPS状态为可见状态", Toast.LENGTH_SHORT).show();                    break;                //GPS状态为服务区外时                case LocationProvider.OUT_OF_SERVICE:                    Toast.makeText(MainActivity.this, "onStatusChanged:当前GPS状态为服务区外状态", Toast.LENGTH_SHORT).show();                    break;                //GPS状态为暂停服务时                case LocationProvider.TEMPORARILY_UNAVAILABLE:                    Toast.makeText(MainActivity.this, "onStatusChanged:当前GPS状态为暂停服务状态", Toast.LENGTH_SHORT).show();                    break;            }        }        @Override        public void onProviderEnabled(String provider) {            Toast.makeText(MainActivity.this, "GPS被打开", Toast.LENGTH_SHORT).show();            getLocation();        }        @Override        public void onProviderDisabled(String provider) {            Toast.makeText(MainActivity.this, "GPS被禁用", Toast.LENGTH_SHORT).show();        }    };    private void updateUI(Location location) {        Date date = new Date();        //File extDir= Environment.getExternalStorageDirectory() ;        double longitude = location.getLongitude();        double latitude = location.getLatitude();        double altitude=location.getAltitude();        double speed =location.getSpeed();        double bearing=location.getBearing();        double accuracy=location.getAccuracy();        textLocationShow.setText(longitude + "\n" + latitude+"\n" + altitude+"\n"+speed+"\n"+bearing+"\n"+accuracy);        ////////////        StringBuilder sb2 = null;        sb2 = new StringBuilder();        sb2.append( longitude + "   " + latitude+"   "+altitude+"   "+speed+"   "+bearing+"   "+accuracy+"\n");//以三个空格分开        try {            FileOutputStream outputStream = new FileOutputStream(fullFilename10,true);            String str = sdfm.format(date) +" "+ sb2.toString();            //mTvOrientation.setText(str);            outputStream.write(str.getBytes());            outputStream.close();        }catch (FileNotFoundException e) {            e.printStackTrace();            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();        } catch (IOException e) {            e.printStackTrace();            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();        }        ////////////    }    private void updateUI2() {        textLocationShow.setText("正在搜索GPS,需要等待");    }    //////    @Override    protected void onResume() {        super.onResume();        // 注册传感器监听器        // 方向传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),                SensorManager.SENSOR_DELAY_GAME);        // 陀螺仪传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),                SensorManager.SENSOR_DELAY_GAME);        // 磁场传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),                SensorManager.SENSOR_DELAY_GAME);        // 重力传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),                SensorManager.SENSOR_DELAY_GAME);        // 线性加速度传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),                SensorManager.SENSOR_DELAY_GAME);        // 温度传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE),                SensorManager.SENSOR_DELAY_GAME);        // 光线传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),                SensorManager.SENSOR_DELAY_GAME);        // 压力传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE),                SensorManager.SENSOR_DELAY_GAME);        //距离传感器        mSensorManager.registerListener(this,                mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),                SensorManager.SENSOR_DELAY_GAME);    }    @Override    protected void onDestroy() {        // 退出时取消传感器监听器        mSensorManager.unregisterListener(this);        super.onDestroy();    }    private void assignViews() {        mTvOrientation = (TextView) findViewById(R.id.tv_orientation);        mTvGyroscope = (TextView) findViewById(R.id.tv_gyroscope);        mTvMagnetic = (TextView) findViewById(R.id.tv_magnetic);        mTvGravity = (TextView) findViewById(R.id.tv_gravity);        mTvLinearAcceleration = (TextView) findViewById(R.id.tv_linear_acceleration);        mTvProximity = (TextView) findViewById(R.id.tv_proximity);        mTvLight = (TextView) findViewById(R.id.tv_light);        mTvPressure = (TextView) findViewById(R.id.tv_pressure);        //mTvGps=(TextView) findViewById(R.id.tv_gps);        ///        show =(TextView)findViewById(R.id.textView1);        ///    }    /**     * 传感器数值改变时的回调     *     * @param sensorEvent     */    @Override    public void onSensorChanged(SensorEvent sensorEvent) {        // 获取变化的传感器对应的数值        int type = sensorEvent.sensor.getType();        // 获取变化的值        float[] values = sensorEvent.values;        StringBuilder sb = null;        StringBuilder sb1 = null;        // 根据不同的传感器做出不同的响应        Date date = new Date();        switch (type) {            case Sensor.TYPE_ORIENTATION:                sb = new StringBuilder();                //sb.append("方向:");                //sb.append("\n绕 X 轴旋转的角度:");                sb.append(values[0]+" ");                //sb.append("\n绕 Y 轴旋转的角度:");                sb.append(values[1]+" ");                //sb.append("\n绕 Z 轴旋转的角度:");                sb.append(values[2]+"\n");                mTvOrientation.setText(sb.toString());                try {                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename1,true);                    String str = sdfm.format(date) +" "+ sb.toString();                    //mTvOrientation.setText(str);                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            case Sensor.TYPE_GYROSCOPE:                sb = new StringBuilder();                //sb.append("陀螺仪:");                //sb.append("\n绕 X 轴旋转的角速度:");                sb.append(values[0]+" ");                //sb.append("\n绕 Y 轴旋转的角速度:");                sb.append(values[1]+" ");                //sb.append("\n绕 Z 轴旋转的角速度:");                sb.append(values[2]+"\n");                mTvGyroscope.setText(sb.toString());                try {                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename2,true);                    String str = sdfm.format(date)+" " + sb.toString();                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            case Sensor.TYPE_MAGNETIC_FIELD:                sb = new StringBuilder();                //sb.append("磁场:");                //sb.append("\nX 轴上的磁场:");                sb.append(values[0]+" ");                //sb.append("\nY 轴上的磁场:");                sb.append(values[1]+" ");                //sb.append("\nZ 轴上的磁场:");                sb.append(values[2]+"\n");                mTvMagnetic.setText(sb.toString());                try {                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename3,true);                    String str = sdfm.format(date) +" "+ sb.toString();                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            case Sensor.TYPE_GRAVITY:                sb = new StringBuilder();                //sb.append("重力:");                //sb.append("\nX 轴方向上的重力:");                sb.append(values[0]+" ");                //sb.append("\nY 轴方向上的重力:");                sb.append(values[1]+" ");                //sb.append("\nZ 轴方向上的重力:");                sb.append(values[2]+"\n");                mTvGravity.setText(sb.toString());                try {                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename4,true);                    String str = sdfm.format(date)+" " + sb.toString();                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                count=count+1;//50*20ms=1s                if (count>=50) {                    wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);                    if (!wifi.isWifiEnabled()) {                        if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING)                            wifi.setWifiEnabled(true);                    }                    wifi.startScan();                    List<ScanResult> results = wifi.getScanResults();                    StringBuilder wifiinformation = new StringBuilder();                    //得到WIFI列表信息                    for (ScanResult result : results) {                        wifiinformation.append(result.BSSID);                        wifiinformation.append(" ");                        wifiinformation.append(result.level);                        wifiinformation.append(" ");                        //wifiinformation.append("\n");                    }                    WifiInfo info = wifi.getConnectionInfo();                    int strength = info.getRssi();                    int speed = info.getLinkSpeed();                    //String bssid = info.getBSSID();                    String ssid = info.getSSID();                    String units = WifiInfo.LINK_SPEED_UNITS;                    String text = "We connect" + ssid + " at " + String.valueOf(speed) + " " + String.valueOf(units) + ". Strength : " + strength;                    wifiinformation.append(" ");                    wifiinformation.append(text);                    //results.clear();                    show.setText(wifiinformation.toString());                    try {                        //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                        FileOutputStream outputStream = new FileOutputStream(fullFilename5, true);                        String str = sdfm.format(date) + " " + wifiinformation.toString() + "\n";                        //mTvOrientation.setText(str);                        outputStream.write(str.getBytes());                        outputStream.close();                    } catch (FileNotFoundException e) {                        e.printStackTrace();                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                    } catch (IOException e) {                        e.printStackTrace();                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                    }                    count=0;                }                break;            case Sensor.TYPE_LINEAR_ACCELERATION:                sb = new StringBuilder();                //sb.append("线性加速度:");                //sb.append("\nX 轴方向上的线性加速度:");                sb.append(values[0]+" ");                //sb.append("\nY 轴方向上的线性加速度:");                sb.append(values[1]+" ");                //sb.append("\nZ 轴方向上的线性加速度:");                sb.append(values[2]+"\n");                mTvLinearAcceleration.setText(sb.toString());                try {                    FileOutputStream outputStream = new FileOutputStream(fullFilename6,true);                    String str = sdfm.format(date) +" "+ sb.toString();                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            case Sensor.TYPE_PROXIMITY:                sb = new StringBuilder();                //sb.append("距离:");                //sb.append("\n当前的温度:");                sb.append(values[0]+" ");                mTvProximity.setText(sb.toString());                try {                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename7,true);                    String str = sdfm.format(date) +" "+ sb.toString()+"\n";                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            case Sensor.TYPE_LIGHT:                sb = new StringBuilder();                //sb.append("光线:");                //sb.append("\n当前的光线强度:");                sb.append(values[0]+" ");                mTvLight.setText(sb.toString());                try {//                    String fileName="guangXianSensor.txt";//                    File fullFilename6 =new File(extDir,fileName);                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename8,true);                    String str = sdfm.format(date) +" "+ sb.toString()+"\n";                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            case Sensor.TYPE_PRESSURE:                sb1 = new StringBuilder();                //sb1.append("气压计:");                //sb1.append("\n当前的压力:");                sb1.append(values[0]+" ");                mTvPressure.setText(sb1.toString());                try {                    String fileName="qiYaJi.txt";                    File fullFilename6 =new File(extDir,fileName);                    //FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_APPEND + MODE_WORLD_READABLE);                    FileOutputStream outputStream = new FileOutputStream(fullFilename9,true);                    String str = sdfm.format(date) +" "+ sb.toString()+"\n";                    outputStream.write(str.getBytes());                    outputStream.close();                }catch (FileNotFoundException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();                }                break;            default:                break;        }    }    /**     * 传感器精度改变时的回调     *     * @param sensor     * @param i     */    @Override    public void onAccuracyChanged(Sensor sensor, int i) {    }}
原创粉丝点击