|
| 1 | +package com.android.adbkeyboard; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by andrewleo on 2017/11/1. |
| 5 | + */ |
| 6 | + |
| 7 | +import java.io.BufferedWriter; |
| 8 | +import java.io.File; |
| 9 | +import java.io.FileWriter; |
| 10 | +import java.io.IOException; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +import android.app.IntentService; |
| 14 | +import android.content.Intent; |
| 15 | +import android.content.pm.ApplicationInfo; |
| 16 | +import android.content.pm.PackageManager; |
| 17 | +import android.os.Bundle; |
| 18 | +import android.util.Log; |
| 19 | + |
| 20 | +import org.json.JSONArray; |
| 21 | +import org.json.JSONObject; |
| 22 | + |
| 23 | +public class ProcessInfoService extends IntentService { |
| 24 | + |
| 25 | + private static final String PROCESS_INFO_ACTION = "com.android.adbkeyboard.ProcessInfo"; |
| 26 | + private static final String DEFAULT_FILE_PATH = "/data/local/tmp/appinfos"; |
| 27 | + |
| 28 | + public ProcessInfoService() { |
| 29 | + super("ProcessInfoService"); |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + protected void onHandleIntent(Intent intent) { |
| 34 | + if (intent != null) { |
| 35 | + Bundle bundle = intent.getExtras(); |
| 36 | + String fileToSaved = (bundle != null) ? bundle.getString("fileToSave", |
| 37 | + DEFAULT_FILE_PATH) : DEFAULT_FILE_PATH; |
| 38 | + try { |
| 39 | + switch (intent.getAction()) { |
| 40 | + case PROCESS_INFO_ACTION: |
| 41 | + JSONArray jsonArray = new JSONArray(); |
| 42 | + PackageManager pm = this.getPackageManager(); |
| 43 | + for (ApplicationInfo appinfo : getAppInfos()) { |
| 44 | + JSONObject jsonObject = new JSONObject(); |
| 45 | + jsonObject.put(appinfo.loadLabel(pm).toString(), appinfo.processName); |
| 46 | + jsonArray.put(jsonObject); |
| 47 | + } |
| 48 | + saveToFile(fileToSaved, jsonArray.toString()); |
| 49 | + } |
| 50 | + } catch (Exception e) { |
| 51 | + Log.e("adbKeyBoard", e.getMessage()); |
| 52 | + e.printStackTrace(); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + } |
| 57 | + |
| 58 | + private void saveToFile(String filePath, String content) throws IOException { |
| 59 | + File file = new File(filePath); |
| 60 | + if (!file.exists()) { |
| 61 | + file.createNewFile(); |
| 62 | + } |
| 63 | + FileWriter fw = new FileWriter(file); |
| 64 | + BufferedWriter bw = new BufferedWriter(fw); |
| 65 | + bw.write(content); |
| 66 | + bw.close(); |
| 67 | + } |
| 68 | + |
| 69 | + private List<ApplicationInfo> getAppInfos() { |
| 70 | + PackageManager pm = getApplicationContext().getPackageManager(); |
| 71 | + List<ApplicationInfo> appList = pm |
| 72 | + .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES); |
| 73 | + return appList; |
| 74 | + } |
| 75 | +} |
0 commit comments