我尝试了一个代码来检测手机上任何地方的长按。事情是这样的:
WindowManager wm;
View myview;
LayoutInflater li;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("\n=\n=\n=\n" + "oncreate service" + "\n=\n=\n=\n");
li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
//WindowManager.LayoutParams.TYPE_INPUT_METHOD |
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,// | WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
System.out.println("\n=\n=\n=\n" + "lp " + params + "\n=\n=\n=\n");
params.gravity = Gravity.RIGHT | Gravity.TOP;
myview = li.inflate(R.layout.traslucent, null);
System.out.println("\n=\n=\n=\n" + "View inflated" + "\n=\n=\n=\n");
System.out.println("\n=\n=\n=\n" + "Layout inflator = " + li + "\nWindow manager = " + wm + "\nparams = " + params + "\nView = " + myview + "\n=\n=\n=\n");
myview.setOnLongClickListener(this);
System.out.println("\n=\n=\n=\n" + "On touch listener" + "\n=\n=\n=\n");
wm.addView(myview, params);
System.out.println("\n=\n=\n=\n" + "add view" + "\n=\n=\n=\n");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wm.removeView(myview);
myview=null;
}
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "LongPress", Toast.LENGTH_SHORT).show();
return false;
}
它没有检测到长按,但我尝试了一个类似的活动代码,它工作得很好。这是代码:
公共类 testlongpress 扩展 Activity 实现 OnLongClickListener、OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LayoutInflater li = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.test_layout, null);
v.setOnLongClickListener(this);
setContentView(v);
}
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "LongPress", Toast.LENGTH_SHORT).show();
return true;
}
}
我的问题是为什么它不适用于活动但不适用于服务?