Developing AI Prompts for Code Generation. https://oflameron.ru/Valery_Shmelev_5eng.pdf AI-powered Code Generation We'll develop an AI prompt for Android Studio Java code generation for an entropy generator—a giant pseudo-random number. The length of the number in the request is limited by the file size of 10124000 bytes. It can be changed to a larger value. The generator uses the randomness of the least significant bit of data from the smartphone's accelerometer's X-ray sensor. It's possible, in principle, to significantly improve the efficiency of such random number generation by adding values ​​from cryptographic algorithms (such as Blum-Blum-Shub), from internet radio streams, microphone data, multiple text-to-voice conversions, etc. The request was tested in the free chat at chat.deepseek.com. The app was tested on a Samsung S23 smartphone running Android 14. A file with a pseudo-random number is saved to the smartphone's Download folder and can be copied to a second smartphone, after which secure messaging can be established using a Vernam code (XOR transformation). -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Technical requirements (prompt) for the "LargeEntropy" app 1. MAIN CHARACTERISTICS -Goal: Generate an entropy file based on accelerometer/gyroscope data -Platform: Android 14 (API 33), minimum support for Android 5.0 (API 21) -Language: Java -Architecture: Single Activity with a simple MVP structure -Performance requirements: Minimal resource consumption, background sensor operation 2. TECHNOLOGIES AND LIBRARIES - Android SDK 33 - AndroidX: AppCompat, Core, Activity - Sensor API (Hardware Sensor Framework) - File I/O (java.io) - BigInteger for processing numeric data - Handler for periodic tasks - AlertDialog for user messages - Logging for debugging - Permission Handling Android 11+ 3. PERMISSIONS 3.1 Required permissions: AndroidManifest.xml: xml 3.2 Permission Request Logic: 1. Android Version Check: - API >= 30: Use MANAGE_EXTERNAL_STORAGE - API < 30: Use WRITE_EXTERNAL_STORAGE 2. Request Process: a) Check current permissions b) If permission is denied -> show an explanation dialog c) For MANAGE_EXTERNAL_STORAGE: Open system settings d) For WRITE_EXTERNAL_STORAGE: Standard permission request 3. Result handling: - Success: Continue initialization - Failure: Show a message and terminate the application 4. VARIABLES AND TYPES IN MainActivity.java 4.1 Constants: java private static final String TAG = "LargeEntropy"; // Tag for logging private static final int FSize = 1024000; // Target file size (1MB) private static final int PERMISSION_REQUEST_LEGACY = 100; // Request code for APIs < 30 private static final int MANAGE_STORAGE_REQUEST = 101; // Request code for API >= 30 4.2 UI References: java private TextView tvStatus; // TextView for displaying status and file size private Button btnExit; // Button for terminating the application 4.3 Sensor Objects: java private SensorManager sensorManager; // Sensor manager for accessing hardware sensors private Sensor sensor; // Current active sensor (accelerometer or gyroscope) private SensorEventListener sensorListener; // Sensor event listener 4.4 File Objects: java private File dataFile; // File object czechentropy.mp4 private FileOutputStream fos; // Stream for writing to file 4.5 Data Processing Variables: java private char LeastSignificantDigit = '0'; // Current digit (last written) private char LeastSignificantDigit2 = '0'; // New digit (received from the sensor) 4.6 State Flags: java private boolean isRunning = true; // Flag indicating whether the application is running private boolean hasStoragePermission = false; // Flag indicating whether storage permissions are present 4.7 Threading Objects: java private Handler handler; // Handler for periodic tasks in the UI thread private Runnable fileCheckRunnable; // Task for periodically checking file size 5. LOGGING 5.1 Logging levels: java Log.d(TAG, "Information messages"); // DEBUG - general information Log.i(TAG, "Important events"); // INFO - key events Log.w(TAG, "Warnings"); // WARN - non-critical errors Log.e(TAG, "Critical errors"); // ERROR - critical errors Log.e(TAG, "=== Least Significant Digit ===" + digit); // Special log for digits 5.2 Key logging points: 1. Application initialization 2. Requesting and receiving permissions 3. Creating/opening a file 4. Connecting the sensor 5. Receiving each new digit 6. Writing to the file 7. Checking the file size 8. Errors at all stages 6. DIGITAL VALIDATION 6.1 Validation algorithm: java // Step 1: Receiving a value from the sensor (X-axis only) float xValue = event.values[0]; // Step 2: Converting float to string String valueStr = Float.toString(xValue); // Step 3: Cleaning the string (removing the period and minus signs) valueStr = valueStr.replace(".", "").replace("-", ""); // Step 4: Remove leading zeros while (valueStr.startsWith("0") && valueStr.length() > 1) { valueStr = valueStr.substring(1); } // Step 5: Check for an empty string if (valueStr.isEmpty()) return; // Step 6: Convert to BigInteger BigInteger bigInt = new BigInteger(valueStr); String bigIntStr = bigInt.toString(); // Step 7: Extract the last digit if (!bigIntStr.isEmpty()) { char digit = bigIntStr.charAt(bigIntStr.length() - 1); // Step 8: Validate a digit (0-9) if (digit >= '0' && digit <= '9') { // Step 9: Logging Log.e(TAG, "=== Least Significant Digit ===" + digit); // Step 10: Compare with the previous digit if (previousDigit != digit) { // Step 11: Write to file writeDigitToFile(previousDigit); previousDigit = digit; } } } 7. ERROR HANDLING 7.1 Error Handling Levels: 1. Permission Level: - Storage access denied - User denied permissions 2. File System Level: - Storage unavailable (not mounted) - Failed to create folder - Failed to create file - Error writing to file - Error reading file 3. Sensor Level: - Sensors unavailable - Listener registration error - Sensor data processing error 4. Data Level: - Incorrect sensor data - Type conversion error - Digit validation error 7.2 Handling Mechanisms: java // 1. Try-Catch for critical operations try { // Critical code } catch (IOException e) { Log.e(TAG, "I/O error", e); showErrorToUser("Error working with file: " + e.getMessage()); } catch (SecurityException e) { Log.e(TAG, "Security Error", e); showErrorToUser("No permission: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Unknown error", e); showErrorToUser("An error occurred: " + e.getMessage()); } // 2. Pre-operation checks if (!isStorageAvailable()) { showErrorToUser("Storage unavailable"); return; } // 3. Graceful degradation if (sensor == null) { Log.w(TAG, "Sensor unavailable, operation without generating data"); tvStatus.setText("Sensors unavailable - data collection impossible"); // The application continues to run, but without generating any messages. } 8. USER MESSAGES 8.1 Message Types: java // 1. Toast - short notifications Toast.makeText(context, "Message", Toast.LENGTH_SHORT).show(); // 2. AlertDialog - important messages requiring attention new AlertDialog.Builder(context) .setTitle("Title") .setMessage("Detailed message") .setPositiveButton("OK", null) .show(); // 3. Status TextView - persistent information tvStatus.setText("Current status: " + status); // 4. Log - for developers Log.d(TAG, "Debug information"); 8.2 Key user messages: 1. Initial: - "Checking permissions..." - "Starting application..." 2. Permissions: - "Access to storage is required to create the file czechentropy.mp4" - "Access denied. The application will close." 3. File System: - "Storage Unavailable" - "File Created" - "File Found. Size: X Bytes" 4. Sensors: - "Accelerometer Connected" - "Gyroscope Connected" - "No Sensors Available" 5. Generation Process: - "File Size: X / 1024000 Bytes" - "Maximum Entropy Made" 6. Errors: - "File Creation Error" - "Sensor Error: [Description]" - "Failed to Access Storage" 9. MAIN METHODS of MainActivity 9.1 Lifecycle Methods: java onCreate() - UI initialization, permission request onDestroy() - Resource release, unsubscribe from sensors onRequestPermissionsResult() - Processing the result of the permission request onActivityResult() - Processing the result of the system request (MANAGE_EXTERNAL_STORAGE) 9.2 Permission Methods: java checkPermissions() - Determine required permissions requestManageExternalStorage() - MANAGE_EXTERNAL_STORAGE request (API 30+) setupApp() - Initialization after receiving permissions 9.3 File System Methods: java isStorageAvailable() - Check storage availability setupFile() - Create/open the czechentropy.mp4 file loadLastDigit() - Load the last digit from file startFileCheck() - Starts a periodic file size check stopEverything() - Gracefully terminates work with a file 9.4 Methods for Working with Sensors: java setupSensor() - Accelerometer/gyroscope initialization SensorEventListener - Sensor data handler (inner class) 9.5 User Interface Methods: java showErrorToUser() - Displays errors to the user updateFileSize() - Updates the file size display exitApp() - Gracefully exits the application 10. CODE REQUIREMENTS 10.1 Code Structure: 1. Imports (grouped by type) 2. Constants and static variables 3. Instance variables 4. Activity lifecycle methods 5. Permission methods 6. Initialization methods 7. File methods 8. Sensors 9. UI and Error Handling Methods 10. Helper Methods 10.2 Naming Rules: - Constants: UPPER_SNAKE_CASE - Variables: camelCase - Methods: camelCase() - Classes: PascalCase - Logging Tags: "ClassName" 10.3 Null and Exception Handling: - All external objects are checked for null - Critical operations in try-catch - Resources are freed in finally or onDestroy Summary Code Generation Request: Generate the complete Java code for MainActivity.java, activity_main.xml, and AndroidManifest.xml based on the above specifications. Requirements: 1. The code must be as simple and straightforward as possible. 2. All variables must be explicitly typed. 3. Be sure to include all the described checks and error handling. 4. Implement logging as described in Section 5. 5. Add digit validation as in Section 6. 6. Implement error handling as in Section 7. 7. Enable user messages as in Section 8. 8. Maintain the method structure as in Section 9. 9. Follow the code requirements in Section 10. Pay special attention to: - Correct handling of permissions on Android 14 - Stable operation of sensors - Reliable handling of file operations - Clear user messages - Full logging for debugging -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- (c) by Valery Shmelev https://oflameron.ru/Valery_Shmelev_5eng.pdf https://oflameron.myfilebase.site/ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Project listing -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- MainActivity.java package com.example.largeentropy; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.Settings; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.math.BigInteger; public class MainActivity extends AppCompatActivity { private static final String TAG = "LargeEntropy"; private static final int FSize = 1024000; private SensorManager sensorManager; private Sensor sensor; private TextView tvStatus; private Button btnExit; private File dataFile; private FileOutputStream fos; private char LeastSignificantDigit = '0'; private char LeastSignificantDigit2 = '0'; private boolean isRunning = true; private Handler handler = new Handler(); private Runnable fileCheckRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "Application launched"); tvStatus = findViewById(R.id.tvStatus); btnExit = findViewById(R.id.btnExit); tvStatus.setText("Checking permissions..."); btnExit.setOnClickListener(v -> { Log.d(TAG, "Exit button pressed"); stopEverything(); finish(); System.exit(0); }); // Check and request permissions checkPermissions(); } private void checkPermissions() { // For Android 11+ use MANAGE_EXTERNAL_STORAGE if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Environment.isExternalStorageManager()) { Log.d(TAG, "MANAGE_EXTERNAL_STORAGE already exists"); setupApp(); } else { requestManageExternalStorage(); } } else { // For older versions if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { setupApp(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100); } } } private void requestManageExternalStorage() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Storage access"); builder.setMessage("The application requires storage access to work with the file czechentropy.mp4"); builder.setPositiveButton("Allow", (dialog, which) -> { try { Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); intent.setData(android.net.Uri.parse("package:" + getPackageName())); startActivityForResult(intent, 101); } catch (Exception e) { Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); startActivityForResult(intent, 101); } }); builder.setNegativeButton("Cancel", (dialog, which) -> { tvStatus.setText("Access denied. The application will close."); Toast.makeText(this, "Access denied", Toast.LENGTH_LONG).show(); finish(); }); builder.setCancelable(false); builder.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 101) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Environment.isExternalStorageManager()) { setupApp(); } else { tvStatus.setText("Access denied"); Toast.makeText(this, "Access denied", Toast.LENGTH_LONG).show(); } } } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 100 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { setupApp(); } else { tvStatus.setText("Permission denied"); Toast.makeText(this, "Permission denied", Toast.LENGTH_LONG).show(); } } private void setupApp() { Log.d(TAG, "Application settings"); // Check the storage String storageState = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(storageState)) { tvStatus.setText("Storage unavailable: " + storageState); Toast.makeText(this, "Storage unavailable", Toast.LENGTH_LONG).show(); return; } // File setup if (!setupFile()) { return; } // Sensor setup setupSensor(); // Start checking the file startFileCheck(); } private boolean setupFile() { try { File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); Log.d(TAG, "Download folder: " + downloadDir.getAbsolutePath()); if (!downloadDir.exists()) { if (!downloadDir.mkdirs()) { tvStatus.setText("Error: I can't create the Download folder"); return false; } } dataFile = new File(downloadDir, "czechentropy.mp4"); Log.d(TAG, "File: " + dataFile.getAbsolutePath()); if (dataFile.exists()) { long fileSize = dataFile.length(); Log.d(TAG, "File exists, size: " + fileSize + " bytes"); tvStatus.setText("File found. Size: " + fileSize + " bytes"); if (fileSize >= FSize) { tvStatus.setText("Maximum Entropy Made"); isRunning = false; return true; } else { fos = new FileOutputStream(dataFile, true); } } else { if (dataFile.createNewFile()) { Log.d(TAG, "File created"); fos = new FileOutputStream(dataFile, true); tvStatus.setText("File created"); } else { tvStatus.setText("Error creating file"); return false; } } // Load the last digit loadLastDigit(); return true; } catch (Exception e) { Log.e(TAG, "Error setting up file", e); tvStatus.setText("File error: " + e.getMessage()); return false; } } private void loadLastDigit() { try { if (dataFile.exists() && dataFile.length() > 0) { FileInputStream fis = new FileInputStream(dataFile); fis.skip(dataFile.length() - 1); int lastByte = fis.read(); fis.close(); if (lastByte != -1) { LeastSignificantDigit = (char) lastByte; Log.d(TAG, "Last digit loaded: " + LeastSignificantDigit); } } } catch (Exception e) { Log.e(TAG, "Error loading last digit", e); } } private void setupSensor() { try { sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // First, try the accelerometer Sensor accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); if (accelSensor != null) { sensor = accelSensor; sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL); Log.d(TAG, "Accelerometer connected"); tvStatus.append("\nAccelerometer connected"); return; } // If there is no accelerometer, try the gyroscope Sensor gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); if (gyroSensor != null) { sensor = gyroSensor; sensorManager.registerListener(sensorListener, gyroSensor, SensorManager.SENSOR_DELAY_NORMAL); Log.d(TAG, "Gyroscope connected"); tvStatus.append("\nGyroscope connected"); return; } tvStatus.append("\nNo sensors available"); Log.e(TAG, "No sensors available"); } catch (Exception e) { Log.e(TAG, "Sensor setup error", e); tvStatus.append("\nSensor error: " + e.getMessage()); } } private SensorEventListener sensorListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { if (!isRunning || fos == null) return; try { // Take only the X-axis value (the first element of the array) float xValue = event.values[0]; // Convert the float to a string, removing the period and minus sign String valueStr = Float.toString(xValue); valueStr = valueStr.replace(".", "").replace("-", ""); // Remove leading zeros if (valueStr.length() > 1) { while (valueStr.startsWith("0") && valueStr.length() > 1) { valueStr = valueStr.substring(1); } } // If the string is empty, skip it if (valueStr.isEmpty()) return; // Convert to BigInteger BigInteger bigInt = new BigInteger(valueStr); String bigIntStr = bigInt.toString(); // Take the last digit if (!bigIntStr.isEmpty()) { LeastSignificantDigit2 = bigIntStr.charAt(bigIntStr.length() - 1); // Log Log.e(TAG, "=== Least Significant Digit ===" + LeastSignificantDigit2); // Check that it's a digit if (LeastSignificantDigit2 >= '0' && LeastSignificantDigit2 <= '9') { // If the digit has changed, write it to file if (LeastSignificantDigit != LeastSignificantDigit2) { try { fos.write(LeastSignificantDigit); fos.flush(); Log.d(TAG, "The digit written is: " + LeastSignificantDigit); LeastSignificantDigit = LeastSignificantDigit2; } catch (IOException e) { Log.e(TAG, "Error writing to file", e); } } } } } catch (Exception e) { Log.e(TAG, "Sensor processing error", e); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Not used } }; private void startFileCheck() { fileCheckRunnable = new Runnable() { @Override public void run() { if (!isRunning) return; try { if (dataFile != null && dataFile.exists()) { long fileSize = dataFile.length(); runOnUiThread(() -> { tvStatus.setText("File size: " + fileSize + " / " + FSize + " bytes"); }); if (fileSize >= FSize) { runOnUiThread(() -> { tvStatus.setText("Maximum Entropy Made"); }); stopEverything(); } } } catch (Exception e) { Log.e(TAG, "File check error", e); } // Repeat every second if (isRunning) { handler.postDelayed(this, 1000); } } }; handler.post(fileCheckRunnable); } private void stopEverything() { Log.d(TAG, "Stopping everything"); isRunning = false; // Stop file checking if (handler != null && fileCheckRunnable != null) { handler.removeCallbacks(fileCheckRunnable); } // Disable the sensor if (sensorManager != null && sensorListener != null) { sensorManager.unregisterListener(sensorListener); } // Close the file if (fos != null) { try { fos.close(); Log.d(TAG, "File closed"); } catch (IOException e) { Log.e(TAG, "Error closing file", e); } } } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); stopEverything(); } } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Activity_main.xml