Compare commits

...

12 Commits

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetDropDown">
<targetSelectedWithDropDown>
<runningDeviceTargetSelectedWithDropDown>
<Target>
<type value="QUICK_BOOT_TARGET" />
<type value="RUNNING_DEVICE_TARGET" />
<deviceKey>
<Key>
<type value="VIRTUAL_DEVICE_PATH" />
<value value="C:\Users\zqy04\.android\avd\Pixel_XL_API_31.avd" />
<type value="SERIAL_NUMBER" />
<value value="W3VBB21918206146" />
</Key>
</deviceKey>
</Target>
</targetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2023-03-28T17:08:46.341846900Z" />
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2023-06-28T03:24:01.996639400Z" />
</component>
</project>

@ -1,5 +0,0 @@
C
java:S1604"(Make this anonymous inner class a lambda(ìäÔéùÿÿÿÿ
P
java:S1161":Add the "@Override" annotation above this method signature(¼²Á÷

@ -1,5 +0,0 @@
>
java:S1604"(Make this anonymous inner class a lambda(ʆ<C38A>õ
P
java:S1161":Add the "@Override" annotation above this method signature(¼²Á÷

@ -1,32 +0,0 @@
C
java:S1604Z"(Make this anonymous inner class a lambda(ƒø…Òÿÿÿÿÿ
>
java:S1604c"(Make this anonymous inner class a lambda(›³äª
t java:S115!"ZRename this constant name to match the regular expression '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.(­“ïÍøÿÿÿÿ
o java:S115""ZRename this constant name to match the regular expression '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.(šŸåå
t java:S116O"ZRename this field "Trans_to_Detect" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(¾¥Âöûÿÿÿÿ
y
java:S1450O"^Remove the "Trans_to_Detect" field and declare it as a local variable in the relevant methods.(¾¥Âöûÿÿÿÿ
m
java:S1450Q"RRemove the "btn" field and declare it as a local variable in the relevant methods.(ãȧ<C388>üÿÿÿÿ
`
java:S1124!"EReorder the modifiers to comply with the Java Language Specification.(­“ïÍøÿÿÿÿ
[
java:S1124""EReorder the modifiers to comply with the Java Language Specification.(šŸåå
[
java:S1124#"EReorder the modifiers to comply with the Java Language Specification.(ß×á
[
java:S1124$"EReorder the modifiers to comply with the Java Language Specification.(Ó¾þá
V java:S125]"<This block of commented-out lines of code should be removed.(è·¿¯ùÿÿÿÿ
C
java:S1185~"(Remove this method to simply inherit it.(ñ‰ÿÜýÿÿÿÿ
W java:S125"<This block of commented-out lines of code should be removed.(<28>­éäøÿÿÿÿ
W java:S125"<This block of commented-out lines of code should be removed.(çéŸþÿÿÿÿ
F
java:S2093<18>"*Change this "try" to a try-with-resources.(ç£ê<C2A3>úÿÿÿÿ
W java:S125Í"<This block of commented-out lines of code should be removed.(òœô˜úÿÿÿÿ
9
java:S1128"Remove this duplicated import.(°þÊóøÿÿÿÿ
L
java:S1068*"1Remove this unused "receiveSocket" private field.(ÜÁ‰Óúÿÿÿÿ

@ -1,54 +0,0 @@
p
java:S11049"[Make mLocationClient a static final constant or non-public and provide accessors if needed.(òó•L
q
java:S1104;"[Make mLocationOption a static final constant or non-public and provide accessors if needed.(ÈÀ‚§
k
java:S2259ê"MA "NullPointerException" could be thrown; "mLocationClient" is nullable here.(Ô¹¤<C2B9>8üÀ±•‡1
z java:S116>"YRename this field "Current_latlng" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(æàÁÆÿÿÿÿÿ8ýÀ±•‡1
v java:S116P"ZRename this field "ClearMarker_btn" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(ëþ¥È8ýÀ±•‡1
y java:S116R"XRename this field "ChangeAct_btn" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(ÂîœÃúÿÿÿÿ8ýÀ±•‡1
Ÿ
java:S1186Å"€Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.(±€¿ë8Á±•‡1
~
java:S1450R"\Remove the "ChangeAct_btn" field and declare it as a local variable in the relevant methods.(ÂîœÃúÿÿÿÿ8ƒÁ±•‡1
i
java:S1450="SRemove the "city" field and declare it as a local variable in the relevant methods.(“øÌà
t
java:S1450L"WRemove the "cityCode" field and declare it as a local variable in the relevant methods.(êýð†8ƒÁ±•‡1
N
java:S1874H"1Remove this use of "PoiSearch"; it is deprecated.(–ƒëÖ8ŒÁ±•‡1
S
java:S1874J"1Remove this use of "PoiSearch"; it is deprecated.(²¹·‘ÿÿÿÿÿ8<>Á±•‡1
] java:S125e"<This block of commented-out lines of code should be removed.(¤¯¿Îúÿÿÿÿ8˜Á±•‡1
m
java:S1874 "JDon't override a deprecated method or explicitly mark it as "@Deprecated".(Ó»×¶þÿÿÿÿ8œÁ±•‡1
Y java:S125Ö"<This block of commented-out lines of code should be removed.(©áèè8¤Á±•‡1
`
java:S1854"=Remove this useless assignment to local variable "longitude".(ËàÅ€ûÿÿÿÿ8¨Á±•‡1
_
java:S1854"<Remove this useless assignment to local variable "latitude".(û‘áäùÿÿÿÿ8©Á±•‡1
P
java:S1481"-Remove this unused "latitude" local variable.(û‘áäùÿÿÿÿ8«Á±•‡1
Q
java:S1481".Remove this unused "longitude" local variable.(ËàÅ€ûÿÿÿÿ8«Á±•‡1
Y java:S125Ä"<This block of commented-out lines of code should be removed.(É–Ö­8ÔŸÈ•‡1
N
java:S1172ç"+Remove this unused method parameter "view".(çÑ¢‰ýÿÿÿÿ8²Á±•‡1
\
java:S1155è">Use isEmpty() to check whether the collection is empty or not.(”ó±’8²Á±•‡1
N
java:S1172ð"+Remove this unused method parameter "view".(•É‘Îûÿÿÿÿ8³Á±•‡1
X java:S125"<This block of commented-out lines of code should be removed.(Ÿ…¦Q8¸Á±•‡1
\
java:S1117±"9Rename "query" which hides the field declared at line 72.(˜Ž“áûÿÿÿÿ8»Á±•‡1
^ java:S125Ê"<This block of commented-out lines of code should be removed.(±<>öîýÿÿÿÿ8½Á±•‡1
Y java:S125Õ"<This block of commented-out lines of code should be removed.(ÎÞ<C38E>û8½Á±•‡1
>
java:S1068="(Remove this unused "city" private field.(“øÌà
F
java:S1068H")Remove this unused "query" private field.(–ƒëÖ8¾Á±•‡1
O
java:S1068J"-Remove this unused "poiSearch" private field.(²¹·‘ÿÿÿÿÿ8¾Á±•‡1
I
java:S1068L",Remove this unused "cityCode" private field.(êýð†8¾Á±•‡1

