Home / Documentation / Examples

RedBoxVM Examples

This section provides practical examples and code samples for integrating RedBoxVM into your applications using the LazyVM library. Each example includes complete source code and explanations.

Sample Project: All examples are available in the examples directory of the RedBoxVM repository.

Basic Integration Example

Simple Virtual App Manager

This example demonstrates the basic integration of RedBoxVM using LazyVM to install and manage virtual app instances.

public class BasicRedBoxExample extends AppCompatActivity {
    private LazyVMCore lazyVMCore;
    private BPackageManager packageManager;
    private List<PackageInfo> installedApps;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Initialize RedBoxVM
        initializeRedBox();
        
        // Setup UI
        setupUI();
    }
    
    private void initializeRedBox() {
        try {
            // Get LazyVM core instance
            lazyVMCore = LazyVMCore.get();
            
            // Initialize native core with current API level
            NativeCore.init(Build.VERSION.SDK_INT);
            
            // Initialize authentication system
            if (NativeCore.initializeAuth()) {
                Log.d("RedBox", "Authentication system initialized");
                
                // Set license key (replace with your actual license)
                String licenseKey = "your-license-key-here";
                if (NativeCore.setClientLicense(licenseKey)) {
                    Log.d("RedBox", "License validated successfully");
                } else {
                    Log.w("RedBox", "License validation failed");
                }
            }
            
            // Get package manager
            packageManager = BPackageManager.get();
            
            // Enable I/O redirection
            NativeCore.enableIO();
            
            // Hide Xposed framework if needed
            NativeCore.hideXposed();
            
            // Disable hidden API restrictions
            if (NativeCore.disableHiddenApi()) {
                Log.d("RedBox", "Hidden API restrictions disabled");
            }
            
            Log.d("RedBox", "RedBoxVM initialized successfully");
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to initialize RedBoxVM", e);
            showErrorDialog("Initialization failed", e);
        }
    }
    
    private void setupUI() {
        Button installAppButton = findViewById(R.id.btn_install_app);
        Button launchAppButton = findViewById(R.id.btn_launch_app);
        EditText packageNameInput = findViewById(R.id.et_package_name);
        EditText apkPathInput = findViewById(R.id.et_apk_path);
        
        installAppButton.setOnClickListener(v -> {
            String apkPath = apkPathInput.getText().toString().trim();
            if (!apkPath.isEmpty()) {
                installVirtualApp(apkPath);
            }
        });
        
        launchAppButton.setOnClickListener(v -> {
            String packageName = packageNameInput.getText().toString().trim();
            if (!packageName.isEmpty()) {
                launchVirtualApp(packageName);
            }
        });
        
        updateInstalledAppsList();
    }
    
    private void installVirtualApp(String apkPath) {
        new Thread(() -> {
            try {
                // Create install options
                InstallOption option = new InstallOption();
                option.userId = 0;
                option.copyApk = true;
                option.enableExternalStorage = true;
                
                // Install the app
                InstallResult result = packageManager.installPackage(apkPath, option);
                
                runOnUiThread(() -> {
                    if (result.isSuccess()) {
                        Toast.makeText(this, "App installed: " + result.packageName, 
                            Toast.LENGTH_SHORT).show();
                        updateInstalledAppsList();
                    } else {
                        showErrorDialog("Installation failed", new Exception(result.error));
                    }
                });
                
            } catch (Exception e) {
                runOnUiThread(() -> {
                    showErrorDialog("Failed to install app", e);
                });
            }
        }).start();
    }
    
    private void launchVirtualApp(String packageName) {
        new Thread(() -> {
            try {
                // Check if app is installed
                if (!packageManager.isPackageInstalled(packageName)) {
                    runOnUiThread(() -> {
                        Toast.makeText(this, "App not installed: " + packageName, 
                            Toast.LENGTH_SHORT).show();
                    });
                    return;
                }
                
                // Get application info
                ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
                
                // Launch the app using BActivityThread
                BActivityThread activityThread = BActivityThread.currentActivityThread();
                
                // Set virtual app info in native core
                NativeCore.setVirtualAppInfo(packageName, Process.myPid(), Process.myUid());
                
                // Create launch intent
                Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
                if (launchIntent != null) {
                    startActivity(launchIntent);
                    
                    runOnUiThread(() -> {
                        Toast.makeText(this, "Launched: " + packageName, 
                            Toast.LENGTH_SHORT).show();
                    });
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(this, "No launch activity found for: " + packageName, 
                            Toast.LENGTH_SHORT).show();
                    });
                }
                
            } catch (Exception e) {
                runOnUiThread(() -> {
                    showErrorDialog("Failed to launch app", e);
                });
            }
        }).start();
    }
    
    private void updateInstalledAppsList() {
        new Thread(() -> {
            try {
                installedApps = packageManager.getInstalledPackages(0);
                runOnUiThread(() -> {
                    // Update UI with installed apps list
                    updateAppsList();
                });
            } catch (Exception e) {
                Log.e("RedBox", "Failed to get installed apps", e);
            }
        }).start();
    }
    
    private void updateAppsList() {
        // Update RecyclerView or ListView with installed apps
        // Implementation depends on your UI structure
    }
    
    private void showErrorDialog(String message, Exception error) {
        new AlertDialog.Builder(this)
            .setTitle("Error")
            .setMessage(message + "\n\n" + error.getMessage())
            .setPositiveButton("OK", null)
            .show();
    }
}

