使用Android系統的粘貼板管理服務及ClipboardManager通過addPrimaryClipChangedListener添加Listener來監聽粘貼板的狀態,很很簡單的一個小功能~
1.首先創建一個Service在後臺運行:
Intent intent = new Intent(this,MainService.class);
startService(intent);
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ClipboardManager mClipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
Log.e("Copylistenerdemo", mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString());
}
2.在Service管理粘貼板服務:
mClipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(mPrimaryClipChangedListener);
3.在onPrimaryClipChanged()做想要的事情,例如彈出框:
使用WindowManager來顯示彈出框
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View floatView = layoutInflater.inflate(R.layout.floater, null);
final WindowManager mWindowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
LayoutParams params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;//系統內部錯誤提示,顯示於所有內容之上
params.format = PixelFormat.RGBA_8888;
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; //當窗口可以獲得焦點(沒有設置FLAG_NOT_FOCUSALBE選項)時,仍然將窗口範圍之外的點設備事件(鼠標、觸摸屏)發送給後面的窗口處理
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.LEFT | Gravity.TOP;
params.x = 0;
params.y = 0;
mWindowManager.addView(floatView, params);
ObjectAnimator animatorShow = ObjectAnimator.ofFloat(floatView, "alpha", 0.0f,1.0f);
animatorShow.setDuration(500);
animatorShow.start();
ObjectAnimator animatorHide = ObjectAnimator.ofFloat(floatView, "alpha", 1.0f,0.0f);
animatorHide.setDuration(500);
animatorHide.setStartDelay(3000);
animatorHide.start();
floatView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainService.this, "點擊淘口令", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(MainService.this, xxActivity.class);
startActivity(intent);
}
});
很簡單的小功能,不過應用的實際過程應該還會出現一些待解決的小問題