|
| 1 | +How to run QPython script in your application ? |
| 2 | +=========================================== |
| 3 | +You could call QPython to run some script or python code in your app |
| 4 | + |
| 5 | +:: |
| 6 | + |
| 7 | + String extPlgPlusName = "org.qpython.qpy"; // QPython package name |
| 8 | + Intent intent = new Intent(); |
| 9 | + intent.setClassName(extPlgPlusName, "org.qpython.qpylib.MPyApi"); |
| 10 | + intent.setAction(extPlgPlusName + ".action.MPyApi"); |
| 11 | + |
| 12 | + Bundle mBundle = new Bundle(); |
| 13 | + mBundle.putString("app", "myappid"); |
| 14 | + mBundle.putString("act", "onPyApi"); |
| 15 | + mBundle.putString("flag", "onQPyExec"); // any String flag you may use in your context |
| 16 | + mBundle.putString("param", ""); // param String param you may use in your context |
| 17 | + |
| 18 | + /* |
| 19 | + * The String Python code, you can put your py file in res or raw or intenet, so that you can get it the same way, which can make it scalable |
| 20 | + */ |
| 21 | + String code = "#qpy:console\n" + |
| 22 | + "try:\n" + |
| 23 | + " import androidhelper\n" + |
| 24 | + "\n" + |
| 25 | + " droid = androidhelper.Android()\n" + |
| 26 | + " line = droid.dialogGetInput()\n" + |
| 27 | + " s = 'Hello %s' % line.result\n" + |
| 28 | + " droid.makeToast(s)\n" + |
| 29 | + "except:\n" + |
| 30 | + " print(\"Hello, Please update to newest QPython version from (http://play.qpython.com/qrcode-python.html) to use this feature\")\n"); |
| 31 | + |
| 32 | + |
| 33 | + mBundle.putString("pycode", code); |
| 34 | + intent.putExtras(mBundle); |
| 35 | + |
| 36 | + startActivityForResult(intent, SCRIPT_EXEC_PY); |
| 37 | + |
| 38 | + ... |
| 39 | + |
| 40 | + |
| 41 | + // Deal with the result callback by qpython |
| 42 | + @Override |
| 43 | + protected void onActivityResult(int requestCode, int resultCode, Intent data) { |
| 44 | + if (requestCode == SCRIPT_EXEC_PY) { |
| 45 | + if (data!=null) { |
| 46 | + Bundle bundle = data.getExtras(); |
| 47 | + String flag = bundle.getString("flag"); |
| 48 | + String param = bundle.getString("param"); |
| 49 | + String result = bundle.getString("result"); // Result your Pycode generate |
| 50 | + Toast.makeText(this, "onQPyExec: return ("+result+")", Toast.LENGTH_SHORT).show(); |
| 51 | + } else { |
| 52 | + Toast.makeText(this, "onQPyExec: data is null", Toast.LENGTH_SHORT).show(); |
| 53 | + |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +`You can see this sample project <https://github.com/qpython-android/app-call-qpython-api>`_ |
0 commit comments