检测Android上的长按按钮

检测Android上的长按按钮,android,broadcastreceiver,android-service,Android,Broadcastreceiver,Android Service,我想从我的服务中启动一个方法,按下一个物理按钮(主页、返回、菜单…) 如果用户长按其中一个按钮,服务应调用一个方法。如何为我的案例实现广播接收器或侦听器?您应该尝试以下代码: public class MyActivity extends Activity { protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.content_layout_id);

我想从我的服务中启动一个方法,按下一个物理按钮(主页、返回、菜单…)
如果用户长按其中一个按钮,服务应调用一个方法。如何为我的案例实现广播接收器或侦听器?

您应该尝试以下代码:

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;
         }
     });
     }
    }

不要认为您可以自定义长按home按钮-参考增强请求:


但是,您可以自定义长按此处提到的其他一些硬按钮:

服务无法访问UI线程。您可以做的一件事是让活动注册onlongclick侦听器,然后使用广播接收器或服务的onStart(intent-intent)向服务广播意图