You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
TermApp/app/src/main/java/com/xypower/mpapp/MainActivity.java

811 lines
33 KiB
Java

package com.xypower.mpapp;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Environment;
2 years ago
import android.os.FileObserver;
import android.os.Handler;
2 years ago
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.StrictMode;
2 years ago
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
2 years ago
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;
2 years ago
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.dev.devapi.api.SysApi;
import com.dowse.camera.client.DSCameraManager;
import com.xypower.common.CameraUtils;
import com.xypower.common.MicroPhotoContext;
import com.xypower.mpapp.databinding.ActivityMainBinding;
2 years ago
import com.xypower.mpapp.utils.RandomReader;
import java.io.File;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MPLOG";
private static int MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE = 100;
2 years ago
public static final int MSG_WHAT_LOG_OBSERVER = MicroPhotoService.MSG_WHAT_MAX + 10;
// Used to load the 'microphoto' library on application startup.
static {
System.loadLibrary("microphoto");
}
1 year ago
public static final int MAX_LOG_LINES = 480;
public static final int MIN_LOG_LINES = 120;
private ActivityMainBinding binding;
2 years ago
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;
2 years ago
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);
}
} else if (e == FileObserver.CREATE) {
mOffset = 0;
2 years ago
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
1 year ago
// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
// ViewUtils.hideSoftKeyboard(this);
ActionBar actionBar = getSupportActionBar();
// String buildTime = BuildConfig.BUILD_
Date date = new Date(BuildConfig.BUILD_TIMESTAMP);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
2 years ago
actionBar.setTitle(actionBar.getTitle().toString() + " v" + MicroPhotoContext.getVersionName(getApplicationContext()) + " " + sdf.format(date));
// CompactSpinnerAdapter adapter = new CompactSpinnerAdapter(this, R.array.networkProtocols, R.layout.spinner_dropdown_item);
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// binding.networkProtocol.setAdapter(adapter);
// ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this, R.array.networkProtocols, android.R.layout.simple_spinner_item);
// adapter1.setDropDownViewResource(R.layout.spinner_dropdown_item);
// binding.protocol.setAdapter(adapter1);
2 years ago
binding.logs.setText("");
binding.logs.setMovementMethod(ScrollingMovementMethod.getInstance());
binding.logs.setScrollbarFadingEnabled(false);
2 years ago
mHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
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) {
e.printStackTrace();
2 years ago
}
if (log != null) {
binding.logs.append(log);
int offset = binding.logs.getLineCount() * binding.logs.getLineHeight();
2 years ago
if (offset > binding.logs.getHeight()) {
binding.logs.scrollTo(0, offset - binding.logs.getHeight() + binding.logs.getLineHeight());
}
}
}
break;
}
}
};
// mMessenger = new Messenger(new Handler());
2 years ago
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
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.i(TAG, "After Reboot");
}
2 years ago
Log.d(TAG, "MainActivity: reboot=" + rebootFlag + " noDelay=" + noDelay);
2 years ago
MicroPhotoContext.AppConfig appConfig = getAppConfig();
if (TextUtils.isEmpty(appConfig.cmdid)) {
binding.cmdid.setText(MicroPhotoService.getSerialNumber());
} else {
binding.cmdid.setText(appConfig.cmdid);
}
binding.server.setText(appConfig.server);
binding.port.setText(appConfig.port != 0 ? Integer.toString(appConfig.port) : "");
2 years ago
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);
}
if (appConfig.encryption < binding.encryptions.getCount()) {
binding.encryptions.setSelection(appConfig.encryption);
}
binding.heartbeat.setText((appConfig.heartbeat > 0) ? Integer.toString(appConfig.heartbeat) : "");
binding.packetSize.setText((appConfig.packetSize > 0) ? Integer.toString(appConfig.packetSize) : "");
if (appConfig.network < binding.network.getCount()) {
binding.network.setSelection(appConfig.network);
}
this.binding.btnStartServ.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,
2 years ago
/*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;
}
binding.logs.setText("");
2 years ago
MicroPhotoContext.AppConfig curAppConfig = retrieveAndSaveAppConfig();
startMicroPhotoService(MainActivity.this.getApplicationContext(), appConfig, mMessenger);
binding.btnStartServ.setEnabled(false);
binding.btnStopServ.setEnabled(true);
}
});
2 years ago
this.binding.btnSaveCfg.setOnClickListener(new View.OnClickListener() {
2 years ago
@Override
public void onClick(View view) {
retrieveAndSaveAppConfig();
MicroPhotoService.updateConfigs(MainActivity.this.getApplicationContext());
2 years ago
}
});
this.binding.btnTakePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(1, 255, true);
}
});
this.binding.btnTakePhoto2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(2, 255, true);
}
});
this.binding.btnTakePhoto3.setOnClickListener(new View.OnClickListener() {
2 years ago
@Override
public void onClick(View view) {
takePhoto(3, 255, true);
2 years ago
}
});
this.binding.btnTakePhoto4.setOnClickListener(new View.OnClickListener() {
2 years ago
@Override
public void onClick(View view) {
takePhoto(4, 255, true);
}
});
this.binding.takeVideoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(1, 255, false);
}
});
this.binding.takeVideoBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(2, 255, false);
}
});
this.binding.takeVideoBtn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(3, 255, false);
}
});
this.binding.takeVideoBtn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(4, 255, false);
}
});
this.binding.btnStopServ.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);
MicroPhotoService.stopTerminalService(getApplicationContext());
binding.btnStartServ.setEnabled(true);
binding.btnStopServ.setEnabled(false);
}
});
binding.simchange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
1 year ago
// defaultDataSubId = getDefaultDataSubId();
// System.out.println(defaultDataSubId);
}
});
binding.simchange2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
1 year ago
/*
if (defaultDataSubId == 0) {
setDefaultDataSubId(1);
} else {
if (defaultDataSubId == 1) {
setDefaultDataSubId(2);
} else {
setDefaultDataSubId(1);
}
}
1 year ago
*/
}
});
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();
2 years ago
boolean gpsEnabled = LocationUtil.isGpsEnabled(MainActivity.this);
System.out.printf("g" + gpsEnabled);
2 years ago
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());
2 years ago
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 (!MicroPhotoService.isRunning && !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.btnStartServ.isEnabled()) {
binding.btnStartServ.performClick();
}
}
};
handler.postDelayed(runnable, noDelay != 0 ? 1000 : 5000);
}
binding.btnStartServ.setEnabled(!MicroPhotoService.isRunning);
binding.btnStopServ.setEnabled(MicroPhotoService.isRunning);
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) {
}
});
binding.video2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
binding.btnSendHb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MicroPhotoService.sendHeartbeat(getApplicationContext());
}
});
binding.btnRestartApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext().getApplicationContext();
MicroPhotoService.restartApp(context, context.getPackageName());
}
});
binding.btnReboot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle(R.string.confirm_reboot);
builder.setMessage(R.string.text_confirm_reboot);
builder.setCancelable(true);
builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
SysApi.reboot(v.getContext().getApplicationContext());
}
});
builder.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.show();
}
});
binding.btnCameraInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MicroPhotoService.setOtgState(true);
// SysApi.setOtgState(true);
MicroPhotoService.setCam3V3Enable(true);
Runnable runnable = new Runnable() {
@Override
public void run() {
String cameraInfo = CameraUtils.getAllCameraInfo(view.getContext());
Log.d(TAG, cameraInfo);
MicroPhotoService.setCam3V3Enable(false);
MicroPhotoService.setOtgState(false);
binding.logs.append(cameraInfo + "\r\n");
Toast.makeText(view.getContext(), cameraInfo, Toast.LENGTH_LONG).show();
}
};
mHandler.postDelayed(runnable, 1500);
}
});
}
2 years ago
public static void startMicroPhotoService(Context context, MicroPhotoContext.AppConfig curAppConfig, Messenger messenger) {
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("encryption", curAppConfig.encryption);
intent.putExtra("network", curAppConfig.network);
if (messenger != null) {
intent.putExtra("messenger", messenger);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
}
private void takePhoto(int channel, int preset, boolean photoOrVideo) {
MicroPhotoService.takePhoto(this.getApplicationContext(), channel, preset, photoOrVideo);
}
@Override
protected void onResume() {
// call the superclass method first
super.onResume();
try {
String logFilePath = MicroPhotoContext.buildAppDir(this.getApplicationContext());
logFilePath += "logs";
File file = new File(logFilePath);
if (!file.exists()) {
file.mkdirs();
}
logFilePath += "/log.txt";
file = new File(logFilePath);
if (!file.exists()) {
file.createNewFile();
}
mLogFileObserver = new LogFileObserver(logFilePath);
mLogFileObserver.startWatching();
Log.i(TAG, "Log Observer Started");
int lines = binding.logs.getLineCount();
if (lines > MAX_LOG_LINES) {
int excessLineNumber = lines - MIN_LOG_LINES;
int eolIndex = -1;
CharSequence charSequence = binding.logs.getText();
for (int i = 0; i < excessLineNumber; i++) {
do {
eolIndex++;
} while (eolIndex < charSequence.length() && charSequence.charAt(eolIndex) != '\n');
}
if (eolIndex < charSequence.length()) {
binding.logs.getEditableText().delete(0, eolIndex + 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
// call the superclass method first
super.onPause();
try {
if (mLogFileObserver != null) {
mLogFileObserver.stopWatching();
mLogFileObserver = null;
Log.i(TAG, "Log Observer Stopped");
}
} catch (Exception e) {
e.printStackTrace();
}
}
@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());
}
}
2 years ago
private MicroPhotoContext.AppConfig retrieveAndSaveAppConfig() {
MicroPhotoContext.AppConfig appConfig = new MicroPhotoContext.AppConfig();
2 years ago
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);
2 years ago
String protocolStr = MainActivity.this.binding.protocol.getSelectedItem().toString();
2 years ago
appConfig.protocol = MicroPhotoContext.DEFAULT_PROTOCOL;
2 years ago
String[] parts = protocolStr.split("-");
if (parts != null) {
appConfig.protocol = Integer.parseInt(parts[0]);
}
appConfig.networkProtocol = MainActivity.this.binding.networkProtocol.getSelectedItemPosition();
appConfig.encryption = MainActivity.this.binding.encryptions.getSelectedItemPosition();
2 years ago
appConfig.heartbeat = TextUtils.isEmpty(binding.heartbeat.getText().toString()) ? 0 : Integer.parseInt(binding.heartbeat.getText().toString());
appConfig.packetSize = TextUtils.isEmpty(binding.packetSize.getText().toString()) ? 0 : Integer.parseInt(binding.packetSize.getText().toString());
appConfig.network = MainActivity.this.binding.network.getSelectedItemPosition();
saveAppConfig(appConfig);
2 years ago
return appConfig;
}
2 years ago
private MicroPhotoContext.AppConfig getAppConfig() {
return MicroPhotoContext.getMpAppConfig(this.getApplicationContext());
}
2 years ago
private void saveAppConfig(MicroPhotoContext.AppConfig appConfig) {
MicroPhotoContext.saveMpAppConfig(getApplicationContext(), appConfig);
}
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();
}
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());
2 years ago
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已开启
/**
*
* 1GPS_PROVIDERNETWORK_PROVIDERGPS,GPRSWIFI
* 2.
* 3
* 4
* 23303300
*/
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();
}
}
2 years ago
// 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();
// }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Back pressed
return true; // disable it
}
return super.onKeyDown(keyCode, event);
}
}