aboutsummaryrefslogtreecommitdiff
path: root/tests/UnitTestRunner/app/src/main/java/com/google/oboe/tests/unittestrunner/MainActivity.java
blob: 97c939ad2d6f9617a5faf15f8ac9788b877462d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.google.oboe.tests.unittestrunner;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    private final String TAG = MainActivity.class.getName();
    private static final String TEST_BINARY_FILENAME = "testOboe.so";
    private static final int APP_PERMISSION_REQUEST = 0;

    private TextView outputText;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        outputText = findViewById(R.id.output_view_text);
        scrollView = findViewById(R.id.scroll_view);
        runCommand();
    }

    private void runCommand(){
        if (!isRecordPermissionGranted()){
            requestPermissions();
        } else {
            Log.d(TAG, "Got RECORD_AUDIO permission");
            Thread commandThread = new Thread(new UnitTestCommand());
            commandThread.start();
        }
    }

    private String executeBinary() {
        StringBuilder output = new StringBuilder();

        try {
            String executablePath;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                executablePath = getApplicationInfo().nativeLibraryDir + "/" + TEST_BINARY_FILENAME;
            } else {
                executablePath = getExecutablePathFromAssets();
            }

            Log.d(TAG, "Attempting to execute " + executablePath);

            Process process = Runtime.getRuntime().exec(executablePath);

            BufferedReader stdInput = new BufferedReader(new
                    InputStreamReader(process.getInputStream()));

            BufferedReader stdError = new BufferedReader(new
                    InputStreamReader(process.getErrorStream()));

            // read the output from the command
            String s;
            while ((s = stdInput.readLine()) != null) {
                Log.d(TAG, s);
                output.append(s).append("\n");
            }

            // read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                Log.e(TAG, "ERROR: " + s);
                output.append("ERROR: ").append(s).append("\n");
            }

            process.waitFor();
            Log.d(TAG, "Finished executing binary");
        } catch (IOException e){
            Log.e(TAG, "Could not execute binary ", e);
        } catch (InterruptedException e) {
            Log.e(TAG, "Interrupted", e);
        }

        return output.toString();
    }

    // Legacy method to get asset path.
    // This will not work on more recent Android releases.
    private String getExecutablePathFromAssets() {
        AssetManager assetManager = getAssets();

        String abi = Build.SUPPORTED_ABIS[0];
        String extraStringForDebugBuilds = "-hwasan";
        if (abi.endsWith(extraStringForDebugBuilds)) {
            abi = abi.substring(0, abi.length() - extraStringForDebugBuilds.length());
        }
        String filesDir = getFilesDir().getPath();
        String testBinaryPath = abi + "/" + TEST_BINARY_FILENAME;

        try {
            InputStream inStream = assetManager.open(testBinaryPath);
            Log.d(TAG, "Opened " + testBinaryPath);

            // Copy this file to an executable location
            File outFile = new File(filesDir, TEST_BINARY_FILENAME);

            OutputStream outStream = new FileOutputStream(outFile);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, read);
            }
            inStream.close();
            outStream.flush();
            outStream.close();
            Log.d(TAG, "Copied " + testBinaryPath + " to " + filesDir);

            String executablePath = filesDir + "/" + TEST_BINARY_FILENAME;
            Log.d(TAG, "Setting execute permission on " + executablePath);
            boolean success = new File(executablePath).setExecutable(true, false);
            if (!success) {
                Log.d(TAG, "Could not set execute permission on " + executablePath);
            }
            return executablePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private boolean isRecordPermissionGranted() {
        return (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
                PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermissions(){
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.RECORD_AUDIO},
                APP_PERMISSION_REQUEST);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {

        if (APP_PERMISSION_REQUEST != requestCode) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            return;
        }

        if (grantResults.length != 1 ||
                grantResults[0] != PackageManager.PERMISSION_GRANTED) {

            // User denied the permission, without this we cannot record audio
            // Show a toast and update the status accordingly
            outputText.setText(R.string.status_record_audio_denied);
            Toast.makeText(getApplicationContext(),
                    getString(R.string.need_record_audio_permission),
                    Toast.LENGTH_SHORT)
                    .show();
        } else {
            // Permission was granted, run the command
            outputText.setText(R.string.status_record_audio_granted);
            runCommand();
        }
    }

    class UnitTestCommand implements Runnable {

        @Override
        public void run() {
            final String output = executeBinary();

            runOnUiThread(() -> {
                outputText.setText(output);

                // Scroll to the bottom so we can see the test result
                scrollView.postDelayed(() -> scrollView.scrollTo(0, outputText.getBottom()), 100);
            });
        }
    }
}