在安卓系统中检测按钮长按

4

我希望能够通过按下实体按钮 (home、back、menu 等) 来启动我的服务。如果用户长按其中一个按钮,服务应该调用一个方法。我该如何为我的情况实现广播接收器或监听器呢?

3个回答

2

1
一个服务无法访问UI线程。你可以做的一件事是让活动注册onlongclick监听器,然后使用广播接收器或服务的onStart(Intent intent)发送意图广播给服务。

0
你应该尝试这段代码:
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
     super.onCreate(icicle);

     setContentView(R.layout.content_layout_id);

     final Button button = (Button) findViewById(R.id.button_id);
     button.setOnLongClickListener(new View.OnLongClickListener() {
         public boolean onLongClick(View v) {
             // Perform action on click
             return true;
         }
     });
     }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接