【问题标题】:Stopping a runnable停止一个可运行的
【发布时间】:2013-07-23 05:01:25
【问题描述】:

有没有办法在只执行一次方法后停止可运行对象?

我创建了这段代码来延迟“getPreferences”方法的启动,但是当我运行应用程序时,“getPreferences”发送给我的下一个活动会出现屏幕刷新问题?
这是否归结为可运行对象仍在继续循环,以及如何在一次执行后将其杀死?

 import android.os.Bundle;
 import android.os.Handler;
 import android.app.Activity;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.view.Menu;

 public class StartScreen extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_screen);



    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() { 

    getPreferences();

      }}, 10000);

    }


private void getPreferences() {
    // TODO Auto-generated method stub
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String name = sharedPreferences.getString("NAME", "");



    if (name != null) {
        // the key does not exist



                Intent intent=new Intent(StartScreen.this,InitialPreferences.class);
                startActivity(intent);
            }

     if (name == "NAME"){
        // handle the value


                Intent intent=new Intent(StartScreen.this,MainActivity.class);
                startActivity(intent);
     }     

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.start_screen, menu);
    return true;
}

  }

InitialPreferences 活动性....

 import android.content.SharedPreferences;
 import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup; 
import android.widget.TextView;

  public class InitialPreferences extends StartScreen implements OnClickListener {

EditText editText1;
Button button1;
TextView textView1;
 RadioGroup radioGroup;
 RadioButton radioPosistionButton;   

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.initial_preferences);

   //  waitTimer.cancel();

    textView1 = (TextView)findViewById(R.id.textView1);
    editText1 = (EditText)findViewById(R.id.editText1);
    button1 = (Button)findViewById(R.id.button1); 
    radioGroup = (RadioGroup) findViewById(R.id.radioGroup);  




 }
 @Override
 protected void onStart(){
 //waitTimer.cancel();

 LoadPreferences();
 super.onStart();
  }
 private void SavePreferences(String key, String value){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
   }

 private void LoadPreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String name = sharedPreferences.getString("NAME", "");
    textView1.setText(name);       

 }
 @Override
 public void onClick(View v) {
// TODO Auto-generated method stub
  SavePreferences("NAME", editText1.getText().toString());


// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();

// find the radio button by returned id
    radioPosistionButton = (RadioButton) findViewById(selectedId);


 }


 }

【问题讨论】:

  • 等等,这里有什么问题?您所说的“导致屏幕刷新问题”的问题是什么?你能解释更多吗?另外,请问您为什么要使用Runnable() 开始活动?
  • 嗨,对不起,如果我的问题含糊不清。是的,下一个活动,无论是初始偏好还是主要活动,在 10 秒后都会重新加载@lalit poptani,谢谢今晚读完。
  • @LalitPoptani 嗨,我一直在查看您之前指示我的答案,您能告诉我如何将其合并到我的代码中吗?谢谢
  • @J4C3N-14 我已经编辑了我的答案。我认为问题在于您在 InitialPreference 而不是 Activity 中扩展 StartScreen。我建议您查看 PreferenceActivity 以从您的 InitialPreferences 扩展(请参阅我的答案中的链接)

标签: android loops handler delay runnable


【解决方案1】:

方法 run 只执行一次。如果您希望有一个永无止境的循环,您需要包含类似 while(true) 的内容。
更好地描述您的问题,因为我不太了解它。是下一个活动加载两次的问题吗?在什么情况下?你能发布下一个活动的代码吗?正在加载哪个活动? InitialPreferences 还是 MainActivity?
请注意,通过在 Activity 的 onCreate 中包含代码,每次重新创建 Activity 时都会执行一次(例如,当您将手机从横向更改为纵向时,将重新创建 Activity,调用 @ 987654324@再次)。

编辑 1: 您遇到的主要问题是您的InitialPreference 类扩展了StartScreen,并且在您的onCreate 方法中,您调用super 将触发另一个postDelayed,启动另一个InitialPreference 等等。
您是否有任何理由扩展 StartScreen 而不是 Activity?我认为通过这种更改,您的问题将得到解决。当然,如果你正在做一个设置活动,我会建议使用 PreferenceActivity。您可以查看documentation http://developer.android.com/guide/topics/ui/settings.html

