2017-02-26 90 views
0

我正在通過Android Studio爲虛擬鼠標光標進行編程,這來自於此website及其code中的示例。我有一個覆蓋光標和以下代碼返回到主屏幕。Android虛擬鼠標光標無法在應用程序外部點擊

Intent newActivity = new Intent(Intent.ACTION_MAIN); 
newActivity.addCategory(Intent.CATEGORY_HOME); 
newActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(newActivity); 

我的問題是如何申請的點擊動作到我的遊標時的觀點是我的應用程序外(也許主屏幕或其他應用程序)。我想這

Instrumentation m_Instrumentation = new Instrumentation(); 
m_Instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,new_x, new_y, 0)); 
m_Instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, new_x, new_y, 0)); 

但它顯示

注入到另一個應用程序需要INJECT_EVENTS許可

然後,我在AndroidManifest.xml中添加了 <uses-permission android:name="android.permission.INJECT_EVENTS"/>。有一個錯誤,稱爲「權限只授予系統應用程序」,這樣我就不能在我的應用程序中使用它來執行虛擬點擊。如果我關閉檢查系統,它仍然不適用於我的應用程序。

在那之後,我試圖dispatchTouchEvent與處理程序,但它只是在自己的應用程序的工作原理(不能在主屏幕被用來打開其他應用程序。)

dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_DOWN, new_x, new_y, 0)); 
dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_UP, new_x, new_y, 0)); 

感謝您在回答。
我的模擬移動設備是Android 4.4.2。
編譯SDK版本:在Android 6.0
構建工具的版本:24.0.3

回答

0

你不能。出於安全原因,您不允許出於安全考慮,他們不希望某個應用程序能夠將命令發送給另一個應用程序。儀器的東西是單元測試,它的工作原理只是因爲測試套件是同一個應用程序的一部分。

+0

感謝送的點擊。如果我根據手機,我如何在我的項目中打開INJECT_EVENTS的權限? –

+0

您需要將清單添加到清單中,然後將自己安裝到系統apps目錄中(具體取決於您的版本,/ system/apps或/ system/priv-apps)。在那裏安裝的任何應用都可以請求系統權限所以它不適用於Play商店的應用程序,但它可以用於個人應用程序。 –

+0

我安裝了[this](https://kingroot.net/#)來根系我的系統,然後在我的AndroidManifest中添加了INJECT_EVENTS權限。但是,它顯示相同**注入到另一個應用程序需要INJECT_EVENTS權限**在我的調試窗口中。 –

0

您可能會發現此鏈接有用:)

https://github.com/chetbox/android-mouse-cursor

它沒有生根和他設法用這些線

private void click() { 
    Log.d(TAG, String.format("Click [%d, %d]", cursorLayout.x, cursorLayout.y)); 
    AccessibilityNodeInfo nodeInfo = getRootInActiveWindow(); 
    if (nodeInfo == null) return; 
    AccessibilityNodeInfo nearestNodeToMouse = findSmallestNodeAtPoint(nodeInfo, cursorLayout.x, cursorLayout.y + 50); 
    if (nearestNodeToMouse != null) { 
     logNodeHierachy(nearestNodeToMouse, 0); 
     nearestNodeToMouse.performAction(AccessibilityNodeInfo.ACTION_CLICK); 
    } 
    nodeInfo.recycle(); 
}