Advanced Configuration Example

Custom I/O Redirection and System Properties

This example shows how to configure I/O redirection rules and system properties for enhanced virtualization.

public class AdvancedConfigExample {
    
    public void setupIORedirection() {
        try {
            // Add I/O redirection rules for common paths
            NativeCore.addIORule("/data/data/com.example.app", 
                                "/data/data/com.redbox.vm/virtual/com.example.app");
            
            NativeCore.addIORule("/sdcard/Android/data/com.example.app", 
                                "/data/data/com.redbox.vm/virtual/sdcard/com.example.app");
            
            // Add system directory redirections
            NativeCore.addIORule("/system/lib", 
                                "/data/data/com.redbox.vm/virtual/system/lib");
            
            // Enable I/O redirection
            NativeCore.enableIO();
            
            Log.d("RedBox", "I/O redirection configured successfully");
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to setup I/O redirection", e);
        }
    }
    
    public void configureSystemProperties() {
        try {
            // Configure device properties for spoofing
            NativeCore.nativeSetProp("ro.build.version.release", "13");
            NativeCore.nativeSetProp("ro.build.version.sdk", "33");
            NativeCore.nativeSetProp("ro.product.model", "Virtual Device");
            NativeCore.nativeSetProp("ro.product.brand", "RedBox");
            NativeCore.nativeSetProp("ro.product.manufacturer", "RedBoxVM");
            
            // Configure hardware properties
            NativeCore.nativeSetProp("ro.hardware", "virtual");
            NativeCore.nativeSetProp("ro.board.platform", "virtual");
            
            // Configure security properties
            NativeCore.nativeSetProp("ro.debuggable", "0");
            NativeCore.nativeSetProp("ro.secure", "1");
            
            Log.d("RedBox", "System properties configured");
            
            // Verify properties are set
            String androidVersion = NativeCore.nativeGetProp("ro.build.version.release");
            Log.d("RedBox", "Android version set to: " + androidVersion);
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to configure system properties", e);
        }
    }
    
    public void setupNetworkVirtualization() {
        try {
            // Enable network virtualization
            NativeCore.enableNativeNetworkVirtualization(true);
            
            // Configure virtual network interface
            NativeCore.setNetworkInterface("wlan0", "02:00:00:00:00:00", "192.168.1.100");
            
            // Enable SSL bypass for debugging (use carefully)
            NativeCore.enableNativeSSLBypass(true);
            
            Log.d("RedBox", "Network virtualization configured");
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to setup network virtualization", e);
        }
    }
    
