如何在线程或异步任务中运行此代码? [英] How to run this code in a Thread or Async Task?

查看:69
本文介绍了如何在线程或异步任务中运行此代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行此代码时,出现关于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.id.comments);

 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("http://");
 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.

这篇关于如何在线程或异步任务中运行此代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