[英]How can i run a long code on single button click in android without app crash?
I'm using an algo to download a video whenever user place Url on a EditText and hit on a Button. 每当用户将Url放置在EditText上并单击Button时,我都在使用算法来下载视频。 The algo will take some time according to user Connection speed and it will also calculate a value and taking some time in it.
该算法将根据用户连接速度花费一些时间,还将计算一个值并花费一些时间。 Everything works good but whenever I click/press the button twice app crashes so what should i need to do so it will wait until the code execute completely ?
一切正常,但是每当我单击/按下按钮两次时,应用程序崩溃,那么我需要做些什么,直到代码完全执行?
If I'm understanding your question well, you dont want the onClick to be executed twice, right? 如果我很好地理解了您的问题,那么您不希望onClick两次执行,对吗? One way to do this is to create a boolean (false) in the activity attributes, and then, once onClick is executed, change it to "true".
一种方法是在活动属性中创建一个布尔值(false),然后在执行onClick后将其更改为“ true”。 For example:
例如:
public class MainActivity extends AppCompatActivity {
public boolean clicked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!clicked){
methodToExecuteYourTask();
clicked = true;
}
}
});
}
}
If you need to use the button again to download, once the algo is finished, try to add in the algo a check that changes the value of the boolean to false again. 如果您需要再次使用该按钮进行下载,则算法完成后,请尝试在算法中添加将布尔值再次更改为false的检查。 This way, your code inside the if condition will only be executed once.
这样,if条件中的代码将只执行一次。
You should do it in a thread that is not the UI thread. 您应该在不是UI线程的线程中执行此操作。 See the following code for an example of such.
有关此类示例,请参见以下代码。 Read more here .
在这里阅读更多 。
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Do something in the background
}
}).start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.