我想创建包含 Python 网络服务器的 AndroidTVApp。我正在使用 python 库 Chaquopy。像 print HelloWorld 这样的简单 python 脚本可以工作。我是新手,但我认为我必须在服务类中运行网络服务器才能在后台运行。它不起作用。首先,我尝试在 ShowWebsiteActivity.java 中运行 Python,但 webview 只显示空白页面。所以,这就是我尝试在服务中调用和运行 Python 脚本的原因。Python 文件有效,我尝试在我的电脑上运行它,但在 AdnroidStudio 中没有。它引发此错误 - 无法将字节对象转换为 java.lang.String。如何在后台运行 Python 网络服务器?这是我的代码:
Java 类
public class ShowWebsiteActivity extends FragmentActivity {
WebView web;
TextView textView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// CALLING SERVICES
startService(new Intent(this,StartPythonWebServer.class));
setContentView(R.layout.activity_website);
web = findViewById(R.id.webView);
WebSettings webSettings = web.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setDomStorageEnabled(true);
web.setWebViewClient(new Callback());
web.loadUrl("http://10.0.2.2:8080/");
textView = findViewById(R.id.DateTime);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MM-yyyy hh:mm:ss a");
String dateTime = simpleDateFormat.format(calendar.getTime());
textView.setText(dateTime);
final Button logout = findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
web.loadUrl("http://10.0.2.2:8080/menu");
}
});
}
服务等级
public class StartPythonWebServer extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
Python py = Python.getInstance();
py.getModule("webserver").callAttr("start");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
}}
Python
from flask import Flask, render_template, url_for, redirect, render_template, request
import os
from werkzeug.utils import secure_filename
app = Flask(__name__,
static_folder='static',
template_folder='templates')
@app.route('/')
def main():
return render_template('login.html')
@app.route('/menu', methods=['GET', 'POST'])
def menu():
return render_template('menu.html')
@app.route('/content', methods=['GET', 'POST'])
def content():
return render_template('index.html')
def start():
app.run(debug=True, host='0.0.0.0', port=8080)
'''
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
'''