@ -1,33 +0,0 @@
o
java:S2293Z"YReplace the type specification in this constructor call with the diamond operator ("<>").(œœÕ¼
K
java:S1066<18>"/Merge this if statement with the enclosing one.(¦­Üˆûÿÿÿÿ
K
java:S1066"/Merge this if statement with the enclosing one.(þÆÅ÷üÿÿÿÿ
>
java:S1604"(Make this anonymous inner class a lambda(ô§ê
i
java:S1104%"SMake TV_show a static final constant or non-public and provide accessors if needed.(úÀŸõ
>
java:S2189±""Add an end condition to this loop.(˜ïˆžÿÿÿÿÿ
>
java:S2189""Add an end condition to this loop.(˜ïˆžÿÿÿÿÿ
k java:S116!"VRename this field "receive_Msg" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(ŒßÙú
g java:S116%"RRename this field "TV_show" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(úÀŸõ
^
java:S1659#"CDeclare "total1" and all following declarations on a separate line.(Æ‘ç¡üÿÿÿÿ
c java:S100<"NRename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.(Íš“è
h
java:S3776~"RRefactor this method to reduce its Cognitive Complexity from 50 to the 15 allowed.(“–ýþ
u
java:S2142Œ"^Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.(<>í†
W java:S125"<This block of commented-out lines of code should be removed.(‹ãà‘úÿÿÿÿ
R java:S125"<This block of commented-out lines of code should be removed.(çÓ®Ë
U
java:S1155·">Use isEmpty() to check whether the collection is empty or not.(†”“”
u
java:S2142È"^Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.(ä ¹€
O java:S106×"9Replace this use of System.out or System.err by a logger.(ŒŸÍÞ
A
java:S1068$"+Remove this unused "button0" private field.(Îÿæ¡

@ -9,21 +9,7 @@ A
gradle.properties,2\a\2afbb999f001938c88fa43fc2ef52abf0f8213e4
k
;app/src/test/java/com/example/sixaunyi/ExampleUnitTest.java,8\9\892f839083a73d776402535dde27e522288853c9
i
9app/src/main/java/com/example/sixaunyi/FirstFragment.java,0\3\0336633037f72ee431c162e8d6cbc29d1cd6fa5d
j
:app/src/main/java/com/example/sixaunyi/SecondFragment.java,1\2\12963d86ac5c2888cc2a9ae459de5665bc06b01f
?
settings.gradle,0\5\05efc8b1657769a27696d478ded1e95f38737233
@
app/build.gradle,f\4\f4a01d6a4fcb971362ec00a83903fd3902f52164
j
:app/src/main/java/com/example/sixaunyi/DetectActivity.java,9\6\9668392b13e33166876f2a7d3f10eb5405e757ad
i
9app/src/main/java/com/example/sixaunyi/VideoActivity.java,7\1\71fd1993763df2214bbdad8cfee650733993fe44
h
8app/src/main/java/com/example/sixaunyi/MainActivity.java,7\c\7c120b7216f76ce98d1573d90803ab36f481640c
P
app/src/main/AndroidManifest.xml,8\c\8c55c3ccc257e5907959013f99656e4c8ec3903e
k
;app/src/main/java/com/example/sixaunyi/ControlActivity.java,c\9\c99a584c2117ed2df42496451bb97ac1147f5ea0
app/build.gradle,f\4\f4a01d6a4fcb971362ec00a83903fd3902f52164

@ -46,6 +46,7 @@ dependencies {
implementation 'pub.devrel:easypermissions:3.0.0'
//Material
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.media:media:1.3.0'
//

@ -18,16 +18,17 @@
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:icon="@drawable/app"
android:label="哨兵"
android:roundIcon="@drawable/app"
android:supportsRtl="true"
android:theme="@style/Theme.Sixaunyi"
android:theme="@style/Theme.Sixaunyi.NoActionBar"
tools:targetApi="31">
<activity
android:name=".ControlActivity"
android:name=".SettingActivity"
android:exported="false"
android:screenOrientation="landscape"
android:exported="false" />
android:theme="@style/TransparentTheme"/>
<!-- 定位service -->
<service android:name="com.amap.api.location.APSService" /> <!-- 设置高德Key -->
<meta-data
@ -36,17 +37,20 @@
<activity
android:name=".VideoActivity"
android:exported="false" />
<activity
android:name=".DetectActivity"
android:exported="false"
android:label="@string/title_activity_detect"
android:theme="@style/Theme.Sixaunyi.NoActionBar" />
android:screenOrientation="landscape"
/>
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat">
android:theme="@style/Theme.AppCompat.NoActionBar">
</activity>
<activity
android:name=".LoginActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

@ -1,14 +0,0 @@
package com.example.sixaunyi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class ControlActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
}
}

@ -1,221 +0,0 @@
package com.example.sixaunyi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class DetectActivity extends AppCompatActivity {
/*接收发送定义的常量*/
private String mIp= "192.168.79.46"; //这里是NodeMCU的IP Address我们可以通过打开Arduino的串口监视器获取IP Address
private int mPort = 80; //WiFiServer server(80);建立网络服务器对象监听端口80这里的80是自定义的只要与Android中的socket一致就好。
private SendThread sendthread;
String receive_Msg;
String l;
String total0,total1,total2,total3;
private Button button0;
public TextView TV_show;
private DataHandler mHandler = new DataHandler();
/*****************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
//onCreate必做事情继承父类super.onCreate设置当前试图setContentView
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detect);
TV_show = findViewById(R.id.show);
/***************连接*****************/
sendthread = new SendThread(mIp, mPort, mHandler);
create_Thread();
new Thread().start();
/**********************************/
}
/*接收线程*******************************************************************************/
/**
* socket线
*/
void create_Thread(){
new Thread(sendthread).start();//创建一个新线程
}
class DataHandler extends Handler {
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if (msg.what == 0x00) {
Log.i("mr_收到的数据 ", msg.obj.toString());
receive_Msg = msg.obj.toString();
if(receive_Msg.indexOf("Humidity:")!=-1) {
String[] strArray = receive_Msg.split(" "); //处理接受到的数据并将他们显示在TextView中
TV_show.setText(strArray[3]);
}
}
}
}
class SendThread implements Runnable {
private String ip;
private int port;
BufferedReader in;
PrintWriter out; //打印流
Handler mainHandler;
Socket s;
private String receiveMsg;
ArrayList<String> list = new ArrayList<String>();
public SendThread(String ip,int port, Handler mainHandler) { //IP端口数据
this.ip = ip;
this.port=port;
this.mainHandler = mainHandler;
}
/**
*
*/
void open(){
try {
s = new Socket(ip, port);
//in收单片机发的数据
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
s.getOutputStream())), true);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
*/
void close(){
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
//创建套接字
open();
//BufferedReader
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
close();
open();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (!s.isClosed()) {
if (s.isConnected()) {
if (!s.isInputShutdown()) {
try {
Log.i("mr", "等待接收信息");
Message msg=mainHandler.obtainMessage();
char[] chars = new char[1024]; //byte[] bys = new byte[1024];
int len = 0; //int len = 0;
while((len = in.read(chars)) != -1){
receiveMsg = new String(chars, 0, len);
msg.what=0x00;
msg.obj=receiveMsg;
mainHandler.sendMessage(msg);
}
} catch (IOException e) {
Log.i("mr", e.getMessage());
try {
s.shutdownInput();
s.shutdownOutput();
s.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
}
}
}
});
thread.start();
while (true) {
//连接中
if (!s.isClosed()&&s.isConnected()&&!s.isInputShutdown()) {
// 如果消息集合有东西,并且发送线程在工作。
if (list.size() > 0 && !s.isOutputShutdown()) {
out.println(list.get(0));
list.remove(0);
}
Message msg=mainHandler.obtainMessage();
msg.what=0x01;
mainHandler.sendMessage(msg);
} else {
//连接中断了
Log.i("mr", "连接断开了");
Message msg=mainHandler.obtainMessage();
msg.what=0x02;
mainHandler.sendMessage(msg);
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
try {
out.close();
in.close();
s.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public void send(String msg) {
System.out.println("msg的值为 " + msg);
list.add(msg);
}
}
}

@ -0,0 +1,79 @@
package com.example.sixaunyi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
private EditText mUsername;
private EditText mPassword;
private Button mLoginButton;
private CheckBox Account_remember;
private SharedPreferences sharedPreferences;
private Map<String, String> mUsers = new HashMap<>();
{
mUsers.put("admin", "123456");
mUsers.put("tiequan", "8731");
mUsers.put("zhenghaoyuan", "6666");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// 获取输入框和按钮的实例
mUsername = findViewById(R.id.username);
mPassword = findViewById(R.id.password);
mLoginButton = findViewById(R.id.login);
Account_remember = findViewById(R.id.remember_check);
sharedPreferences = getSharedPreferences("account", Context.MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String password =sharedPreferences.getString("password", "");
boolean isChecked = sharedPreferences.getBoolean("checkbox_state", false);
mUsername.setText(username);
mPassword.setText(password);
Account_remember.setChecked(isChecked);
// 设置登录按钮的点击事件
mLoginButton.setOnClickListener(v -> {
attemptLogin();
});
}
private void attemptLogin() {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
boolean if_correct = verifyUser(username,password);
if (if_correct) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.putBoolean("checkbox_state", Account_remember.isChecked());
editor.apply();
if (Account_remember.isChecked()){
editor.putString("password", password);
}else{
editor.putString("password", "");
}
editor.apply();
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
}
}
private boolean verifyUser(String username, String password){
if (mUsers.containsKey(username) && mUsers.get(username).equals(password)) {
return true;
} else {
return false;
}
}
}

@ -2,21 +2,32 @@ package com.example.sixaunyi;
import static androidx.constraintlayout.motion.utils.Oscillator.TAG;
import static java.lang.Math.PI;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.animation.Animator;
import android.animation.ValueAnimator;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
@ -29,6 +40,8 @@ import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
@ -40,14 +53,23 @@ import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import android.view.animation.LinearInterpolator;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
public class MainActivity extends AppCompatActivity implements AMapLocationListener, LocationSource,
public class MainActivity extends AppCompatActivity implements AMapLocationListener, LocationSource,
AMap.OnMapLongClickListener, GeocodeSearch.OnGeocodeSearchListener, AMap.OnMarkerDragListener,
AMap.OnMarkerClickListener{
@ -68,10 +90,6 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
private GeocodeSearch geocodeSearch;
//解析成功标识码
private static final int PARSE_SUCCESS_CODE = 1000;
//POI查询对象
private PoiSearch.Query query;
//POI搜索对象
private PoiSearch poiSearch;
//城市码
private String cityCode = null;
//浮动按钮
@ -79,34 +97,61 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
//浮动按钮 清空地图标点
private FloatingActionButton ClearMarker_btn;
//浮动按钮 更换活动
private FloatingActionButton ChangeAct_btn;
private ImageButton ChangeAct_btn;
//标点列表
private List<Marker> markerList = new ArrayList<>();
//标识参数类
private MarkerOptions markerOption = new MarkerOptions();
//
private DatagramSocket reveSocket;
private String value;
private ExecutorService mThreadPool = Executors.newCachedThreadPool();
//private ActivityResultLauncher<Intent> launcher;
////////////////////////////可修改部分/////////////////////////////
private final LatLng Monitorlatlng = new LatLng(28.257553,113.0417);
private final static String Recieve_IP = "192.168.39.46";
private final static int RECEIVE_PORT = 9975;
private final static String SEND_to_IP = "192.168.39.195";
private final static int SEND_PORT = 8888;
/////////////////////////////////////////////////////////////////
private InetAddress serverAddr;
private String Angle;
private String MonitorAngle;
private float distance;
private float MonitorDistance;
private UdpReceiveThread udpReceiveThread;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fabPOI = findViewById(R.id.fab_poi);
if (savedInstanceState != null) {
// 从保存的状态数据中恢复状态
value = savedInstanceState.getString("key");
}
ClearMarker_btn = findViewById(R.id.clearMarker_btn);
ChangeAct_btn = findViewById(R.id.change_btn);
ChangeAct_btn.show();
//tvContent = findViewById(R.id.tv_content);
/*,
*
*/
ChangeAct_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeAct();
}
});
initLocation();
//初始化地图
initMap(savedInstanceState);
//检查安卓版本
checkingAndroidVersion();
addSensorMarker(Monitorlatlng);
}
/**
* Android
@ -206,6 +251,8 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
aMap.setLocationSource(this);
// 设置为true表示显示定位层并可触发定位false表示隐藏定位层并不可触发定位默认是false
aMap.setMyLocationEnabled(true);
//设置最小缩放等级为16 ,缩放级别范围为[3, 20]
aMap.setMinZoomLevel(14);
//设置地图标志点击事件
aMap.setOnMarkerClickListener(this);
//设置地图标志拖拽事件
@ -259,6 +306,10 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
city = aMapLocation.getCity();
//当前位置经纬度坐标
Current_latlng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
MonitorDistance = AMapUtils.calculateLineDistance(Current_latlng,Monitorlatlng);
Log.i(TAG, String.valueOf(Current_latlng.longitude));
Log.i(TAG, String.valueOf(Current_latlng.latitude));
//
//获取纬度
double latitude = aMapLocation.getLatitude();
//获取经度
@ -266,6 +317,8 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
Log.d("MainActivity", aMapLocation.getCity());
showMsg(address);
udpReceiveThread = new UdpReceiveThread();
udpReceiveThread.startListening();
//停止定位后,本地定位服务并不会被销毁
mLocationClient.stopLocation();
if (mListener != null) {
@ -301,6 +354,7 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("key", value);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
mapView.onSaveInstanceState(outState);
}
@ -320,14 +374,17 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
//LatLng 为高德地图包自带的存储坐标对象
@Override
public void onMapLongClick(LatLng latLng) {
float distance = AMapUtils.calculateLineDistance(Current_latlng,latLng);
distance = AMapUtils.calculateLineDistance(Current_latlng,latLng);
Angle = calcAngle(Current_latlng.latitude, Current_latlng.longitude, latLng.latitude,latLng.longitude);
MonitorAngle = calcAngle(Current_latlng.latitude, Current_latlng.longitude, 113.05370390725032,28.256794281117525);
//showMsg("长按了地图,经度:"+latLng.longitude+",纬度:"+latLng.latitude);
showMsg("直线距离:"+distance+"米");
//坐标转地址
Log.i(TAG, String.valueOf(latLng.longitude));
Log.i(TAG, String.valueOf(latLng.latitude));
showMsg("直线距离:"+distance+"米"+"角度"+Angle);
//坐标转地址113.05370390725032 28.256794281117525
latlonToAddress(latLng);
//添加标点
addMarker(latLng);
}
/**
@ -343,7 +400,7 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
.draggable(true)
//标点图标
.icon(BitmapDescriptorFactory.
fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.img)))
fromBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.weizhi)))
//备注
.title("路径点")
.snippet("距离:")
@ -352,6 +409,124 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
marker.showInfoWindow();
markerList.add(marker);
}
// 添加传感器标点
private Marker sensorMarker = null;
private void addSensorMarker(LatLng latLng) {
// 显示浮动按钮
// 添加传感器标点
MarkerOptions sensorMarkerOption = new MarkerOptions();
sensorMarker = aMap.addMarker(sensorMarkerOption
.position(latLng)
.draggable(false)
// 标点图标
.icon(BitmapDescriptorFactory.
fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.sensor)))
// 备注
.title("传感器")
);
sensorMarker.showInfoWindow();
}
// 添加无人机标点
private Marker droneMarker = null;
private void addDroneMarker() {
// 添加无人机标点
MarkerOptions droneMarkerOption = new MarkerOptions();
droneMarker = aMap.addMarker(droneMarkerOption
.position(Current_latlng)
.draggable(false)
// 标点图标
.icon(BitmapDescriptorFactory.
fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.drone)))
// 备注
.title("无人机")
);
droneMarker.showInfoWindow();
}
// 移动无人机标点到传感器标点并显示平移动画
public static class SmoothMoveUtil {
private Marker droneMarker;
private LatLng startLatLng;
private LatLng endLatLng;
private long duration;
public SmoothMoveUtil(Marker marker) {
this.droneMarker = marker;
}
public void moveDroneMarker(LatLng sensorLatLng, long duration) {
if (droneMarker != null) {
startLatLng = droneMarker.getPosition();
endLatLng = sensorLatLng;
this.duration = duration;
// 开始动画
startSmoothMove();
}
}
private void startSmoothMove() {
LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(duration);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
LatLng newPosition = latLngInterpolator.interpolate(fraction, startLatLng, endLatLng);
droneMarker.setPosition(newPosition);
}
});
valueAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
// 动画结束
droneMarker.setPosition(endLatLng);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
valueAnimator.start();
}
// LatLng 插值器接口——算经纬度过渡用的
public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
class LinearFixed implements LatLngInterpolator {
@Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lngDelta = b.longitude - a.longitude;
// 如果跨越了 180 度经度,则进行调整
if (Math.abs(lngDelta) > 180) {
lngDelta -= Math.signum(lngDelta) * 360;
}
double lng = lngDelta * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
}
}
/**
* Marker
* @param view
@ -365,9 +540,20 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
ClearMarker_btn.hide();
}
public void changeAct(View view) {
public void moveDrone(){
SmoothMoveUtil moveUtil = new SmoothMoveUtil(droneMarker);
long time = (long) MonitorDistance/2*1000;
moveUtil.moveDroneMarker(Monitorlatlng,time);
}
public void changeAct() {
udpReceiveThread.stopListening();
Intent intent = new Intent(MainActivity.this, VideoActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Bundle b = new Bundle();
b.putString("Angle", MonitorAngle);
b.putFloat("Distance", MonitorDistance);
intent.putExtras(b);
int requestCode = 1; // 可以是任何非负整数
startActivity(intent);
}
@ -444,7 +630,7 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
//显示解析后的地址
showMsg("地址:"+regeocodeAddress.getFormatAddress());
}else {
} else {
showMsg("获取地址失败");
}
}
@ -453,20 +639,178 @@ public class MainActivity extends AppCompatActivity implements AMapLocationListe
public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
}
/*
@Override
public void onPoiSearched(PoiResult poiResult, int i) {
//解析result获取POI信息
//获取POI组数列表
ArrayList<PoiItem> poiItems = poiResult.getPois();
for (PoiItem poiItem : poiItems) {
Log.d("MainActivity", " Title" + poiItem.getTitle() + " Snippet" + poiItem.getSnippet());
class ReceiveHandler extends Handler{
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Context context = MainActivity.this;
showAlert(context,"传感器报警");
addDroneMarker();
moveDrone();
}
});
}
}
}
public class UdpReceiveThread extends Thread {
private static final String TAG = "UdpReceiveThread";
private static final int mRECEIVE_PORT = RECEIVE_PORT;
private boolean mRunning = true;
private String mReceiveIp = Recieve_IP;
private String mExpectedData = "Motion detected!";
private float udpMonitorDistance = MonitorDistance;
private String udpMonitorAngle = MonitorAngle;
private Handler receiveHandler = new ReceiveHandler();
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(mRECEIVE_PORT);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (mRunning) {
Log.i(TAG, "run: 111111111111111111");
socket.receive(packet);
byte[] data = packet.getData();
String receivedString = new String(data, 0, packet.getLength());
Log.d(TAG, "Received data: " + receivedString);
if (receivedString.equals(mExpectedData)) {
Log.i(TAG, "run: 222222222222222222222222222");
receiveHandler.sendEmptyMessage(1);
sendCommand("WARNING "+String.valueOf(udpMonitorDistance)+" "+udpMonitorAngle);
mRunning = false;
}
}
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startListening() {
mRunning = true;
start();
}
public void stopListening() {
mRunning = false;
}
}*/
}
public void showAlert(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("警告");
builder.setMessage(message);
builder.setIcon(R.drawable.warning);
builder.setPositiveButton("确定", null);
AlertDialog dialog = builder.create();
dialog.show();
}
//以北为0度
public static String calcAngle(Double centerLat, Double centerLon, Double anotherLat, Double anotherLon) {
//差值
double subLat = anotherLat - centerLat;
double subLon = anotherLon - centerLon;
double angle = 0;
if (subLat == 0) {
//纬度差值为0 表示两点在同一高度 此时点必然在x轴右侧 或者 x轴左侧
if (subLon > 0) {
//x轴右侧
angle = 90;
} else if (subLon < 0) {
//x轴左侧
angle = 270;
}
} else if (subLon == 0) {
//经度差值为0 说明点在y轴上方或者y轴下方
if (subLat > 0) {
//y轴上方
angle = 0;
} else if (subLat < 0) {
//y轴下方
angle = 180;
}
} else {
//根据tan的值求角度 subLon不能为0 纬度差值 除以 经度差值 = tan的值
double v = subLat / subLon;
angle = Math.atan(v) * 180 / PI;
//angle的值在-180到180之间
System.out.println("未处理的角度值:" + (angle));
//第二种求角度的方法
//angle = Math.atan2(subLat,subLon) * 180 / PI ;
//判断数据在第几象限
//1、正切小于0 在二四象限
if (angle < 0) {
if (subLon > 0) {
//此时的点在中心点的右下角
angle = Math.abs(angle)+ 90;
} else if (subLon < 0) {
//此时的点在中心点的左上角
angle = Math.abs(angle) + 270;
}
}
//2、正切大于0 在一三象限
else if (angle > 0) {
if (subLon > 0) {
//此时的点在中心点的右上角 360-angle
angle = 90-angle;
} else if (subLat < 0) {
// 此时的点在中心点的左下角
angle = 270-angle;
}
}
}
return String.valueOf(angle);
}
/*
@Override
public void (PoiItem poiItem, int i) {
*UDP线
*/
class SendRunnable implements Runnable {
byte[] mData;
InetAddress mAddress;
int mPort;
public SendRunnable(byte[] data, InetAddress address, int port) {
mData = data;
mAddress = address;
mPort = port;
}
@Override
public void run() {
try {
// 创建发送数据报文
DatagramPacket packet = new DatagramPacket(mData, mData.length, mAddress, mPort);
// 创建 DatagramSocket 对象并发送数据报文
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
// 关闭 DatagramSocket 对象
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//封装好的接口函数
private void sendCommand(String str) throws UnknownHostException {
byte[] sendData = str.getBytes();
InetAddress address = InetAddress.getByName(SEND_to_IP);
SendRunnable sendRunnable1 = new SendRunnable(sendData, address, SEND_PORT);
mThreadPool.execute(sendRunnable1);
}
}*/
}

@ -0,0 +1,194 @@
package com.example.sixaunyi;
import static androidx.constraintlayout.motion.utils.Oscillator.TAG;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SettingActivity extends AppCompatActivity {
private final static String SEND_to_IP = "192.168.39.47";
private SeekBar Speed_btn;
private SeekBar Battery_btn;
private ImageButton return_btn;
private final static int SEND_PORT = 8888;
private ExecutorService mThreadPool = Executors.newCachedThreadPool();
private Switch photo_btn;
private Context context;
private SharedPreferences sharedPreferences;
private TextView tvProgress;
private TextView Battery_warning;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Speed_btn= findViewById(R.id.speed);
return_btn=findViewById(R.id.returns);
photo_btn = findViewById(R.id.photo);
Battery_btn = findViewById(R.id.warning_num);
tvProgress = findViewById(R.id.tvProgress);
Battery_warning=findViewById(R.id.Battery_warning);
sharedPreferences = getSharedPreferences("control_state", MODE_PRIVATE);
boolean photo_btn_state= sharedPreferences.getBoolean("photo_btn_state", false);
photo_btn.setChecked(photo_btn_state);
// 恢复SeekBar状态
int speedProgress = sharedPreferences.getInt("speed_progress", 0);
Speed_btn.setProgress(speedProgress);
tvProgress.setText(String.valueOf(speedProgress+10));
int warning_num= sharedPreferences.getInt("battery_num", 0);
Battery_btn.setProgress(warning_num);
Battery_warning.setText(String.valueOf(warning_num));
photo_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 保存Switch状态
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("photo_btn_state", isChecked);
editor.apply();
}
});
Speed_btn.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvProgress.setText(String.valueOf(progress+10));
int speed=progress+10;
String s = "SPEED " + Integer.toString(speed);
try {
sendCommand(s);
} catch (UnknownHostException e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("speed_progress", progress);
editor.apply();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Battery_btn.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Battery_warning.setText(String.valueOf(progress));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("battery_num", progress);
editor.apply();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
return_btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// 启动目标 Activity
passingParameters();
}
});
photo_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (photo_btn.isChecked()) {
try {
sendCommand("PHOTO_HIGH");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}else
{
try {
sendCommand("PHOTO_LOW");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
});
}
/*
* UDP线
* */
class SendRunnable implements Runnable {
byte[] mData;
InetAddress mAddress;
int mPort;
public SendRunnable(byte[] data, InetAddress address, int port) {
mData = data;
mAddress = address;
mPort = port;
}
@Override
public void run() {
try {
// 创建发送数据报文
DatagramPacket packet = new DatagramPacket(mData, mData.length, mAddress, mPort);
// 创建 DatagramSocket 对象并发送数据报文
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
// 关闭 DatagramSocket 对象
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*封装函数*/
private void sendCommand(String str) throws UnknownHostException {
byte[] sendData = str.getBytes();
InetAddress address = InetAddress.getByName(SEND_to_IP);
SendRunnable sendRunnable1 = new SendRunnable(sendData, address, SEND_PORT);
mThreadPool.execute(sendRunnable1);
}
@Override
public void onBackPressed() {
// 在这里处理返回事件的逻辑
super.onBackPressed(); // 调用父类的方法,执行默认的返回操作
passingParameters();
}
private void passingParameters(){
int warning_num= sharedPreferences.getInt("battery_num", 0);
Log.i(TAG, "111111111111111111111"+String.valueOf(warning_num));
Intent intent = new Intent(SettingActivity.this,VideoActivity.class);
intent.putExtra("BATTERY_NUM", warning_num); // 设置要传递的参数
setResult(RESULT_OK, intent);
finish();
}
}

@ -4,122 +4,346 @@ import static androidx.constraintlayout.motion.utils.Oscillator.TAG;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.os.Bundle;
public class VideoActivity extends AppCompatActivity {
import android.widget.ToggleButton;
private final static String SEND_to_IP = "192.168.43.165"; //填写接收方IP
private final static String Recieve_IP = "192.168.43.165";//填服务器IP
public class VideoActivity extends AppCompatActivity {
private final static String SEND_to_IP = "192.168.39.195"; //填写接收方IP
private final static String Recieve_IP = "192.168.39.195";//填服务器IP与send_to_IP为同一个
private final static int SEND_PORT = 8888; //发送端口号
private final static int RECEIVE_PORT = 9999; //接收端口号
private boolean listenStatus = true; //接收线程的循环标识
private static boolean listenStatus = true; //接收线程的循环标识
private byte[] buf;
Bitmap bp;
private DatagramSocket receiveSocket;
private DatagramSocket sendSocket;
static Bitmap bp;
private DatagramSocket reveSocket;
private InetAddress serverAddr;
private DatagramSocket sendSocket;
private static InetAddress serverAddr;
private SendHandler sendHandler = new SendHandler();
private ReceiveHandler receiveHandler = new ReceiveHandler();
private Button Trans_to_Detect;
private ImageView imgShow;
private Button btn;
private ImageButton Forward_btn;
private ImageButton Back_btn;
private ImageButton Left_btn;
private ImageButton Right_btn;
private ImageButton Down_btn;
private ImageButton Up_btn;
private ImageButton TurnLeft_btn;
private ImageButton TurnRight_btn;
private ImageButton Setting_btn;
private ImageButton TakeOff_btn;
private ImageButton Landing_btn;
private ImageButton Record_btn;
private ToggleButton Mode_btn;
private ImageButton selfHome_btn;
private String mangle;
private float mdistance;
// 创建一个可缓存的线程池
private ExecutorService mThreadPool = Executors.newCachedThreadPool();
private UdpDataThread warning_thread;
private TextView battery_warning;
private ImageButton show_status;
private String batteryStatus="未获取";
private String speedStatus="未获取";
private String distanceStatus="未获取";
//ReceiveData()显示到imageView
//manager部分打开线程接收
//model部分发送视频流
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
imgShow = findViewById(R.id.img_show);
btn = findViewById(R.id.btn_send);
Trans_to_Detect = findViewById(R.id.transfer_to_detect);
btn.setOnClickListener(new View.OnClickListener() {
setContentView(R.layout.activity_control);
imgShow = findViewById(R.id.imageView);
Forward_btn = findViewById(R.id.forward_button);
Back_btn = findViewById(R.id.backward_button);
Left_btn = findViewById(R.id.left_button);
Right_btn = findViewById(R.id.right_button);
Down_btn = findViewById(R.id.down_button);
Up_btn = findViewById(R.id.up_button);
TurnLeft_btn = findViewById(R.id.rotate_left_button);
Landing_btn = findViewById(R.id.landing_button);
TurnRight_btn = findViewById(R.id.rotate_right_button);
TakeOff_btn = findViewById(R.id.takeoff_button);
Mode_btn = findViewById(R.id.toggleButton2);
Record_btn = findViewById(R.id.start_record_button);
Setting_btn = findViewById(R.id.setting_button);
Setting_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//new UdpSendThread().start();
new UdpReceiveThread().start();
Log.i(TAG, "onClick: 2222222222222222222222222");
Intent intent = new Intent(VideoActivity.this, SettingActivity.class);
startActivity(intent);
}
});
Trans_to_Detect.setOnClickListener(new View.OnClickListener() {
selfHome_btn = findViewById(R.id.self_home);
selfHome_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(VideoActivity.this, DetectActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
try {
sendCommand("DIRECTHOME");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
});
battery_warning =findViewById(R.id.warning);
show_status=findViewById(R.id.show_status_button);
battery_warning.setTextColor(Color.RED);
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500); // 闪烁时间间隔
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
battery_warning.startAnimation(anim);
Intent i = getIntent();
mdistance = i.getFloatExtra("Distance",0);
mangle = i.getStringExtra("Angle");
warning_thread = new UdpDataThread();
warning_thread.start();
try {
Condition_Init();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
show_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在这里编写 ImageButton 的点击事件处理逻辑
showPopup(speedStatus,batteryStatus,distanceStatus);
}
});
}
private void Control_Button_Init(){
TakeOff_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("TAKEOFF");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: TTTTTTTTTTTTTTakeoff");
}
});
Landing_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("LAND");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: LLLLLLLLLLLLLLLLLLand");
}
});
Forward_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("FORWARD");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: FFFFFFFForward");
}
});
Back_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("BACKWORD");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: BBBBBBBBackward");
}
});
Left_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("LEFT");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: LLLLLLLLLLLLeft");
}
});
Right_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("RIGHT");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: RRRRRRRRRRight");
}
});
Down_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("DOWN");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: DDDDDDDDDown");
}
});
Up_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("UP");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: UUUUUUUUUUUUUUp");
}
});
TurnLeft_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("TURN_LEFT");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: TTTTTTTTTurnLLLLLLLLLLeft");
}
});
TurnRight_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendCommand("TURN_RIGHT");
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "onClick: TTTTTTTTTTTTurnRRRRRRRRRRight");
}
});
class ReceiveHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
imgShow.setImageBitmap(bp);
}
private void Condition_Init() throws UnknownHostException {
ReceiveHandler receiveHandler = new ReceiveHandler();
UdpReceiveThread StreamThread = new UdpReceiveThread(Recieve_IP,RECEIVE_PORT,receiveHandler);
try {
StreamThread.startListen();
StreamThread.start();
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
Mode_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 执行功能2
try {
changetoManual();
Control_Button_Init();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
} else {
// 执行功能1
// try {
// changetoAuto();
// } catch (UnknownHostException e) {
// throw new RuntimeException(e);
// }
}
}
});
Record_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveVideo(bp);
}
});
}
private void changetoManual() throws UnknownHostException {
sendCommand("STOP");
}
class ReceiveHandler extends Handler{
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int targetWidth = imgShow.getWidth();
int targetHeight = imgShow.getHeight();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bp, targetWidth, targetHeight, true);
imgShow.setImageBitmap(scaledBitmap);
}
});
}
}
}
class SendHandler extends Handler {
@Override
@ -127,152 +351,463 @@ public class VideoActivity extends AppCompatActivity {
super.handleMessage(msg);
}
}
/*
* UDP线
* */
public class UdpReceiveThread extends Thread
{
public class UdpReceiveThread extends Thread {
private DatagramSocket reveSocket;
private String Recieve_IP;
private int RECEIVE_PORT;
private Handler receiveHandler;
public UdpReceiveThread(String ip, int port, Handler handler) {
this.Recieve_IP = ip;
this.RECEIVE_PORT = port;
this.receiveHandler = handler;
}
public void startListen() throws SocketException, UnknownHostException {
reveSocket = new DatagramSocket(RECEIVE_PORT);
}
public void stopListen() {
if (reveSocket != null && !reveSocket.isClosed()) {
listenStatus = false;
//reveSocket.close();
}
}
@Override
public void run()
{
try
{
reveSocket = new DatagramSocket(RECEIVE_PORT);
serverAddr = InetAddress.getByName(Recieve_IP);
//ByteArrayOutputStream out = new ByteArrayOutputStream();
while(listenStatus)
{
byte[] inBuf= new byte[1024*1024];
DatagramPacket inPacket=new DatagramPacket(inBuf,inBuf.length);
//out.write(inPacket.getData());
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(Recieve_IP);
while (listenStatus) {
byte[] inBuf = new byte[1024 * 1024];
DatagramPacket inPacket = new DatagramPacket(inBuf, inBuf.length);
reveSocket.receive(inPacket);
if(!inPacket.getAddress().equals(serverAddr)){
if (!inPacket.getAddress().equals(serverAddr)) {
throw new IOException("未知名的报文");
}
ByteArrayInputStream in = new ByteArrayInputStream(inPacket.getData());
receiveHandler.sendEmptyMessage(1);
bp = BitmapFactory.decodeStream(in);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* UDP线Runnable
* */
class SendRunnable implements Runnable {
byte[] mData;
InetAddress mAddress;
int mPort;
public SendRunnable(byte[] data, InetAddress address, int port) {
mData = data;
mAddress = address;
mPort = port;
}
} catch (Exception e)
{
@Override
public void run() {
try {
// 创建发送数据报文
DatagramPacket packet = new DatagramPacket(mData, mData.length, mAddress, mPort);
// 创建 DatagramSocket 对象并发送数据报文
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
// 关闭 DatagramSocket 对象
socket.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
reveSocket.close();
}
}
}
/*封装函数*/
private void sendCommand(String str) throws UnknownHostException {
byte[] sendData = str.getBytes();
InetAddress address = InetAddress.getByName(SEND_to_IP);
SendRunnable sendRunnable1 = new SendRunnable(sendData, address, SEND_PORT);
mThreadPool.execute(sendRunnable1);
}
/*
* UDP线
* */
public class UdpSendThread extends Thread {
*UDP线
*/
public class UdpDataThread extends Thread {
private DatagramSocket socket;
private boolean running;
private byte[] buffer;
private static final int BUFFER_SIZE = 1024; // 设置接收缓冲区大小
private JSONObject jsonObject;
public UdpDataThread() {
buffer = new byte[BUFFER_SIZE];
}
@Override
public void run() {
running = true;
try {
buf ="test".getBytes();
socket = new DatagramSocket(6666); // 设置接收端口号
while (running) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String receivedData = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
jsonObject = new JSONObject(receivedData);
batteryStatus = jsonObject.getString("battery");
speedStatus = jsonObject.getString("speed");
distanceStatus = jsonObject.getString("distance");
if (batteryStatus.equals("10")) {
battery_warning.setText("电量仅剩"+batteryStatus);}else{
battery_warning.setText("");
}
System.out.println("接收到数据:" + batteryStatus);
System.out.println("接收到数据:" + speedStatus);
System.out.println("接收到数据:" + distanceStatus);
// 在这里处理收到的数据,可以根据实际需求进行解析或其他操作
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
public void stopThread() {
running = false;
}
}
private String findEncoderCodecName(String mimeType) {
MediaCodecList codecList = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
int numCodecs = codecList.getCodecInfos().length;
for (int i = 0; i < numCodecs; i++) {
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (!codecInfo.isEncoder()) {
continue;
}
String[] types = codecInfo.getSupportedTypes();
for (String type : types) {
if (type.equalsIgnoreCase(mimeType)) {
return codecInfo.getName();
}
}
}
return null;
}
// 创建DatagramSocket对象使用端口8888
sendSocket = new DatagramSocket(8888);
MediaCodec codec;
private void saveVideo(Bitmap videoBitmap) {
try {
String codecName = findEncoderCodecName(MediaFormat.MIMETYPE_VIDEO_AVC);
if (codecName != null) {
codec = MediaCodec.createByCodecName(codecName);
// 根据视频尺寸设置编码器参数
MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, videoBitmap.getWidth(), videoBitmap.getHeight());
format.setInteger(MediaFormat.KEY_BIT_RATE, 2000000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
// 配置编码器并启动
codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
Surface inputSurface = codec.createInputSurface();
codec.start();
// 创建保存视频的路径和文件名
String fileName = "video_" + System.currentTimeMillis() + ".mp4";
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/" + fileName;
File videoFile = new File(filePath);
FileOutputStream fileOutputStream = new FileOutputStream(videoFile);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
// 循环编码每一帧
boolean isInputDone = false;
boolean isOutputDone = false;
while (!isOutputDone) {
if (!isInputDone) {
int index = codec.dequeueInputBuffer(10000);
if (index >= 0) {
ByteBuffer inputBuffer = codec.getInputBuffer(index);
inputBuffer.clear();
Canvas canvas = inputSurface.lockCanvas(null);
canvas.drawBitmap(videoBitmap, 0, 0, null);
inputSurface.unlockCanvasAndPost(canvas);
codec.queueInputBuffer(index, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
isInputDone = true;
}
}
serverAddr = InetAddress.getByName(SEND_to_IP);
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputIndex = codec.dequeueOutputBuffer(bufferInfo, 10000);
if (outputIndex >= 0) {
ByteBuffer outputBuffer = codec.getOutputBuffer(outputIndex);
byte[] outData = new byte[bufferInfo.size];
outputBuffer.get(outData);
bufferedOutputStream.write(outData);
codec.releaseOutputBuffer(outputIndex, false);
}
DatagramPacket outPacket = new DatagramPacket(buf, buf.length, serverAddr, SEND_PORT);
sendSocket.send(outPacket);
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
isOutputDone = true;
}
}
sendSocket.close();
sendHandler.sendEmptyMessage(1);
Log.i(TAG, "run: 111111111111111111111111111111111111111111111111");
// 关闭文件流
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.close();
// 通知媒体库更新文件
MediaScannerConnection.scanFile(this, new String[]{videoFile.getAbsolutePath()}, null, null);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "视频保存成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "无法找到支持的视频编码器", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (codec != null) {
codec.stop();
codec.release();
}
}
}
public void showPopup(String speedStatus,String batteryStatus,String distanceStatus) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
TextView speedstatus = dialogView.findViewById(R.id.speed);
speedstatus.setText("当前速度为:"+speedStatus);
TextView batterystatus = dialogView.findViewById(R.id.battery);
batterystatus.setText("当前电量为:"+batteryStatus);
TextView distancestatus = dialogView.findViewById(R.id.distance);
distancestatus.setText("当前距离为:"+distanceStatus);
builder.setView(dialogView);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 点击确定按钮后的操作
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
//*************************************************************************************************
/*public class TelloControlDemo {
//////////////////////////////滑动开关//////////////////////////////
public static class SlideUnlockView extends View{
private final int BG_COLOR = Color.parseColor("#2D2E32"); // 背景颜色
private static final int GUIDE_TEXT_COLOR = Color.WHITE; // 引导文本颜色
private static final int GUIDE_TEXT_SIZE = 100; // 引导文本大小
private static final int INDICATOR_COLOR = Color.WHITE; // 指示器颜色
private static final int INDICATOR_RADIUS = 40; // 指示器半径
private static final int INDICATOR_GAP = 300; // 指示器间距
private static final int ARROW_COLOR = Color.WHITE; // 箭头颜色
private static final int ARROW_SIZE = 20; // 箭头大小
private static final int STATE_LOCKED = 0; // 锁屏状态
private static final int STATE_DRAGGING = 1; // 拖动状态
private static final int STATE_UNLOCKED = 2; // 解锁状态
private Paint mPaint;
private Path mPath;
private int mViewWidth;
private int mViewHeight;
private int mIndicatorCount;
private int mCurrentIndex;
private float mLastX;
private boolean mIsUnlocked;
private int mState;
private OnUnlockListener mOnUnlockListener;
public abstract static class OnUnlockListener {
public class SimpleOnUnlockListener extends OnUnlockListener {
@Override
public void onUnlock() {
// 默认空实现
}
}
public abstract void onUnlock();
}
private DatagramSocket socket;
private InetAddress telloAddress;
private int port = 8889;
public void setOnUnlockListener(OnUnlockListener listener) {
this.mOnUnlockListener = listener;
}
public void main(String[] args) throws IOException {
TelloControlDemo demo = new TelloControlDemo();
demo.start();
public SlideUnlockView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void start() throws IOException {
// Create a UDP socket
socket = new DatagramSocket(9000);
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true); // 抗锯齿
mPaint.setStyle(Paint.Style.FILL);
telloAddress = InetAddress.getByName("192.168.10.1");
mPath = new Path();
// Start the receiver thread
Thread receiverThread = new Thread(new Receiver());
receiverThread.start();
mIsUnlocked = false;
mState = STATE_LOCKED;
System.out.println("\r\n\r\nTello Java Demo.\r\n");
System.out.println("Tello: command takeoff land flip forward back left right \r\n" +
" up down cw ccw speed speed?\r\n");
System.out.println("end -- quit demo.\r\n");
// 指示器个数为 3
mIndicatorCount = 3;
}
while (true) {
try {
// Read user input from console
byte[] buffer = new byte[1024];
System.in.read(buffer);
String message = new String(buffer).trim();
if (message.equalsIgnoreCase("end")) {
System.out.println("...");
socket.close();
break;
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mViewWidth = w;
mViewHeight = h;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
switch (mState) {
case STATE_LOCKED:
drawGuideText(canvas);
drawIndicatorCircles(canvas);
break;
case STATE_DRAGGING:
drawUnlockPath(canvas);
drawUnlockArrow(canvas);
break;
case STATE_UNLOCKED:
if (mOnUnlockListener != null) {
mOnUnlockListener.onUnlock();
}
break;
}
}
// Send command to Tello drone
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, telloAddress, port);
socket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
}
private void drawGuideText(Canvas canvas) {
mPaint.setColor(BG_COLOR);
canvas.drawRect(0, 0, mViewWidth, mViewHeight, mPaint);
mPaint.setColor(GUIDE_TEXT_COLOR);
mPaint.setTextSize(GUIDE_TEXT_SIZE);
String guideText = "即将起飞";
float textWidth = mPaint.measureText(guideText);
float textX = mViewWidth / 2 - textWidth / 2;
float textY = mViewHeight * 2 / 3;
canvas.drawText(guideText, textX, textY, mPaint);
}
private void drawIndicatorCircles(Canvas canvas) {
mPaint.setColor(INDICATOR_COLOR);
float cy = mViewHeight / 2;
float startX = mViewWidth / 2 - INDICATOR_GAP * (mIndicatorCount - 1) / 2;
float radius = INDICATOR_RADIUS;
Path path = new Path();
for (int i = 0; i < mIndicatorCount; i++) {
float cx = startX + INDICATOR_GAP * i;
path.addCircle(cx, cy, radius, Path.Direction.CCW);
}
canvas.drawPath(path, mPaint);
}
private class Receiver implements Runnable {
private void drawUnlockPath(Canvas canvas) {
mPaint.setColor(INDICATOR_COLOR);
float cy = mViewHeight / 2;
float startX = mViewWidth / 2 - INDICATOR_GAP * (mIndicatorCount - 1) / 2;
float currentX = Math.max(Math.min(mLastX, mViewWidth - INDICATOR_RADIUS), startX + INDICATOR_GAP * mCurrentIndex);
Path path = new Path();
path.moveTo(startX + INDICATOR_RADIUS, cy);
path.lineTo(currentX - INDICATOR_RADIUS, cy);
path.arcTo(new RectF(currentX - INDICATOR_RADIUS, cy - INDICATOR_RADIUS,
currentX + INDICATOR_RADIUS, cy + INDICATOR_RADIUS), -90, 180);
path.lineTo(startX + INDICATOR_GAP * (mIndicatorCount - 1), cy);
canvas.drawPath(path, mPaint);
}
@Override
public void run() {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
private void drawUnlockArrow(Canvas canvas) {
mPaint.setColor(ARROW_COLOR);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
Path arrowPath = new Path();
float x = Math.max(Math.min(mLastX, mViewWidth - INDICATOR_RADIUS - ARROW_SIZE), mViewWidth / 2 + INDICATOR_GAP * (mCurrentIndex - 1));
float y = mViewHeight / 2;
arrowPath.moveTo(x - ARROW_SIZE, y - ARROW_SIZE);
arrowPath.lineTo(x, y);
arrowPath.lineTo(x - ARROW_SIZE, y + ARROW_SIZE);
canvas.drawPath(arrowPath, mPaint);
}
while (true) {
try {
// Receive data from Tello drone
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mState == STATE_LOCKED) {
mState = STATE_DRAGGING;
mCurrentIndex = 0;
invalidate();
return true;
}
}
break;
case MotionEvent.ACTION_MOVE:
if (mState == STATE_DRAGGING) {
mLastX = x;
int index = (int) ((x - mViewWidth / 2) / INDICATOR_GAP);
index = Math.max(Math.min(index, mIndicatorCount - 1), 0);
if (index != mCurrentIndex) {
mCurrentIndex = index;
invalidate();
}
if (mCurrentIndex == mIndicatorCount - 1) {
mState = STATE_UNLOCKED;
mIsUnlocked = true;
}
return true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mState == STATE_DRAGGING) {
mState = STATE_LOCKED;
mCurrentIndex = 0;
invalidate();
return true;
}
break;
}
return super.onTouchEvent(event);
}
}*/
}
}
private void shutdown(){
warning_thread.stopThread();
mThreadPool.shutdownNow();
}
@Override
public void onBackPressed() {
// 返回到 MainActivity
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish(); // 结束 VideoActivity
}
@Override
protected void onDestroy() {
super.onDestroy();
// 关闭线程
shutdown();
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 992 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 600 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/auto" android:state_checked="false" /> <!-- 当未选中时的背景 -->
<item android:drawable="@drawable/manual" android:state_checked="true" /> <!-- 当选中时的背景 -->
</selector>

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/zidongkongzhi" android:state_checked="false" /> <!-- 当未选中时的图标 -->
<item android:drawable="@drawable/shoudong" android:state_checked="true" /> <!-- 当选中时的图标 -->
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 设置透明背景色 -->
<solid android:color="#80000000" />
<!-- 设置一个黑色边框 -->
<stroke
android:width="2px"
android:color="#000000" />
<!-- 设置四个圆角的半径 -->
<corners
android:bottomLeftRadius="10px"
android:bottomRightRadius="10px"
android:topLeftRadius="10px"
android:topRightRadius="10px" />
<!-- 设置一下边距,让空间大一点 -->
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>

@ -1,68 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 显示无人机回传图像的控件 -->
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_height="match_parent"
android:scaleType="centerCrop"
/>
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true" />
<!-- 左侧竖直轴按钮 -->
<RelativeLayout
android:id="@+id/left_vertical_button_layout"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_below="@+id/imageView">
android:layout_above="@id/imageView"
android:layout_marginLeft="50dp"
android:layout_marginBottom="10dp"
android:layout_gravity="left|bottom"
android:layout_marginTop="20dp">
<!-- 上升按钮 -->
<ImageButton
android:id="@+id/up_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="@null"
android:contentDescription="@string/up_button"
android:src="@drawable/img" />
android:src="@drawable/up"
android:scaleType="centerCrop"
/>
<!-- 下降按钮 -->
<ImageButton
android:id="@+id/down_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@null"
android:contentDescription="@string/down_button"
android:src="@drawable/img" />
android:src="@drawable/down"
android:scaleType="centerCrop"
/>
<!-- 左旋转按钮 -->
<ImageButton
android:id="@+id/rotate_left_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:background="@null"
android:contentDescription="@string/turn_left_button"
android:src="@drawable/img" />
android:src="@drawable/turnleft"
android:scaleType="centerCrop"
/>
<!-- 右旋转按钮 -->
<ImageButton
android:id="@+id/rotate_right_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:background="@null"
android:contentDescription="@string/turn_right_button"
android:src="@drawable/img" />
android:src="@drawable/turnright"
android:scaleType="centerCrop"
/>
</RelativeLayout>
@ -70,9 +83,10 @@
android:id="@+id/top_horizontal_button_layout"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_above="@id/imageView"
android:layout_marginRight="50dp"
android:layout_marginBottom="10dp"
android:layout_gravity="right|bottom"
android:layout_alignParentEnd="true">
<!-- 向左按钮 -->
@ -85,7 +99,9 @@
android:layout_centerVertical="true"
android:background="@null"
android:contentDescription="@string/move_left_button"
android:src="@drawable/img" />
android:src="@drawable/moveleft"
android:scaleType="centerCrop"
/>
<!-- 向右按钮 -->
<ImageButton
@ -96,7 +112,9 @@
android:layout_centerVertical="true"
android:background="@null"
android:contentDescription="@string/move_right_button"
android:src="@drawable/img" />
android:src="@drawable/moveright"
android:scaleType="centerCrop"
/>
<!-- 向前移动按钮 -->
<ImageButton
@ -106,7 +124,9 @@
android:layout_centerHorizontal="true"
android:background="@null"
android:contentDescription="@string/move_forward_button"
android:src="@drawable/img" />
android:src="@drawable/moveforward"
android:scaleType="centerCrop"
/>
<!-- 向后移动按钮 -->
<ImageButton
@ -115,41 +135,137 @@
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:contentDescription="@string/move_back_button"
android:layout_marginEnd="50dp"
android:contentDescription="@string/move_back_button"
android:background="@null"
android:src="@drawable/img" />
android:src="@drawable/movebackward"
android:scaleType="centerCrop"
/>
</RelativeLayout>
<LinearLayout
android:id="@+id/takeoff_landing_buttons_layout"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal">
android:layout_marginBottom="15dp"
android:layout_gravity="center|bottom"
android:orientation="horizontal"
>
<!-- 降落按钮 -->
<Button
<ImageButton
android:id="@+id/landing_button"
android:layout_width="80dp"
android:layout_height="61dp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="left"
android:layout_marginRight="10dp"
android:contentDescription="@string/landing_button123"
android:layout_weight="1"
android:text="降落" />
android:background="@null"
android:src="@drawable/landing"
android:scaleType="centerCrop"
/>
<!-- 起飞按钮 -->
<Button
<ImageButton
android:id="@+id/takeoff_button"
android:layout_width="80dp"
android:layout_height="match_parent"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="right"
android:layout_weight="1"
android:text="起飞" />
android:background="@null"
android:scaleType="centerCrop"
android:src="@drawable/takeoff"
android:text="起飞"
android:contentDescription="@string/takeoff_button"
/>
<!-- android:onClick="showDialog"-->
</LinearLayout>
</RelativeLayout>
<!-- 添加三个按钮,用于设置、开始录制和显示当前状态 -->
<LinearLayout
android:id="@+id/top_left_buttons_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:layout_gravity="left|top">
<ImageButton
android:id="@+id/setting_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@null"
android:contentDescription="@string/setting_button"
android:scaleType="centerInside"
android:src="@drawable/setting" />
<ImageButton
android:id="@+id/start_record_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@null"
android:layout_marginLeft="20dp"
android:src="@drawable/record"
android:contentDescription="@string/start_record_button"
android:text="开始录制"
android:scaleType="centerCrop"
/>
<ImageButton
android:id="@+id/show_status_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@null"
android:layout_marginLeft="20dp"
android:src="@drawable/status"
android:text="当前状态"
android:scaleType="centerCrop"
android:contentDescription="@string/show_status_button"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/top_right_buttons_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:layout_gravity="right|top">
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_weight="2"
android:background="@drawable/selector_toggle_icon"
android:text="ToggleButton"
android:textOff=""
android:textOn="" />
<ImageButton
android:id="@+id/self_home"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@null"
android:layout_marginLeft="20dp"
android:src="@drawable/selfhome"
android:text="自动返航"
android:scaleType="centerCrop"
android:contentDescription="@string/show_status_button"
/>
</LinearLayout>
<TextView
android:id="@+id/warning"
android:layout_width="131dp"
android:layout_height="40dp"
android:layout_marginTop="70dp"
android:text=""
android:textSize="22dp"/>
</FrameLayout>

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/bg"
tools:context=".MainActivity">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/android"
android:layout_marginTop="200dp"
android:layout_gravity="center"/>
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="账号:"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码:"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"/>
<CheckBox
android:id="@+id/remember_check"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="记住密码"
android:layout_marginLeft="280dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/login"
android:layout_width="100dp"
android:layout_height="57dp"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="登录" />
</LinearLayout>
</LinearLayout>

@ -12,55 +12,41 @@
android:id="@+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageButton
android:id="@+id/change_btn"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="50dp"
android:clickable="true"
android:scaleType="centerInside"
android:src="@drawable/wurenji"
app:backgroundTint="#FFF"
app:backgroundTintMode="screen"
app:fabSize="normal"
app:hoveredFocusedTranslationZ="18dp"
app:pressedTranslationZ="18dp" />
<!--浮动按钮-->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_poi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="20dp"
android:clickable="true"
android:src="@drawable/icon_favorite_red"
android:visibility="gone"
app:backgroundTint="#FFF"
app:backgroundTintMode="screen"
app:hoveredFocusedTranslationZ="18dp"
app:pressedTranslationZ="18dp" />
<!--浮动按钮 清空marker-->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/clearMarker_btn"
android:layout_width="wrap_content"
android:layout_above="@+id/fab_poi"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginEnd="20dp"
android:clickable="true"
android:onClick="clearAllMarker"
app:fabSize="normal"
android:src="@drawable/icon_clear"
app:backgroundTint="#FFF"
android:visibility="invisible"
app:backgroundTintMode="screen"
app:hoveredFocusedTranslationZ="18dp"
app:pressedTranslationZ="18dp" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/change_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginEnd="20dp"
android:clickable="true"
android:onClick="changeAct"
app:fabSize="normal"
android:src="@drawable/img"
app:backgroundTint="#FFF"
android:visibility="invisible"
app:backgroundTintMode="screen"
app:fabSize="normal"
app:hoveredFocusedTranslationZ="18dp"
app:pressedTranslationZ="18dp" />

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80000000" />
<!-- 这里是其他控件 -->
<LinearLayout
android:layout_width="414dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#80FFFFFF"
android:orientation="vertical"
android:padding="16dp">
<ImageButton
android:id="@+id/returns"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="bottom"
android:background="#00000000"
android:scaleType="centerInside"
app:srcCompat="@drawable/returns" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:background="@drawable/txt_radiuborder">
<TextView
android:layout_width="150dp"
android:layout_height="50dp"
android:text="电量预警"
android:textColor="@color/white"
android:textSize="28dp" />
<SeekBar
android:id="@+id/warning_num"
android:layout_width="180dp"
android:layout_height="50dp"
android:max="100"
android:progress="0"
android:thumbTint='@color/teal_200' />
<TextView
android:id="@+id/Battery_warning"
android:layout_width="77dp"
android:layout_height="30dp"
android:text="0"
android:textColor="@color/white"
android:textSize="18dp" />
</LinearLayout>
<Switch
android:id="@+id/photo"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:text="图像高画质"
android:textSize="28dp"
android:textColor="@color/white"
android:background="@drawable/txt_radiuborder"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:background="@drawable/txt_radiuborder">
<TextView
android:layout_width="150dp"
android:layout_height="50dp"
android:text="飞行速度"
android:textColor="@color/white"
android:textSize="28dp" />
<SeekBar
android:id="@+id/speed"
android:layout_width="180dp"
android:layout_height="50dp"
android:max="90"
android:progress="0"
android:thumbTint='@color/teal_200' />
<TextView
android:id="@+id/tvProgress"
android:layout_width="77dp"
android:layout_height="30dp"
android:text="10"
android:textColor="@color/white"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>

@ -0,0 +1,40 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/dialogTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="16dp"
android:text="当前状态"
android:textColor="#000000"
android:textSize="28sp" />
<TextView
android:id="@+id/battery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="当前电量:"
android:padding="16dp"
android:textSize="18dp"
android:textColor="#000000" />
<TextView
android:id="@+id/speed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="当前速度:"
android:padding="16dp"
android:textColor="#000000" />
<TextView
android:id="@+id/distance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="当前距离:"
android:textSize="18dp"
android:padding="16dp"
android:textColor="#000000" />
</LinearLayout>

@ -0,0 +1,21 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<view
android:id="@+id/slide_unlock_view"
class="com.example.sixaunyi.VideoActivity$SlideUnlockView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundColor="#03A9F4"
app:lockText="Slide to unlock"
app:sliderColor="@color/purple_200"
app:textColor="@color/purple_500"
app:textSize="50sp"
app:unlockText="Unlocked!" />
<!-- 其他控件 -->
</LinearLayout>

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SlideUnlockView">
<attr name="textSize" format="dimension" />
<attr name="textColor" format="color" />
<attr name="sliderColor" format="color" />
<attr name="backgroundColor" format="color" />
<attr name="unlockText" format="string" />
<attr name="lockText" format="string" />
</declare-styleable>
</resources>

@ -14,6 +14,12 @@
<string name="move_back_button">向后按钮</string>
<string name="turn_left_button">向左旋转</string>
<string name="turn_right_button">向右旋转</string>
<string name="setting_button">设置</string>
<string name="start_record_button">开始录制</string>
<string name="show_status_button">查看状态</string>
<string name="landing_button123">降落按钮</string>
<string name="takeoff_button">降落按钮</string>
<string name="self_home_button">自动返航按钮</string>
<string name="hello_first_fragment">Hello first fragment</string>
<string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string>
</resources>

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="android:background">@android:color/transparent</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowAnimationStyle">@style/MyDialogAnimation</item>
</style>
<style name="MyDialogAnimation" parent="@android:style/Animation">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsTranslucent">true</item>
</style>
</resources>

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="TransparentTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#00000000</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation</item>
</style>
</resources>
Loading…
Cancel
Save