Android studio调用Python代码
时间: 2024-05-01 19:18:57 浏览: 197
你可以使用 Android Studio 中的 Java 代码来调用 Python 代码。以下是一个简单的例子:
1. 首先,在 Android Studio 中创建一个新的 Java 项目。
2. 在项目文件夹中创建一个名为“python”的文件夹。
3. 在“python”文件夹中创建一个名为“test.py”的 Python 文件,其中包含以下代码:
```python
def add_numbers(a, b):
return a + b
```
4. 在 Android Studio 中创建一个名为“PythonInterpreter”的 Java 类,其中包含以下代码:
```java
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class PythonInterpreter {
private PythonInterpreter interpreter = null;
public PythonInterpreter() {
interpreter = new PythonInterpreter();
}
public int addNumbers(int a, int b) {
interpreter.execfile("python/test.py");
PyFunction func = interpreter.get("add_numbers", PyFunction.class);
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
return pyobj.asInt();
}
}
```
5. 在 MainActivity.java 中,调用 PythonInterpreter 类的 addNumbers() 方法来调用 Python 代码:
```java
int result = new PythonInterpreter().addNumbers(1, 2);
System.out.println("The result is: " + result);
```
以上代码将打印出“The result is: 3”。
需要注意的是,在 Android 设备上运行 Python 代码可能会有性能上的问题,因此建议仅在必要时才使用此方法。
阅读全文
相关推荐


















