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/xinyingpower/microphoto/MainActivity.java

450 lines
17 KiB
Java

package com.xinyingpower.microphoto;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Path;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.SystemClock;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import com.dowse.camera.client.DSCameraManager;
import com.xinyingpower.microphoto.databinding.ActivityMainBinding;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.SharedPreferences;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
private static int MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE = 100;
// Used to load the 'microphoto' library on application startup.
static {
System.loadLibrary("microphoto");
}
private ActivityMainBinding binding;
private int defaultDataSubId;
@Override
protected void onDestroy() {
super.onDestroy();
}
protected class AppConfig {
public String cmdid;
public String server;
public int port;
public int protocol;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display defaultDisplay = windowManager.getDefaultDisplay();
int width = defaultDisplay.getWidth();
int height = defaultDisplay.getHeight();
Log.d(TAG, "Screen Size: " + width + " x " + height);
String cmdid = "0123456789ABCDEFG";
String server = "47.96.238.157";
Integer port = new Integer(6891);
Integer protocol = new Integer(0xFF00); // 0xFF00
AppConfig appConfig = getAppConfig();
binding.cmdid.setText(appConfig.cmdid);
binding.server.setText(appConfig.server);
binding.port.setText(Integer.toString(appConfig.port));
this.binding.startServBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String[] accessPermissions = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.FOREGROUND_SERVICE,
Manifest.permission.READ_PHONE_STATE,
/*Manifest.permission.PACKAGE_USAGE_STATS,*/
/*Manifest.permission.SET_TIME,*/
};
boolean needRequire = false;
for (String access : accessPermissions) {
int curPermission = ActivityCompat.checkSelfPermission(MainActivity.this, access);
if (curPermission != PackageManager.PERMISSION_GRANTED) {
needRequire = true;
break;
}
}
if (needRequire) {
ActivityCompat.requestPermissions(
MainActivity.this,
accessPermissions,
MY_PERMISSIONS_REQUEST_FOREGROUND_SERVICE);
return;
}
int channel = 2;
String path = buildPhotoDir(channel);
String fileName = buildPhotoFileName(channel, 255);
// MainActivity.this.takePhoto(channel, 255, path, fileName);
String cmdid = MainActivity.this.binding.cmdid.getText().toString();
String server = MainActivity.this.binding.server.getText().toString();
int port = Integer.parseInt(MainActivity.this.binding.port.getText().toString());
int protocol = 0xFF00;
MainActivity.this.saveAppConfig(cmdid, server, port, protocol);
Intent intent = new Intent(MainActivity.this, MicroPhotoService.class);
intent.setAction(MicroPhotoService.ACTION_START);
intent.putExtra("cmdid", cmdid);
intent.putExtra("server", server);
intent.putExtra("port", port);
intent.putExtra("protocol", protocol);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MainActivity.this.startForegroundService(intent);
} else {
MainActivity.this.startService(intent);
}
binding.startServBtn.setEnabled(false);
binding.stopServBtn.setEnabled(true);
}
});
this.binding.takePhotoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MicroPhotoService.takePhoto(MainActivity.this.getApplicationContext(), 1, 255, true);
}
});
this.binding.takePhotoBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MicroPhotoService.takePhoto(MainActivity.this, 2, 255, true);
}
});
this.binding.takePhotoBtn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MicroPhotoService.takePhoto(MainActivity.this, 3, 255, true);
}
});
this.binding.takePhotoBtn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MicroPhotoService.takePhoto(MainActivity.this, 4, 255, true);
}
});
this.binding.stopServBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MicroPhotoService.class);
intent.setAction(MicroPhotoService.ACTION_STOP);
MainActivity.this.stopService(intent);
binding.startServBtn.setEnabled(true);
binding.stopServBtn.setEnabled(false);
}
});
binding.simchange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
defaultDataSubId = getDefaultDataSubId();
System.out.println(defaultDataSubId);
}
});
binding.simchange2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (defaultDataSubId == 0) {
setDefaultDataSubId(1);
} else {
if (defaultDataSubId == 1) {
setDefaultDataSubId(2);
} else {
setDefaultDataSubId(1);
}
}
}
});
if (!TextUtils.isEmpty(appConfig.cmdid) && !TextUtils.isEmpty(appConfig.server) && appConfig.port != 0) {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (binding.startServBtn.isEnabled()) {
binding.startServBtn.performClick();
}
}
};
handler.postDelayed(runnable, 5000);
}
}
private void setDefaultDataSubId(int subId) {
SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
try {
Method method = subscriptionManager.getClass().getDeclaredMethod("setDefaultDataSubId", int.class);
method.invoke(subscriptionManager, subId);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method method1 = telephonyManager.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
method1.invoke(telephonyManager, true);
} catch (Exception e) {
Log.e(TAG, "wjz debug setDefaultDataSubId: error is " + e.getMessage());
}
}
private AppConfig getAppConfig() {
AppConfig appConfig = new AppConfig();
String appPath = MicroPhotoService.buildAppDir(this.getApplicationContext());
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(new FileInputStream(new File(appPath + "data/App.json")), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
StringBuilder stringBuilder = new StringBuilder();
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
appConfig.cmdid = jsonObject.getString("CMDID");
appConfig.server = jsonObject.getString("Server");
appConfig.port = jsonObject.getInt("Port");
appConfig.protocol = jsonObject.getInt("Protocol");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (Exception ex) {
}
}
}
return appConfig;
}
private void saveAppConfig(String cmdid, String server, int port, int protocol) {
String appPath = MicroPhotoService.buildAppDir(this.getApplicationContext());
OutputStreamWriter outputStreamWriter = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("CMDID", cmdid);
jsonObject.put("Server", server);
jsonObject.put("Port", port);
jsonObject.put("Protocol", protocol);
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(appPath + "data/App.json")), "UTF-8");
outputStreamWriter.write(jsonObject.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
if (outputStreamWriter != null) {
try {
outputStreamWriter.close();
} catch (Exception ex) {
}
}
}
}
private int getDefaultDataSubId() {
SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
try {
Method method = subscriptionManager.getClass().getDeclaredMethod("getDefaultDataSubscriptionId");
return (int) method.invoke(subscriptionManager);
} catch (Exception e) {
Log.e(TAG, "wjz debug getDefaultDataSubId: error is " + e.getMessage());
}
return 0;
}
protected void takePhoto() {
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "photo.jpg");
boolean res = false;
res = DSCameraManager.getInstace().init();
res = DSCameraManager.getInstace().takePhoto(file.getAbsolutePath(), 2);
if (!res) {
int aa = 0;
}
res = DSCameraManager.getInstace().unInit();
}
String buildPhotoDir(int channel) {
File path = new File(Environment.getExternalStorageDirectory(), "com.xinyingpower.com/photos/");
if (!path.exists() && !path.mkdirs()) {
return null;
}
String p = path.getAbsolutePath();
if (!p.endsWith(File.separator)) {
p += File.separator;
}
return p;
}
String buildPhotoFileName(int channel, int preset) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "img_" + Integer.toString(channel) + "_" + Integer.toHexString(preset).toUpperCase() + "_" + date + ".jpg";
return photoFile;
}
private void takePhoto(int aa) {
System.out.println("Preparing to take photo");
Camera camera = null;
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
SystemClock.sleep(1000);
Camera.getCameraInfo(camIdx, cameraInfo);
try {
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
System.out.println("Camera not available: " + camIdx);
camera = null;
//e.printStackTrace();
}
try {
if (null == camera) {
System.out.println("Could not get camera instance");
} else {
System.out.println("Got the camera, creating the dummy surface texture");
//SurfaceTexture dummySurfaceTextureF = new SurfaceTexture(0);
try {
//camera.setPreviewTexture(dummySurfaceTextureF);
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
} catch (Exception e) {
System.out.println("Could not set the surface preview texture");
e.printStackTrace();
}
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File path = getApplicationContext().getFilesDir();
// String appPath = path.getAbsolutePath();
File pictureFileDir = path;
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "PictureFront_" + "_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File mainPicture = new File(filename);
// addImageFile(mainPicture);
try {
FileOutputStream fos = new FileOutputStream(mainPicture);
fos.write(data);
fos.close();
System.out.println("image saved");
} catch (Exception error) {
System.out.println("Image could not be saved");
}
camera.release();
}
});
}
} catch (Exception e) {
camera.release();
}
}
}
/**
* A native method that is implemented by the 'microphoto' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public native boolean takePhoto(int channel, int preset, String path, String fileName);
}