    public void configureVirtualEnvironment(String packageName) {
        try {
            // Get virtual environment
            BEnvironment virtualEnv = BEnvironment.getVirtualEnvironment(0);
            
            if (virtualEnv != null && virtualEnv.isInitialized()) {
                // Get virtual directories
                File dataDir = virtualEnv.getDataDirectory(packageName);
                File cacheDir = virtualEnv.getCacheDirectory(packageName);
                File externalDir = virtualEnv.getExternalStorageDirectory();
                
                Log.d("RedBox", "Virtual data directory: " + dataDir.getAbsolutePath());
                Log.d("RedBox", "Virtual cache directory: " + cacheDir.getAbsolutePath());
                Log.d("RedBox", "Virtual external storage: " + externalDir.getAbsolutePath());
                
                // Ensure directories exist
                if (!dataDir.exists()) {
                    dataDir.mkdirs();
                }
                if (!cacheDir.exists()) {
                    cacheDir.mkdirs();
                }
                
            } else {
                Log.w("RedBox", "Virtual environment not initialized");
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to configure virtual environment", e);
        }
    }
}

Multi-User Virtual Environment Example

Managing Multiple Virtual Users

This example demonstrates how to create and manage multiple virtual users for app isolation.

graph TB subgraph "Virtual User Management" UM[BUserManager] U1[Virtual User 1] U2[Virtual User 2] U3[Virtual User 3] end subgraph "Virtual Apps per User" A1[App Instance 1] A2[App Instance 2] A3[App Instance 3] end UM --> U1 UM --> U2 UM --> U3 U1 --> A1 U2 --> A2 U3 --> A3
public class MultiUserExample {
    private BUserManager userManager;
    private Map<Integer, List<String>> userApps;
    
    public MultiUserExample() {
        userManager = BUserManager.get();
        userApps = new HashMap<>();
    }
    
    public void createVirtualUsers(int count) {
        for (int i = 0; i < count; i++) {
            try {
                String userName = "Virtual User " + (i + 1);
                BUserInfo user = userManager.createUser(userName, 0);
                
                if (user != null) {
                    Log.d("RedBox", "Created virtual user: " + user.name + " (ID: " + user.id + ")");
                    userApps.put(user.id, new ArrayList<>());
                } else {
                    Log.e("RedBox", "Failed to create virtual user: " + userName);
                }
                
            } catch (Exception e) {
                Log.e("RedBox", "Error creating virtual user " + i, e);
            }
        }
    }
    
