Android 輔助功能 -搶紅包
本篇文章主要介紹下透過android輔助功能的方式來實現類似搶紅包的功能.
1:許可權宣告
<uses-permission
android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
tools:ignore="ProtectedPermissions" />
2: 配置資訊
xml目錄下建立如下檔案:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackAllMask"
android:accessibilityFlags="flagDefault"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:description="@string/desc"
android:packageNames= "com.test.redpacket">
</accessibility-service>
- android:accessibilityEventTypes 定義服務要監聽的事件型別
- android:accessibilityFeedbackType 定義了服務的反饋型別
- android:accessibilityFlags 定義服務的行為標誌
- android:description 描述資訊 (需要使用資原始檔配置)
- android:canRetrieveWindowContent 定義了服務是否可以獲取視窗內容
- android:packageNames定義了監聽的包名
3: 自定義AccessibilityService
具體的程式碼如下:
public class RedPacketAccessibilityService extends AccessibilityService {
private static final String TAG = "RedPacketAccessibilityService";
@SuppressLint("LongLogTag")
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
int action = event.getAction();
Log.i(TAG, "onAccessibilityEvent: " + action);
CharSequence packageName = event.getPackageName();
Log.i(TAG, "onAccessibilityEvent: " + packageName);
AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
if (rootInActiveWindow != null) {
List<AccessibilityNodeInfo> nodeInfos = rootInActiveWindow.findAccessibilityNodeInfosByText("紅包:恭喜發財");
if (nodeInfos != null) {
for (AccessibilityNodeInfo nodeInfo : nodeInfos) {
nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
}
}
@Override
public void onInterrupt() {
}
}
此處透過findAccessibilityNodeInfosByText來查詢節點了, 我們還可以使用 findAccessibilityNodeInfosByViewId來實現.
4: 服務宣告
在manifest.xml中宣告服務.
<service
android:name=".RedPacketAccessibilityService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/acc" />
</service>
5: 測試程式碼
public class MainActivity extends AppCompatActivity {
private Button btnSend;
private TextView tvMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend=findViewById(R.id.btn_send);
tvMsg=findViewById(R.id.tv_msg);
Intent serviceIntent = new Intent(this, RedPacketAccessibilityService.class);
startService(serviceIntent);
btnSend.setOnClickListener(v -> {
tvMsg.setText("紅包:恭喜發財");
});
tvMsg.setOnClickListener(v -> {
tvMsg.setText("訊息展示");
Toast.makeText(MainActivity.this,"搶紅包",Toast.LENGTH_SHORT).show();
});
}
}
本文由部落格一文多發平臺 OpenWrite 釋出!