【讨论】:

  • 您好,感谢您的回答,是的,您是对的,问题是下一个活动(初始偏好)不断重新加载,不是一次或两次,而是每 10 秒或我放置的任何时间无限期地重新加载。无法在工作时发布初始偏好代码,但稍后会发布。我以为我需要在暂停时停止此活动,但这似乎也不起作用...正如您可能会说的那样,我在编码方面还是个新手,所以感谢您的帮助和建议,不要在 onCreate 中使用它。
  • 嗨,再次感谢您的回答,在 Initialpreferences 活动中似乎每隔一秒左右就会重新创建活动,如果您不介意查看它,我已经修改了我的问题以包含该代码我
  • @J4C3N-14 我已经编辑了我的答案。我认为问题在于您在 InitialPreference 而不是 Activity 中扩展 StartScreen。我建议你看看 PreferenceActivity
  • 你解决了,谢谢,我使用 eclipse 创建了 InitialPreferences 活动(为你做)。非常感谢,我会读入 PreferenceActivity。欢呼
【解决方案2】:

停止可运行对象的正确方法是终止其中的循环。在您的情况下,没有循环,因此可运行对象应该在 getPreferences() 完成运行后停止。

由于您已将其置于 onCreate 中,因此它将在创建或重新创建 Activity 后运行 10000 毫秒

【讨论】:

  • 您好,感谢您的回答,不幸的是它似乎并没有停止,下一个活动被加载,然后每 10 秒继续加载。这可能归结为 onCreate 中的可运行对象吗?你能给我举个例子,让我把它从 onCreate 中删除吗?再次感谢,您可以告诉我,我是一个编码新手,所以请耐心等待。
  • @J4C3N-14 1) name == "NAME" 将始终返回 false。您需要使用类似以下的语法检查是否相等: if (name.equals("NAME")) 2) 您得到的正是您所做的 - StartScreen 活动将在创建后 10 秒调用 InitialPreferences。您的 InitialPreferences 活动中的 onCreate 中可能有相同的代码。这可以解释为什么它会一遍又一遍地呼唤自己。
  • 嗨,感谢您的回答,我已经用您的代码替换了我的代码,因为我确信这样会更好,但只是出于好奇,作为代码故障查找的一部分,我完全消除了延迟,它将我引导到 initialPreferences 或 mainActivity 总是工作得很好?关于 initialPreferences 活动,如果这就是您的意思,我没有在该活动中设置任何延迟?
【解决方案3】:

将 Timer 和 TimerTask 用于重复性任务。

见下面的代码。它对我有用。

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
      // use handler here.

  new Handler().postDelayed(new Runnable() {
      @Override
      public void run() { 
         getPreferences();
       }
     });
  }
},100000) // second parameter of scheduleAtFixedRate() method is Time in MilliSecond
             Specify the time interval here for repepititive execution.

在 Activity 的 onDestroy 或 onStop 方法中,使用以下代码取消计时器。

timer.cancel();

【讨论】:

  • 嗨。我以前看过您的代码,并从其他人的答案中尝试过。它仍然会导致我遇到同样的问题,但我稍后会再试一次,因为我可能错过了一些东西。谢谢
【解决方案4】:

通过处理interrupts 让您的Runnable interrupt 知道,当您决定取消/中止Runnable 实例时,发送interrupt 给它:

    run() {
    ..
      if(Thread.currentThread().isInterrupted()) {
         //thread is interrupt, abort run method, either by returning or throwing InterruptedException
         return;
         //OR
         throw new InterruptedException("Explicit abort signal!");
      }else {
         //continue your work
      }
   }

通常interrupt 标志在run 方法内的多个位置(以及循环中)检查,以使其更能感知中断,您应该在多个点添加getPreferences 方法。

要中断thread,调用者可以调用t.interrupt,其中tThread 实例。

【讨论】:

  • 谢谢,我可以试试这个。
猜你喜欢
  • 2018-02-04
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 2018-09-30
  • 2020-08-05
  • 2012-05-19
  • 2021-08-19
  • 2020-06-01
相关资源
最近更新 更多