    public void installAppForUser(int userId, String apkPath) {
        try {
            // Switch to target user
            if (userManager.switchUser(userId)) {
                Log.d("RedBox", "Switched to user: " + userId);
                
                // Install app for this user
                BPackageManager pm = BPackageManager.get();
                InstallOption option = new InstallOption();
                option.userId = userId;
                option.copyApk = true;
                
                InstallResult result = pm.installPackage(apkPath, option);
                
                if (result.isSuccess()) {
                    Log.d("RedBox", "App installed for user " + userId + ": " + result.packageName);
                    
                    // Track installed app for this user
                    List<String> apps = userApps.get(userId);
                    if (apps != null) {
                        apps.add(result.packageName);
                    }
                } else {
                    Log.e("RedBox", "Installation failed for user " + userId + ": " + result.error);
                }
                
            } else {
                Log.e("RedBox", "Failed to switch to user: " + userId);
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Error installing app for user " + userId, e);
        }
    }
    
    public void launchAppForUser(int userId, String packageName) {
        try {
            // Switch to target user
            if (userManager.switchUser(userId)) {
                Log.d("RedBox", "Switched to user " + userId + " to launch: " + packageName);
                
                // Set virtual app info for this user
                NativeCore.setVirtualAppInfo(packageName, Process.myPid(), userId);
                
                // Get virtual environment for this user
                BEnvironment virtualEnv = BEnvironment.getVirtualEnvironment(userId);
                
                if (virtualEnv != null && virtualEnv.isInitialized()) {
                    // Launch app in virtual environment
                    BActivityThread activityThread = BActivityThread.currentActivityThread();
                    
                    // Create launch intent
                    Intent launchIntent = new Intent();
                    launchIntent.setPackage(packageName);
                    launchIntent.setAction(Intent.ACTION_MAIN);
                    launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    
                    // Launch the app
                    LazyVMCore.getContext().startActivity(launchIntent);
                    
                    Log.d("RedBox", "Launched " + packageName + " for user " + userId);
                } else {
                    Log.e("RedBox", "Virtual environment not available for user: " + userId);
                }
                
            } else {
                Log.e("RedBox", "Failed to switch to user: " + userId);
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Error launching app for user " + userId, e);
        }
    }
    
    public void listUsersAndApps() {
        try {
            List<BUserInfo> users = userManager.getUsers();
            
            Log.d("RedBox", "=== Virtual Users and Apps ===");
            for (BUserInfo user : users) {
                Log.d("RedBox", "User: " + user.name + " (ID: " + user.id + ")");
                
                List<String> apps = userApps.get(user.id);
                if (apps != null && !apps.isEmpty()) {
                    for (String app : apps) {
                        Log.d("RedBox", "  - " + app);
                    }
                } else {
                    Log.d("RedBox", "  - No apps installed");
                }
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Error listing users and apps", e);
        }
    }
    
    public void cleanupUser(int userId) {
        try {
            // Remove all apps for this user
            List<String> apps = userApps.get(userId);
            if (apps != null) {
                BPackageManager pm = BPackageManager.get();
                for (String packageName : apps) {
                    pm.uninstallPackage(packageName);
                    Log.d("RedBox", "Uninstalled " + packageName + " for user " + userId);
                }
            }
            
            // Remove the user
            if (userManager.removeUser(userId)) {
                Log.d("RedBox", "Removed virtual user: " + userId);
                userApps.remove(userId);
            } else {
                Log.e("RedBox", "Failed to remove virtual user: " + userId);
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Error cleaning up user " + userId, e);
        }
    }
}

Security and Anti-Detection Example

Implementing Security Policies and Detection Bypass

This example demonstrates how to implement security policies and bypass various detection mechanisms.

public class SecurityExample {
    
    public void setupAntiDetection() {
        try {
            // Hide Xposed framework
            NativeCore.hideXposed();
            Log.d("RedBox", "Xposed framework hidden");
            
            // Disable hidden API restrictions
            if (NativeCore.disableHiddenApi()) {
                Log.d("RedBox", "Hidden API restrictions disabled");
            }
            
            // Initialize stealth memory system
            if (NativeCore.initializeStealthMemorySystem()) {
                Log.d("RedBox", "Stealth memory system initialized");
            }
            
            // Configure anti-detection properties
            setupAntiDetectionProperties();
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to setup anti-detection", e);
        }
    }
    
    private void setupAntiDetectionProperties() {
        // Hide virtualization indicators
        NativeCore.nativeSetProp("ro.kernel.qemu", "0");
        NativeCore.nativeSetProp("ro.hardware", "qcom");
        NativeCore.nativeSetProp("ro.product.model", "SM-G973F");
        NativeCore.nativeSetProp("ro.product.brand", "samsung");
        NativeCore.nativeSetProp("ro.product.manufacturer", "samsung");
        
        // Hide debugging indicators
        NativeCore.nativeSetProp("ro.debuggable", "0");
        NativeCore.nativeSetProp("ro.secure", "1");
        NativeCore.nativeSetProp("service.adb.root", "0");
        
        // Hide emulator indicators
        NativeCore.nativeSetProp("ro.build.tags", "release-keys");
        NativeCore.nativeSetProp("ro.build.type", "user");
        
        Log.d("RedBox", "Anti-detection properties configured");
    }
    
    public void configureProcessSecurity(String packageName) {
        try {
            // Check authentication status for package
            if (!NativeCore.checkAuthStatusForPackage(packageName)) {
                Log.w("RedBox", "Package not authorized: " + packageName);
                return;
            }
            
            // Set virtual app info with security context
            int virtualUid = generateVirtualUid(packageName);
            NativeCore.setVirtualAppInfo(packageName, Process.myPid(), virtualUid);
            
            // Configure process isolation
            LazyVMCore core = LazyVMCore.get();
            core.setCurrentAppUid(virtualUid, packageName);
            
            if (core.isSandboxedEnvironment()) {
                Log.d("RedBox", "Process running in secure sandbox: " + packageName);
                
                // Apply additional security measures
                applySecurityPolicies(packageName);
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to configure process security", e);
        }
    }
    
    private void applySecurityPolicies(String packageName) {
        try {
            // Configure I/O restrictions
            String virtualDataPath = "/data/data/com.redbox.vm/virtual/" + packageName;
            NativeCore.addIORule("/data/data/" + packageName, virtualDataPath);
            
            // Configure network restrictions if needed
            if (isNetworkRestrictedApp(packageName)) {
                NativeCore.enableNativeNetworkVirtualization(true);
                Log.d("RedBox", "Network virtualization enabled for: " + packageName);
            }
            
            // Configure SSL bypass for debugging (if authorized)
            if (isDebugAuthorized(packageName)) {
                NativeCore.enableNativeSSLBypass(true);
                Log.d("RedBox", "SSL bypass enabled for debugging: " + packageName);
            }
            
        } catch (Exception e) {
            Log.e("RedBox", "Failed to apply security policies", e);
        }
    }
    
    private int generateVirtualUid(String packageName) {
        // Generate a virtual UID based on package name
        // This should be consistent for the same package
        int hash = packageName.hashCode();
        // Ensure UID is in application range
        return Math.abs(hash % 50000) + Process.FIRST_APPLICATION_UID;
    }
    
    private boolean isNetworkRestrictedApp(String packageName) {
        // Define network-restricted apps
        String[] restrictedApps = {
            "com.example.banking",
            "com.example.payment",
            "com.example.secure"
        };
        
        for (String app : restrictedApps) {
            if (packageName.equals(app)) {
                return true;
            }
        }
        return false;
    }
    
    private boolean isDebugAuthorized(String packageName) {
        // Check if debugging is authorized for this package
        // This should be based on your security policy
        return NativeCore.checkAuthStatusForPackage(packageName + ".debug");
    }
    
    public void monitorSecurityEvents() {
        try {
            // Monitor process state
            if (NativeCore.isVirtualProcess()) {
                String virtualPkg = NativeCore.getVirtualPackageName();
                Log.d("RedBox", "Monitoring virtual process: " + virtualPkg);
                
                // Check stealth memory system health
                if (NativeCore.isStealthMemorySystemHealthy()) {
                    Log.d("RedBox", "Stealth memory system is healthy");
                } else {
                    Log.w("RedBox", "Stealth memory system health check failed");
                }
            }
            
            // Monitor authentication status
            boolean authStatus = NativeCore.checkAuthStatus();
            Log.d("RedBox", "Authentication status: " + (authStatus ? "Valid" : "Invalid"));
            
        } catch (Exception e) {
            Log.e("RedBox", "Error monitoring security events", e);
        }
    }
    
    public void cleanup() {
        try {
            // Clear custom properties
            NativeCore.nativeClearProps();
            
            // Shutdown stealth memory system
            if (NativeCore.shutdownStealthMemorySystem()) {
                Log.d("RedBox", "Stealth memory system shutdown successfully");
            }
            
            // Disable SSL bypass
            NativeCore.enableNativeSSLBypass(false);
            
            // Disable network virtualization
            NativeCore.enableNativeNetworkVirtualization(false);
            
            Log.d("RedBox", "Security cleanup completed");
            
        } catch (Exception e) {
            Log.e("RedBox", "Error during security cleanup", e);
        }
    }
}