【问题标题】:how to stop an Handler in android如何在android中停止处理程序
【发布时间】:2013-04-03 16:04:38
【问题描述】:

我已经创建了一个 android 应用程序,当单击一个按钮时,处理程序将在每 2 秒激活一个烤面包机。另一方面,我有一个停止按钮,我想在点击时停止正在运行的线程

这是我的代码

private final int  FIVE_SECONDS = 2000;


    public void scheduleSendLocation() {
        handler.postDelayed(new Runnable() {
            public void run() {
                sendLocation();          // this method will contain your almost-finished HTTP calls
                handler.postDelayed(this, FIVE_SECONDS);
            }
        }, FIVE_SECONDS);
    }


    protected void sendLocation() {
        Toast.makeText(getApplicationContext(), "Your Location is ", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
        stop = (Button) findViewById(R.id.stop);

        btnShowLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {        
                scheduleSendLocation();

            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {        
        // what to write here
            }
        });

    }

【问题讨论】:

    标签: android handler android-handler


    【解决方案1】:

    尝试调用以下代码

        stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {        
                handler.removeCallbacks(runnable);
            }
        });
    

    runnable 是您在调用 postDelayed 时添加的可运行对象。 runnable 的任何待处理帖子都将被删除,这些帖子位于消息队列中。

    【讨论】:

    • 先生,removeCallbacks() 的参数是什么
    【解决方案2】:

    试试这个:

    stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {        
                 myHandlerThread.interrupt();
                 myHandlerThread = null;
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多