如何在线程或异步任务中运行此代码?

编程入门 行业动态 更新时间:2024-10-26 12:21:14
本文介绍了如何在线程或异步任务中运行此代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我尝试运行此代码时,出现关于strictMode线程策略的错误,因此我添加了这一行.

When I tried running this code I get an error, about the strictMode Thread policy, so I added this line.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

后来我发现这不是在线程或异步任务中运行它的最佳方法,因此我想在线程或Asynctask中运行它.回答

I later discovered this is not the best approach that I have to run it in a Thread or an ansync task, so i will like to run it in a thread or an Asynctask. Please help edit my code when answering

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requestWindowFeature(Window.FEATURE_NO_TITLE); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_live_streaming); ActionBar actionbar = getSupportActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); abm = new ActionBarMenu(LiveStreaming.this); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); if (InternetStatus.getInstance(this).isOnline(this)) { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element // NodeList nl = doc.getElementsByTagName(); NodeList studentList = doc.getElementsByTagName("streamingurl"); // Print total student elements in document // System.out.println("Total students: " + studentList.getLength()); Toast.makeText(getBaseContext(), "Please wait while stream loads", Toast.LENGTH_SHORT).show(); if (studentList != null && studentList.getLength() > 0) { for (int i = 0; i < studentList.getLength(); i++) { Node node = studentList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; NodeList nodeList = e.getElementsByTagName("andhigh_value"); theAndroid_HighValue = nodeList.item(0).getChildNodes() .item(0).getNodeValue(); } vid = (VideoView) findViewById(R.id.videoview); vid.setVideoPath(theAndroid_HighValue); // static final String KEY_IPADHIGH = "ipadhigh_value"; MediaController mediaController = new MediaController(this); mediaController.setAnchorView(vid); // vid.setMediaController(mediaController); vid.requestFocus(); vid.start(); videoBuffering = new ProgressDialog(LiveStreaming.this); videoBuffering.setMessage("Loading...Please wait"); // videoBuffering.setIcon(R.drawable.ic_launcher); // videoBuffering.setTitle(R.string.app_name); videoBuffering.setProgressStyle(ProgressDialog.STYLE_SPINNER); videoBuffering.show(); vid.setOnErrorListener(new OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { // Log.e(TAG, "Error playing video"); // Toast.makeText(getBaseContext(),"No Stream Found",Toast.LENGTH_SHORT).show(); AlertDialog NetAlert = new AlertDialog.Builder(LiveStreaming.this).create(); NetAlert.setMessage("No Stream Found!"); NetAlert.setButton("OK", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog,int which) { // here you can add functions // finish(); } }); NetAlert.show(); return true; } }); vid.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { videoBuffering.cancel(); } }); } } else { Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show(); // Toast t = // Toast.makeText(this,"You are not online!!!!",8000).show(); Log.v("Home", "############################You are not online!!!!"); } } // liveblog_tab = (LinearLayout) findViewById(R.id.liveblog_tab); addcom_tab = (ImageView) findViewById(R.id.addcom); liveblog = (ImageView) findViewById(R.id.addfull); // comments = (LinearLayout) findViewById(R.idments); FLAG = LIVE_BLOG; ourBrow = (WebView) findViewById(R.id.browser); // adding webviewclient prevents web-view launching every-time the // web-site is visited ourBrow.setWebViewClient(new WebViewClient()); // ourBrow.getSettings().setBuiltInZoomControls(true); // ourBrow.getSettings().setSupportZoom(true); ourBrow.getSettings().setJavaScriptEnabled(true); ourBrow.getSettings().setAllowFileAccess(true); ourBrow.loadUrl(""); ourBrow.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { ourBrow.loadUrl("file:///android_asset/internet.htm"); } }); addcom_tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // FLAG = COMMENT; // changeView(); viewCategory(); } }); liveblog.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(LiveStreaming.this, FullVideoView.class); i.putExtra("video_url", "theAndroid_HighValue"); startActivity(i); } }); }

推荐答案

您可以尝试以下操作.

button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { new asyn().execute(); } });

然后像这样创建您的asynctask.

then create your asynctask like this.

class asyn extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(yourActivityname.this); pDialog.setMessage("Loading... Please wait..."); pDialog.setCancelable(false); pDialog.show(); } protected String doInBackground(String... args) { if (InternetStatus.getInstance(this).isOnline(this)) { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element // NodeList nl = doc.getElementsByTagName(); NodeList studentList = doc.getElementsByTagName("streamingurl"); // Print total student elements in document // System.out.println("Total students: " + studentList.getLength()); Toast.makeText(getBaseContext(), "Please wait while stream loads", Toast.LENGTH_SHORT).show(); if (studentList != null && studentList.getLength() > 0) { for (int i = 0; i < studentList.getLength(); i++) { Node node = studentList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; NodeList nodeList = e.getElementsByTagName("andhigh_value"); theAndroid_HighValue = nodeList.item(0).getChildNodes() .item(0).getNodeValue(); } vid = (VideoView) findViewById(R.id.videoview); vid.setVideoPath(theAndroid_HighValue); // static final String KEY_IPADHIGH = "ipadhigh_value"; MediaController mediaController = new MediaController(this); mediaController.setAnchorView(vid); // vid.setMediaController(mediaController); vid.requestFocus(); vid.start(); videoBuffering = new ProgressDialog(LiveStreaming.this); videoBuffering.setMessage("Loading...Please wait"); // videoBuffering.setIcon(R.drawable.ic_launcher); // videoBuffering.setTitle(R.string.app_name); videoBuffering.setProgressStyle(ProgressDialog.STYLE_SPINNER); videoBuffering.show(); vid.setOnErrorListener(new OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { // Log.e(TAG, "Error playing video"); // Toast.makeText(getBaseContext(),"No Stream Found",Toast.LENGTH_SHORT).show(); AlertDialog NetAlert = new AlertDialog.Builder(LiveStreaming.this).create(); NetAlert.setMessage("No Stream Found!"); NetAlert.setButton("OK", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog,int which) { // here you can add functions // finish(); } }); NetAlert.show(); return true; } }); vid.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { videoBuffering.cancel(); } }); } } else { Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show(); // Toast t = // Toast.makeText(this,"You are not online!!!!",8000).show(); Log.v("Home", "############################You are not online!!!!"); } } return null; } protected void onPostExecute(String file_url) { pDialog.dismiss(); } }

此处pDialog是您的ProgressDialog,您可以像这样定义它ProgressDialog pDialog;,或者如果您不想在按钮上发生此事件;则单击事件可以直接在onCreate方法.

here pDialog is your ProgressDialog and you can define it like this ProgressDialog pDialog; Or if you don't want to fore this event on button;s click event then you can directly use this line in your onCreate method new asyn().execute();.

修改

我已经编辑了答案,但是您必须对此做一些必要的更改,我认为它将要求您在某处添加try and catch块,然后只需添加即可.

I have edited my answer, but you have to make some necessary changes in this, i think it will ask you add try and catch block somewhere, then just add it.

更多推荐

如何在线程或异步任务中运行此代码?

本文发布于:2023-11-23 10:36:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   代码   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!