package com.xypower.mpapp; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Environment; import android.os.FileObserver; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.core.app.ActivityCompat; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Toast; import com.dowse.camera.client.DSCameraManager; import com.xypower.mpapp.databinding.ActivityMainBinding; import com.xypower.mpapp.utils.RandomReader; //import com.xinyingpower.microphoto.request.INettyMessageListener; //import com.xinyingpower.microphoto.request.NettyChatClient; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { public static final String TAG = "MainActivity"; private static int MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE = 100; public static final int MSG_WHAT_LOG_OBSERVER = MicroPhotoService.MSG_WHAT_MAX + 10; public final static int DEFAULT_PROTOCOL = 0xFF00; // Used to load the 'microphoto' library on application startup. static { System.loadLibrary("microphoto"); } private ActivityMainBinding binding; private int defaultDataSubId; private Handler mHandler = null; private Messenger mMessenger = null; private LogFileObserver mLogFileObserver = null; private class LogFileObserver extends FileObserver { private long mOffset = 0; private String mPath = null; public LogFileObserver(String path) { super(path, FileObserver.MODIFY | FileObserver.CREATE); mPath = path; File file = new File(path); if (file.exists()) { mOffset = file.length(); } } @Override public void onEvent(int event, String s) { int e = event & FileObserver.ALL_EVENTS; if (e == FileObserver.MODIFY) { File file = new File(mPath); long newOffset = file.length(); if (newOffset > mOffset) { RandomReader reader = new RandomReader(mPath, mOffset); byte[] bytes = new byte[(int)(newOffset - mOffset)]; int bytesRead = reader.read(bytes); mOffset += bytesRead; Message msg = Message.obtain(); msg.what = MSG_WHAT_LOG_OBSERVER; msg.obj = bytes; msg.arg1 = bytesRead; mHandler.sendMessage(msg); } } } } public static class AppConfig { public String cmdid; public String server; public int port; public int protocol; public int networkProtocol; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(actionBar.getTitle().toString() + " " + getVersionName(getApplicationContext())); binding.logs.setText(""); binding.logs.setMovementMethod(ScrollingMovementMethod.getInstance()); binding.logs.setScrollbarFadingEnabled(false); // binding.logs.setMaxLines(16); mHandler = new Handler(Looper.myLooper()) { @Override public void handleMessage(@NonNull Message msg) { switch (msg.what) { case MicroPhotoService.MSG_WHAT_LOG: { String log = (String) msg.obj; binding.logs.append(log); // Reply // Messenger clientMessenger = msg.replyTo; // Message replyMessage = Message.obtain(null, 2); // 设置回复消息中的数据 Bundle replyData = new Bundle(); replyData.putString("key", "reply value"); // replyMessage.setData(replyData); /* try { clientMessenger.send(replyMessage); } catch (RemoteException e) { e.printStackTrace(); } */ } break; case MSG_WHAT_LOG_OBSERVER: { byte[] bytes = (byte[])msg.obj; int bytesRead = msg.arg1; String log = null; try { log = new String(bytes, 0, bytesRead, "UTF-8"); } catch (Exception e) { } if (log != null) { binding.logs.append(log); int line = binding.logs.getLineCount(); // if (line > 9) {//超出屏幕自动滚动显示(9是当前页面显示的最大行数) int offset = line * binding.logs.getLineHeight(); if (offset > binding.logs.getHeight()) { binding.logs.scrollTo(0, offset - binding.logs.getHeight() + binding.logs.getLineHeight()); } // } } } break; } } }; mMessenger = new Messenger(new Handler()); WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); Display defaultDisplay = windowManager.getDefaultDisplay(); int width = defaultDisplay.getWidth(); int height = defaultDisplay.getHeight(); Intent intent = getIntent(); final int noDelay = intent.getIntExtra("noDelay", 0); int rebootFlag = intent.getIntExtra("reboot", 0); if (rebootFlag == 1) { // SysApi.enableAirPlane(MainActivity.this, true); } Log.d(TAG, "MainActivity: reboot=" + rebootFlag + " noDelay=" + noDelay); String cmdid = ""; String server = ""; Integer port = new Integer(6891); Integer protocol = new Integer(DEFAULT_PROTOCOL); // 0xFF00 AppConfig appConfig = getAppConfig(); binding.cmdid.setText(appConfig.cmdid); binding.server.setText(appConfig.server); binding.port.setText(appConfig.port != 0 ? Integer.toString(appConfig.port) : ""); String protocolStr = appConfig.protocol + "-"; for (int idx = 0; idx < binding.protocol.getCount(); idx++) { String item = binding.protocol.getItemAtPosition(idx).toString(); if (item.startsWith(protocolStr)) { binding.protocol.setSelection(idx); break; } } if (appConfig.networkProtocol < binding.networkProtocol.getCount()) { binding.networkProtocol.setSelection(appConfig.networkProtocol); } this.binding.startServBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String[] accessPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.FOREGROUND_SERVICE, Manifest.permission.READ_PHONE_STATE, /*Manifest.permission.PACKAGE_USAGE_STATS,*/ /*Manifest.permission.SET_TIME,*/}; boolean needRequire = false; for (String access : accessPermissions) { int curPermission = ActivityCompat.checkSelfPermission(MainActivity.this, access); if (curPermission != PackageManager.PERMISSION_GRANTED) { needRequire = true; break; } } if (needRequire) { ActivityCompat.requestPermissions(MainActivity.this, accessPermissions, MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE); return; } AppConfig curAppConfig = retrieveAndSaveAppConfig(); startMicroPhotoService(MainActivity.this, appConfig); binding.startServBtn.setEnabled(false); binding.stopServBtn.setEnabled(true); } }); this.binding.saveCfg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { retrieveAndSaveAppConfig(); } }); this.binding.takePhotoBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MicroPhotoService.takePhoto(MainActivity.this.getApplicationContext(), 1, 255, true); } }); this.binding.takePhotoBtn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MicroPhotoService.takePhoto(MainActivity.this, 2, 255, true); } }); this.binding.takePhotoBtn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MicroPhotoService.takePhoto(MainActivity.this, 3, 255, true); } }); this.binding.takePhotoBtn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MicroPhotoService.takePhoto(MainActivity.this, 4, 255, true); } }); this.binding.stopServBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, MicroPhotoService.class); intent.setAction(MicroPhotoService.ACTION_STOP); MainActivity.this.stopService(intent); binding.startServBtn.setEnabled(true); binding.stopServBtn.setEnabled(false); } }); binding.simchange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { defaultDataSubId = getDefaultDataSubId(); System.out.println(defaultDataSubId); } }); binding.simchange2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (defaultDataSubId == 0) { setDefaultDataSubId(1); } else { if (defaultDataSubId == 1) { setDefaultDataSubId(2); } else { setDefaultDataSubId(1); } } } }); binding.btnChannels.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ChannelActivity.class); startActivity(intent); } }); binding.gps.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // gpsTake(); startLocate(); // LocationUtils.unregister(); } }); binding.netgps.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // startLocate(); boolean gpsEnabled = LocationUtil.isGpsEnabled(MainActivity.this); System.out.printf("g" + gpsEnabled); LocationUtil.register(MainActivity.this, 0, 0, new LocationUtil.OnLocationChangeListener() { @Override public void getLastKnownLocation(Location location) { Log.e("xyh", "onLocationChanged: " + location.getLatitude()); } @Override public void onLocationChanged(Location location) { //位置信息变化时触发 Log.e("xyh", "定位方式:" + location.getProvider()); Log.e("xyh", "纬度:" + location.getLatitude()); Log.e("xyh", "经度:" + location.getLongitude()); Log.e("xyh", "海拔:" + location.getAltitude()); Log.e("xyh", "时间:" + location.getTime()); Log.e("xyh", "国家:" + LocationUtil.getCountryName(MainActivity.this, location.getLatitude(), location.getLongitude())); Log.e("xyh", "获取地理位置:" + LocationUtil.getAddress(MainActivity.this, location.getLatitude(), location.getLongitude())); Log.e("xyh", "所在地:" + LocationUtil.getLocality(MainActivity.this, location.getLatitude(), location.getLongitude())); Log.e("xyh", "所在街道:" + LocationUtil.getStreet(MainActivity.this, location.getLatitude(), location.getLongitude())); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { System.out.println("dfsad"); } }); } }); if (!TextUtils.isEmpty(appConfig.cmdid) && !TextUtils.isEmpty(appConfig.server) && appConfig.port != 0) { Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { if (binding.startServBtn.isEnabled()) { binding.startServBtn.performClick(); } } }; handler.postDelayed(runnable, noDelay != 0 ? 100 : 5000); } binding.tcpudp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // initSocket(); } }); binding.tcpudpsend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // byte[] bytes = {(byte) 0xA5, 0x5A, 0x04, 0x00, 0x58, 0x59, 0x49, 0x47, 0x51, 0x31, 0x30, 0x44, 0x32, 0x32, 0x31, 0x30, 0x30, 0x30, 0x31, 0x30, 0x30, 0x07, (byte) 0xE7, 0x37, (byte) 0x86, (byte) 0x96, (byte) 0xD4, 0x64, (byte) 0xB5, (byte) 0xFB, (byte) 0x96}; byte[] bytes = {(byte) 0xA5, 0x5A, 0x04, 0x00, 0x58, 0x59, 0x49, 0x47, 0x51, 0x31, 0x30, 0x44, 0x32, 0x32, 0x31, 0x30, 0x30, 0x30, 0x31, 0x30, 0x30, 0x07, (byte) 0xE6, (byte) 0xEA, 0x52, (byte) 0xB7, (byte) 0xD4, 0x64, 0x5C, 0x7E, (byte) 0x96}; // NettyChatClient.getInstance().sendByteMessage(bytes); } }); binding.video.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //方法1 // mediaRecorder = new MediaRecorder(); // // //设置视频和音频的来源 // mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // // // mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // //设置录制视频的编码格式 // mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); // //设置音频的编码格式 // mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB); // //设置视频的帧率:每秒切换图片的次数 // mediaRecorder.setVideoFrameRate(20); // //视频的分辨率 // mediaRecorder.setVideoSize(176, 144); // //// mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface()); // // mediaRecorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/111.mp4"); // try { // mediaRecorder.prepare(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // mediaRecorder.start(); } }); binding.video2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // mediaRecorder.stop(); } }); } public static void startMicroPhotoService(Context context, AppConfig curAppConfig) { if (TextUtils.isEmpty(curAppConfig.cmdid) || TextUtils.isEmpty(curAppConfig.server) || curAppConfig.port == 0) { return; } Intent intent = new Intent(context, MicroPhotoService.class); intent.setAction(MicroPhotoService.ACTION_START); intent.putExtra("cmdid", curAppConfig.cmdid); intent.putExtra("server", curAppConfig.server); intent.putExtra("port", curAppConfig.port); intent.putExtra("protocol", curAppConfig.protocol); intent.putExtra("networkProtocol", curAppConfig.networkProtocol); // intent.putExtra("messenger", mMessenger); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); } } @Override protected void onStart() { // call the superclass method first super.onStart(); String logFilePath = MicroPhotoService.buildAppDir(this.getApplicationContext()); logFilePath += "logs/log.txt"; mLogFileObserver = new LogFileObserver(logFilePath); mLogFileObserver.startWatching(); } @Override protected void onStop() { // call the superclass method first super.onStop(); if (mLogFileObserver != null) { mLogFileObserver.stopWatching(); mLogFileObserver = null; } } @Override protected void onDestroy() { super.onDestroy(); } private void setDefaultDataSubId(int subId) { SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE); try { Method method = subscriptionManager.getClass().getDeclaredMethod("setDefaultDataSubId", int.class); method.invoke(subscriptionManager, subId); TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); Method method1 = telephonyManager.getClass().getDeclaredMethod("setDataEnabled", boolean.class); method1.invoke(telephonyManager, true); } catch (Exception e) { Log.e(TAG, "wjz debug setDefaultDataSubId: error is " + e.getMessage()); } } private AppConfig retrieveAndSaveAppConfig() { AppConfig appConfig = new AppConfig(); appConfig.cmdid = MainActivity.this.binding.cmdid.getText().toString(); appConfig.server = MainActivity.this.binding.server.getText().toString(); String portStr = MainActivity.this.binding.port.getText().toString(); appConfig.port = TextUtils.isEmpty(portStr) ? 0 : Integer.parseInt(portStr); String protocolStr = MainActivity.this.binding.protocol.getSelectedItem().toString(); appConfig.protocol = DEFAULT_PROTOCOL; String[] parts = protocolStr.split("-"); if (parts != null) { appConfig.protocol = Integer.parseInt(parts[0]); } appConfig.networkProtocol = MainActivity.this.binding.networkProtocol.getSelectedItemPosition(); saveAppConfig(appConfig.cmdid, appConfig.server, appConfig.port, appConfig.protocol, appConfig.networkProtocol); return appConfig; } private AppConfig getAppConfig() { return getAppConfig(this.getApplicationContext()); } public static AppConfig getAppConfig(Context context) { AppConfig appConfig = new AppConfig(); String appPath = MicroPhotoService.buildAppDir(context); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStreamReader = new InputStreamReader(new FileInputStream(new File(appPath + "data/App.json")), "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } JSONObject jsonObject = new JSONObject(stringBuilder.toString()); appConfig.cmdid = jsonObject.getString("CMDID"); appConfig.server = jsonObject.getString("Server"); appConfig.port = jsonObject.getInt("Port"); appConfig.protocol = jsonObject.getInt("Protocol"); appConfig.networkProtocol = jsonObject.getInt("NetworkProtocol"); if (appConfig.protocol == 0) { appConfig.protocol = DEFAULT_PROTOCOL; } } catch (UnsupportedEncodingException e) { // e.printStackTrace(); } catch (IOException e) { // e.printStackTrace(); } catch (JSONException e) { // e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception ex) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (Exception ex) { } } } return appConfig; } private void saveAppConfig(String cmdid, String server, int port, int protocol, int networkProtocol) { String appPath = MicroPhotoService.buildAppDir(this.getApplicationContext()); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; OutputStreamWriter outputStreamWriter = null; try { File dataPath = new File(appPath + "data/"); if (!dataPath.exists()) { dataPath.mkdirs(); } StringBuilder stringBuilder = new StringBuilder(); File file = new File(dataPath, "App.json"); if (file.exists()) { inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } JSONObject jsonObject =stringBuilder.length() > 0 ? (new JSONObject(stringBuilder.toString())) : (new JSONObject()); jsonObject.put("CMDID", cmdid); jsonObject.put("Server", server); jsonObject.put("Port", port); jsonObject.put("Protocol", protocol); jsonObject.put("NetworkProtocol", networkProtocol); outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(appPath + "data/App.json")), "UTF-8"); outputStreamWriter.write(jsonObject.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception ex) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (Exception ex) { } } if (outputStreamWriter != null) { try { outputStreamWriter.close(); } catch (Exception ex) { } } } } private int getDefaultDataSubId() { SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE); try { Method method = subscriptionManager.getClass().getDeclaredMethod("getDefaultDataSubscriptionId"); return (int) method.invoke(subscriptionManager); } catch (Exception e) { Log.e(TAG, "wjz debug getDefaultDataSubId: error is " + e.getMessage()); } return 0; } protected void takePhoto() { File path = Environment.getExternalStorageDirectory(); File file = new File(path, "photo.jpg"); boolean res = false; res = DSCameraManager.getInstace().init(); res = DSCameraManager.getInstace().takePhoto(file.getAbsolutePath(), 2); if (!res) { int aa = 0; } res = DSCameraManager.getInstace().unInit(); } String buildPhotoDir(int channel) { File path = new File(Environment.getExternalStorageDirectory(), "com.xinyingpower.com/photos/"); if (!path.exists() && !path.mkdirs()) { return null; } String p = path.getAbsolutePath(); if (!p.endsWith(File.separator)) { p += File.separator; } return p; } String buildPhotoFileName(int channel, int preset) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); String date = dateFormat.format(new Date()); String photoFile = "img_" + Integer.toString(channel) + "_" + Integer.toHexString(preset).toUpperCase() + "_" + date + ".jpg"; return photoFile; } private void takePhoto(int aa) { System.out.println("Preparing to take photo"); Camera camera = null; int cameraCount = 0; Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); cameraCount = Camera.getNumberOfCameras(); for (int camIdx = 0; camIdx < cameraCount; camIdx++) { SystemClock.sleep(1000); Camera.getCameraInfo(camIdx, cameraInfo); try { camera = Camera.open(camIdx); } catch (RuntimeException e) { System.out.println("Camera not available: " + camIdx); camera = null; //e.printStackTrace(); } try { if (null == camera) { System.out.println("Could not get camera instance"); } else { System.out.println("Got the camera, creating the dummy surface texture"); //SurfaceTexture dummySurfaceTextureF = new SurfaceTexture(0); try { //camera.setPreviewTexture(dummySurfaceTextureF); camera.setPreviewTexture(new SurfaceTexture(0)); camera.startPreview(); } catch (Exception e) { System.out.println("Could not set the surface preview texture"); e.printStackTrace(); } camera.takePicture(null, null, new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File path = getApplicationContext().getFilesDir(); // String appPath = path.getAbsolutePath(); File pictureFileDir = path; if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { return; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); String date = dateFormat.format(new Date()); String photoFile = "PictureFront_" + "_" + date + ".jpg"; String filename = pictureFileDir.getPath() + File.separator + photoFile; File mainPicture = new File(filename); // addImageFile(mainPicture); try { FileOutputStream fos = new FileOutputStream(mainPicture); fos.write(data); fos.close(); System.out.println("image saved"); } catch (Exception error) { System.out.println("Image could not be saved"); } camera.release(); } }); } } catch (Exception e) { camera.release(); } } } /** * A native method that is implemented by the 'microphoto' native library, * which is packaged with this application. */ public native String stringFromJNI(); public native boolean takePhoto(int channel, int preset, String path, String fileName); private void gpsTake() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // 注册位置监听器 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastKnownLocation != null) { double latitude = lastKnownLocation.getLatitude(); double longitude = lastKnownLocation.getLongitude(); // 处理最新位置信息 System.out.printf("gps" + latitude + "fds:" + longitude); } } LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { // 处理位置更新事件 double latitude = location.getLatitude(); double longitude = location.getLongitude(); // ... Log.e("xyh", "定位方式:" + location.getProvider()); Log.e("xyh", "纬度:" + location.getLatitude()); Log.e("xyh", "经度:" + location.getLongitude()); Log.e("xyh", "海拔:" + location.getAltitude()); Log.e("xyh", "时间:" + location.getTime()); Log.e("xyh", "国家:" + LocationUtil.getCountryName(MainActivity.this, location.getLatitude(), location.getLongitude())); Log.e("xyh", "获取地理位置:" + LocationUtil.getAddress(MainActivity.this, location.getLatitude(), location.getLongitude())); Log.e("xyh", "所在地:" + LocationUtil.getLocality(MainActivity.this, location.getLatitude(), location.getLongitude())); Log.e("xyh", "所在街道:" + LocationUtil.getStreet(MainActivity.this, location.getLatitude(), location.getLongitude())); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // 处理位置状态变化事件 System.out.printf("fsdaf"); } @Override public void onProviderEnabled(String provider) { // 处理位置提供者启用事件 System.out.printf("fsdaf"); } @Override public void onProviderDisabled(String provider) { // 处理位置提供者禁用事件 System.out.printf("fsdaf"); } }; private void startLocate() { LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean providerEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (providerEnabled) { //GPS已开启 /** * 绑定监听 * 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种,前者是GPS,后者是GPRS以及WIFI定位 * 参数2,位置信息更新周期.单位是毫秒 * 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息 * 参数4,监听 * 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新 */ 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; } mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } else { Toast.makeText(this, "请打开GPS", Toast.LENGTH_SHORT).show(); } } public static String getVersionName(Context context) { String verName = ""; try { verName = context.getPackageManager(). getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return verName; } // private void initSocket() { // NettyChatClient nettyChatClient = NettyChatClient.newInstance("47.96.238.157", 6891); //// NettyChatClient nettyChatClient = NettyChatClient.newInstance("180.166.218.222", 40032); // nettyChatClient.init(new INettyMessageListener() { // @Override // public void onReceive(String message) { //// for (INettyMessageListener nettyMessageListener : mIMessageListenerList) { //// nettyMessageListener.onReceive(message); //// } // System.out.println("dsfa"); // } // // @Override // public void onConnectSuccess() { //// for (INettyMessageListener nettyMessageListener : mIMessageListenerList) { //// nettyMessageListener.onConnectSuccess(); //// } // System.out.println("dsfa"); // } // // @Override // public void onError() { //// for (INettyMessageListener nettyMessageListener : mIMessageListenerList) { //// nettyMessageListener.onError(); //// } // System.out.println("dsfa"); // } // }); // nettyChatClient.connect(); // } }