我尝试了一个代码来检测手机上任何地方的长按。这是怎么回事:
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;
}
它没有检测到longpress但是我尝试了一个类似的活动代码,它运行得很好。这是代码:
public class testlongpress extends 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;
}
}
我的问题是为什么它不是在开展活动而不是服务?
答案 0 :(得分:1)
根据Android Docs
服务是一种应用程序组件,可以在后台执行长时间运行的操作,但不提供用户界面。另一个应用程序组件可以启动服务,即使用户切换到另一个应用程序,它也将继续在后台运行。
您无法在服务上进行UI操作,屏幕上显示的视图由Activity的UI而非服务组成。
有关详细信息,请查看服务上的official documentation。