@Test
  public void execute_whenUberAppInsalled_shouldPointToUberApp() throws IOException {
    String expectedUri =
        readUriResourceWithUserAgentParam(
            "src/test/resources/deeplinkuris/just_client_provided", USER_AGENT_DEEPLINK);

    Activity activity = Robolectric.setupActivity(Activity.class);
    ShadowActivity shadowActivity = shadowOf(activity);

    RobolectricPackageManager packageManager =
        (RobolectricPackageManager) shadowActivity.getPackageManager();

    PackageInfo uberPackage = new PackageInfo();
    uberPackage.packageName = UBER_PACKAGE_NAME;
    packageManager.addPackage(uberPackage);

    RideParameters rideParameters = new RideParameters.Builder().build();

    RequestDeeplink requestDeeplink =
        new RequestDeeplink.Builder()
            .setClientId(CLIENT_ID)
            .setRideParameters(rideParameters)
            .build();

    requestDeeplink.execute(activity);

    Intent startedIntent = shadowActivity.getNextStartedActivity();
    assertEquals(expectedUri, startedIntent.getData().toString());
  }
  private void initializePackageInfo() {
    if (packageList != null) {
      return;
    }

    PackageInfo packageInfo = new PackageInfo();
    packageInfo.packageName = contextWrapper.getPackageName();
    packageInfo.versionName = "1.0";

    packageList = new HashMap<String, PackageInfo>();
    addPackage(packageInfo);
  }
  @Test(expected = PackageManager.NameNotFoundException.class)
  public void removePackage_shouldHideItFromGetApplicationInfo() throws Exception {
    PackageInfo packageInfo = new PackageInfo();
    packageInfo.packageName = TEST_PACKAGE_NAME;
    packageInfo.applicationInfo = new ApplicationInfo();
    packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME;
    packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL;
    rpm.addPackage(packageInfo);
    rpm.removePackage(TEST_PACKAGE_NAME);

    rpm.getApplicationInfo(TEST_PACKAGE_NAME, 0);
  }
    @Override
    public List<PackageInfo> getInstalledPackages(int flags) {
      List<PackageInfo> packages = new ArrayList<PackageInfo>();

      if (isInstalled) {
        PackageInfo info = new PackageInfo();
        info.packageName = NATIVE_APP_PACKAGE;
        packages.add(info);
      }

      return packages;
    }
  @Test
  public void getApplicationInfo__OtherApplication() throws Exception {
    PackageInfo packageInfo = new PackageInfo();
    packageInfo.packageName = TEST_PACKAGE_NAME;
    packageInfo.applicationInfo = new ApplicationInfo();
    packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME;
    packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL;
    rpm.addPackage(packageInfo);

    ApplicationInfo info = rpm.getApplicationInfo(TEST_PACKAGE_NAME, 0);
    assertThat(info).isNotNull();
    assertThat(info.packageName).isEqualTo(TEST_PACKAGE_NAME);
    assertThat(rpm.getApplicationLabel(info).toString()).isEqualTo(TEST_PACKAGE_LABEL);
  }
Exemplo n.º 6
0
  @Override
  public void addPackage(String packageName) {
    PackageInfo packageInfo = new PackageInfo();
    packageInfo.packageName = packageName;

    ApplicationInfo applicationInfo = new ApplicationInfo();
    applicationInfo.packageName = packageName;
    applicationInfo.sourceDir = new File(".").getAbsolutePath();
    applicationInfo.dataDir = TempDirectory.create().toAbsolutePath().toString();

    packageInfo.applicationInfo = applicationInfo;

    addPackage(packageInfo);
  }
Exemplo n.º 7
0
  @Override
  public void addPackage(String packageName) {
    PackageInfo packageInfo = new PackageInfo();
    packageInfo.packageName = packageName;

    ApplicationInfo applicationInfo = new ApplicationInfo();
    applicationInfo.packageName = packageName;
    applicationInfo.sourceDir = new File(".").getAbsolutePath();
    applicationInfo.dataDir = createTempDir("android-tmp").getAbsolutePath();

    packageInfo.applicationInfo = applicationInfo;

    addPackage(packageInfo);
  }
  @Before
  public void reset() throws Exception {
    // reset Logger defaults:
    LogPersister.unsetContext();

    // clear all shared prefs
    SharedPreferences sharedPreferences =
        RuntimeEnvironment.application.getSharedPreferences(
            LogPersister.SHARED_PREF_KEY, Context.MODE_PRIVATE);
    sharedPreferences.edit().clear().commit();
    System.setProperty("http.agent", "Test user agent");

    PackageManager pm = activity.getPackageManager();
    PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), PackageManager.GET_SIGNATURES);
    pi.signatures = new Signature[] {new Signature("1234567890abcdef")};

    File file = new File(activity.getFilesDir(), FILE_NAME0);
    file.delete();
    file = new File(activity.getFilesDir(), FILE_NAME1);
    file.delete();
    file = new File(activity.getFilesDir(), FILE_NAME0 + ".send");
    file.delete();
    file = new File(activity.getFilesDir(), FILE_NAME1 + ".send");
    file.delete();
    file = new File(activity.getFilesDir(), ANALYTICS_FILE_NAME0);
    file.delete();
    file = new File(activity.getFilesDir(), ANALYTICS_FILE_NAME1);
    file.delete();
    file = new File(activity.getFilesDir(), ANALYTICS_FILE_NAME0 + ".send");
    file.delete();
    file = new File(activity.getFilesDir(), ANALYTICS_FILE_NAME1 + ".send");
    file.delete();

    // some tests below use FakeHttp.addPendingHttpResponse();.  We should clear them after every
    // test.
    FakeHttp.clearPendingHttpResponses();

    // reset the static flags in Logger that prevent accidental double sending of the
    // persistent file contents
    Field f1 = LogPersister.class.getDeclaredField("sendingLogs");
    f1.setAccessible(true);
    f1.set(null, false);
    Field f2 = LogPersister.class.getDeclaredField("sendingAnalyticsLogs");
    f2.setAccessible(true);
    f2.set(null, false);

    Logger.setLogPersister(new LogPersisterDelegate());
  }
Exemplo n.º 9
0
 @Override
 public PackageInfo getPackageInfo(String packageName, int flags) throws RemoteException {
   waitForReadyInner();
   try {
     String pkg = getAndCheckCallingPkg(packageName);
     if (pkg != null) {
       enforcePluginFileExists();
       PluginPackageParser parser = mPluginCache.get(pkg);
       if (parser != null) {
         PackageInfo packageInfo = parser.getPackageInfo(flags);
         if (packageInfo != null
             && (flags & PackageManager.GET_SIGNATURES) != 0
             && packageInfo.signatures == null) {
           packageInfo.signatures = mSignatureCache.get(packageName);
         }
         return packageInfo;
       }
     }
   } catch (Exception e) {
     handleException(e);
   }
   return null;
 }
 public void addPackage(String packageName) {
   PackageInfo info = new PackageInfo();
   info.packageName = packageName;
   addPackage(info);
 }
Exemplo n.º 11
0
  public boolean collectCertificates() {
    WeakReference<byte[]> readBufferRef;
    byte[] readBuffer = null;
    synchronized (this.getClass()) {
      readBufferRef = mReadBuffer;
      if (readBufferRef != null) {
        mReadBuffer = null;
        readBuffer = readBufferRef.get();
      }
      if (readBuffer == null) {
        readBuffer = new byte[8192];
        readBufferRef = new WeakReference<byte[]>(readBuffer);
      }
    }

    try {
      JarFile jarFile = new JarFile(mArchiveSourcePath);

      Certificate[] certs = null;

      Enumeration entries = jarFile.entries();
      while (entries.hasMoreElements()) {
        JarEntry je = (JarEntry) entries.nextElement();
        if (je.isDirectory()) continue;

        String name = je.getName();
        if (name.startsWith("META-INF/")) continue;

        if (mLibDir != null && name.startsWith("lib/") && !name.startsWith(mLibDir)) {
          // Ignore unused ABIs
          continue;
        }

        Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
        if (false) {
          Log.i(
              TAG,
              "File "
                  + mArchiveSourcePath
                  + " entry "
                  + name
                  + ": certs="
                  + certs
                  + " ("
                  + (certs != null ? certs.length : 0)
                  + ")");
        }
        if (localCerts == null) {
          Log.e(
              TAG,
              "Package " + mPackageName + " has no certificates at entry " + name + "; ignoring!");
          jarFile.close();
          return false;
        } else if (certs == null) {
          certs = localCerts;
        } else {
          // Ensure all certificates match.
          for (int i = 0; i < certs.length; i++) {
            boolean found = false;
            for (int j = 0; j < localCerts.length; j++) {
              if (certs[i] != null && certs[i].equals(localCerts[j])) {
                found = true;
                break;
              }
            }
            if (!found || certs.length != localCerts.length) {
              Log.e(
                  TAG,
                  "Package "
                      + mPackageName
                      + " has mismatched certificates at entry "
                      + name
                      + "; ignoring!");
              jarFile.close();
              return false;
            }
          }
        }
      }

      jarFile.close();

      synchronized (this.getClass()) {
        mReadBuffer = readBufferRef;
      }

      if (certs != null && certs.length > 0) {
        final int N = certs.length;
        mPackageInfo.signatures = new Signature[certs.length];
        for (int i = 0; i < N; i++) {
          mPackageInfo.signatures[i] = new Signature(certs[i].getEncoded());
        }
      } else {
        Log.e(TAG, "Package " + mPackageName + " has no certificates; ignoring!");
        return false;
      }
    } catch (CertificateEncodingException e) {
      Log.w(TAG, "Exception reading " + mArchiveSourcePath, e);
      return false;
    } catch (IOException e) {
      Log.w(TAG, "Exception reading " + mArchiveSourcePath, e);
      return false;
    } catch (RuntimeException e) {
      Log.w(TAG, "Exception reading " + mArchiveSourcePath, e);
      return false;
    }
    return true;
  }
Exemplo n.º 12
0
  public boolean collectActivities() {
    if (mPackageInfo == null || mPackageInfo.applicationInfo == null) return false;
    AttributeSet attrs = parser;

    int type;
    try {
      List<ActivityInfo> activities = new ArrayList<ActivityInfo>();
      while ((type = parser.next()) != XmlResourceParser.END_DOCUMENT) {
        if (type != XmlResourceParser.START_TAG) {
          continue;
        }

        String tagName = parser.getName();
        if (!tagName.equals("activity")) continue;

        // <activity ...
        ActivityInfo ai = new ActivityInfo();
        ai.applicationInfo = mPackageInfo.applicationInfo;
        ai.packageName = ai.applicationInfo.packageName;

        TypedArray sa = res.obtainAttributes(attrs, R.styleable.AndroidManifestActivity);
        String name = sa.getString(R.styleable.AndroidManifestActivity_name);
        if (name != null) {
          ai.name = ai.targetActivity = buildClassName(mPackageName, name);
        }
        ai.labelRes = sa.getResourceId(R.styleable.AndroidManifestActivity_label, 0);
        ai.icon = sa.getResourceId(R.styleable.AndroidManifestActivity_icon, 0);
        ai.theme = sa.getResourceId(R.styleable.AndroidManifestActivity_theme, 0);
        ai.launchMode = sa.getInteger(R.styleable.AndroidManifestActivity_launchMode, 0);
        //noinspection ResourceType
        ai.screenOrientation =
            sa.getInt(
                R.styleable.AndroidManifestActivity_screenOrientation,
                ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        ai.softInputMode =
            sa.getInteger(R.styleable.AndroidManifestActivity_windowSoftInputMode, 0);
        activities.add(ai);

        sa.recycle();

        // <intent-filter ...
        List<IntentFilter> intents = new ArrayList<IntentFilter>();
        int outerDepth = parser.getDepth();
        while ((type = parser.next()) != XmlResourceParser.END_DOCUMENT
            && (type != XmlResourceParser.END_TAG || parser.getDepth() > outerDepth)) {
          if (type == XmlResourceParser.END_TAG || type == XmlResourceParser.TEXT) {
            continue;
          }

          if (parser.getName().equals("intent-filter")) {
            IntentFilter intent = new IntentFilter();

            parseIntent(res, parser, attrs, true, true, intent);

            if (intent.countActions() == 0) {
              Log.w(
                  TAG,
                  "No actions in intent filter at "
                      + mArchiveSourcePath
                      + " "
                      + parser.getPositionDescription());
            } else {
              intents.add(intent);
            }
          }
        }

        if (intents.size() > 0) {
          if (mIntentFilters == null) {
            mIntentFilters = new ConcurrentHashMap<String, List<IntentFilter>>();
          }
          mIntentFilters.put(ai.name, intents);
        }
      }

      int N = activities.size();
      if (N > 0) {
        mPackageInfo.activities = new ActivityInfo[N];
        mPackageInfo.activities = activities.toArray(mPackageInfo.activities);
      }
      return true;
    } catch (XmlPullParserException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return false;
  }
Exemplo n.º 13
0
  private boolean parsePackage(Resources res, XmlResourceParser parser) {
    AttributeSet attrs = parser;
    mPackageInfo = new PackageInfo();

    try {
      int type;
      while ((type = parser.next()) != XmlResourceParser.START_TAG
          && type != XmlResourceParser.END_DOCUMENT) ;

      // <manifest ...
      mPackageInfo.packageName = parser.getAttributeValue(null, "package").intern();

      // After gradle-small 0.9.0, we roll out
      // `The Small exclusive flags`
      //  F    F    F    F    F    F    F    F
      // 1111 1111 1111 1111 1111 1111 1111 1111
      // ^^^^ ^^^^ ^^^^ ^^^^ ^^^^
      //       ABI Flags (20)
      //                          ^
      //                 nonResources Flag (1)
      //                           ^^^ ^^^^ ^^^^
      //                     platformBuildVersionCode (11) => MAX=0x7FF=4095
      int flags = parser.getAttributeIntValue(null, "platformBuildVersionCode", 0);
      int abiFlags = (flags & 0xFFFFF000) >> 12;
      mNonResources = (flags & 0x800) != 0;

      TypedArray sa = res.obtainAttributes(attrs, R.styleable.AndroidManifest);
      mPackageInfo.versionCode = sa.getInteger(R.styleable.AndroidManifest_versionCode, 0);
      String versionName = sa.getString(R.styleable.AndroidManifest_versionName);
      if (versionName != null) {
        mPackageInfo.versionName = versionName.intern();
      }

      // <application ...
      while ((type = parser.next()) != XmlResourceParser.END_DOCUMENT) {
        if (type == XmlResourceParser.TEXT) {
          continue;
        }

        String tagName = parser.getName();
        if (tagName.equals("application")) {
          ApplicationInfo app = new ApplicationInfo(Small.getContext().getApplicationInfo());

          sa = res.obtainAttributes(attrs, R.styleable.AndroidManifestApplication);

          String name = sa.getString(R.styleable.AndroidManifestApplication_name);
          if (name != null) {
            app.className = name.intern();
          } else {
            app.className = null;
          }

          // Get the label value which used as ABI flags.
          // This is depreciated, we read it from the `platformBuildVersionCode` instead.
          // TODO: Remove this if the gradle-small 0.9.0 or above being widely used.
          if (abiFlags == 0) {
            TypedValue label = new TypedValue();
            if (sa.getValue(R.styleable.AndroidManifestApplication_label, label)) {
              if (label.type == TypedValue.TYPE_STRING) {
                abiFlags = Integer.parseInt(label.string.toString());
              } else {
                abiFlags = label.data;
              }
            }
          }

          app.theme = sa.getResourceId(R.styleable.AndroidManifestApplication_theme, 0);
          mPackageInfo.applicationInfo = app;
          break;
        }
      }

      if (abiFlags != 0) {
        String abi = JNIUtils.getExtractABI(abiFlags, Bundle.is64bit());
        if (abi != null) {
          mLibDir = "lib/" + abi + "/";
        }
      }

      sa.recycle();
      return true;
    } catch (XmlPullParserException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return false;
  }
 protected static synchronized void a(Context context, String str, MMRequest mMRequest) {
   long j;
   long timeInMillis;
   int i = 0;
   synchronized (MMConversionTracker.class) {
     if (!(context == null || str == null)) {
       if (str.length() != 0) {
         GregorianCalendar gregorianCalendar;
         SharedPreferences sharedPreferences =
             context.getSharedPreferences("MillennialMediaSettings", 0);
         boolean z = sharedPreferences.getBoolean("firstLaunch_" + str, true);
         String string = sharedPreferences.getString(a, null);
         Map treeMap = new TreeMap();
         if (mMRequest != null) {
           mMRequest.a(treeMap);
           MMRequest.b(treeMap);
         }
         if (string != null) {
           String[] split = string.split("&");
           int length = split.length;
           while (i < length) {
             String[] split2 = split[i].split("=");
             if (split2.length >= 2) {
               treeMap.put(split2[0], split2[1]);
             }
             i++;
           }
         }
         if (z) {
           Editor edit = sharedPreferences.edit();
           edit.putBoolean("firstLaunch_" + str, false);
           edit.commit();
         }
         try {
           PackageInfo packageInfo =
               context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
           try {
             j = packageInfo.getClass().getField("firstInstallTime").getLong(packageInfo);
           } catch (Exception e) {
             MMLog.e(b, "Error with firstInstallTime", e);
             j = 0;
             if (j <= 0) {
               timeInMillis = j;
             } else {
               gregorianCalendar = new GregorianCalendar();
               gregorianCalendar.setTimeInMillis(j);
               gregorianCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
               timeInMillis = gregorianCalendar.getTimeInMillis();
             }
             if (MMSDK.a(context)) {
               MMLog.d(b, "No network available for conversion tracking.");
             } else {
               treeMap.put("ua", "Android:" + Build.MODEL);
               treeMap.put("apid", HandShake.a);
               MMSDK.a(context, treeMap);
               ThreadUtils.a(new AnonymousClass_1(str, z, timeInMillis, treeMap));
             }
           }
         } catch (NameNotFoundException e2) {
           MMLog.e(b, "Can't find packagename: ", e2);
         }
         if (j <= 0) {
           gregorianCalendar = new GregorianCalendar();
           gregorianCalendar.setTimeInMillis(j);
           gregorianCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
           timeInMillis = gregorianCalendar.getTimeInMillis();
         } else {
           timeInMillis = j;
         }
         if (MMSDK.a(context)) {
           MMLog.d(b, "No network available for conversion tracking.");
         } else {
           treeMap.put("ua", "Android:" + Build.MODEL);
           treeMap.put("apid", HandShake.a);
           MMSDK.a(context, treeMap);
           ThreadUtils.a(new AnonymousClass_1(str, z, timeInMillis, treeMap));
         }
       }
     }
   }
 }
Exemplo n.º 15
0
  @Override
  public void addManifest(AndroidManifest androidManifest) {
    androidManifests.put(androidManifest.getPackageName(), androidManifest);

    // first opportunity to access a resource index for this manifest, use it to init the references
    androidManifest.initMetaData(RuntimeEnvironment.getAppResourceLoader());

    PackageInfo packageInfo = new PackageInfo();
    packageInfo.packageName = androidManifest.getPackageName();
    packageInfo.versionName = androidManifest.getVersionName();
    packageInfo.versionCode = androidManifest.getVersionCode();

    ContentProviderData[] cpdata =
        androidManifest.getContentProviders().toArray(new ContentProviderData[] {});
    if (cpdata.length == 0) {
      packageInfo.providers = null;
    } else {
      packageInfo.providers = new ProviderInfo[cpdata.length];
      for (int i = 0; i < cpdata.length; i++) {
        ProviderInfo info = new ProviderInfo();
        info.authority = cpdata[i].getAuthority();
        info.name = cpdata[i].getClassName();
        info.packageName = androidManifest.getPackageName();
        packageInfo.providers[i] = info;
      }
    }

    // Populate information related to BroadcastReceivers. Broadcast receivers can be queried in two
    // possible ways,
    // 1. PackageManager#getPackageInfo(...),
    // 2. PackageManager#queryBroadcastReceivers(...)
    // The following piece of code will let you enable querying receivers through both the methods.
    List<ActivityInfo> receiverActivityInfos = new ArrayList<>();
    for (int i = 0; i < androidManifest.getBroadcastReceivers().size(); ++i) {
      ActivityInfo activityInfo = new ActivityInfo();
      activityInfo.name = androidManifest.getBroadcastReceivers().get(i).getClassName();
      activityInfo.permission = androidManifest.getBroadcastReceivers().get(i).getPermission();
      receiverActivityInfos.add(activityInfo);

      ResolveInfo resolveInfo = new ResolveInfo();
      resolveInfo.activityInfo = activityInfo;
      IntentFilter filter = new IntentFilter();
      for (String action : androidManifest.getBroadcastReceivers().get(i).getActions()) {
        filter.addAction(action);
      }
      resolveInfo.filter = filter;

      for (String action : androidManifest.getBroadcastReceivers().get(i).getActions()) {
        Intent intent = new Intent(action);
        intent.setPackage(androidManifest.getPackageName());
        addResolveInfoForIntent(intent, resolveInfo);
      }
    }
    packageInfo.receivers = receiverActivityInfos.toArray(new ActivityInfo[0]);

    String[] usedPermissions = androidManifest.getUsedPermissions().toArray(new String[] {});
    if (usedPermissions.length == 0) {
      packageInfo.requestedPermissions = null;
    } else {
      packageInfo.requestedPermissions = usedPermissions;
    }

    ApplicationInfo applicationInfo = new ApplicationInfo();
    applicationInfo.flags = androidManifest.getApplicationFlags();
    applicationInfo.targetSdkVersion = androidManifest.getTargetSdkVersion();
    applicationInfo.packageName = androidManifest.getPackageName();
    applicationInfo.processName = androidManifest.getProcessName();
    applicationInfo.name = androidManifest.getApplicationName();
    applicationInfo.metaData = metaDataToBundle(androidManifest.getApplicationMetaData());
    applicationInfo.sourceDir = new File(".").getAbsolutePath();
    applicationInfo.dataDir = TempDirectory.create().toAbsolutePath().toString();

    ResourceIndex resourceIndex = RuntimeEnvironment.getAppResourceLoader().getResourceIndex();
    if (androidManifest.getLabelRef() != null && resourceIndex != null) {
      Integer id =
          ResName.getResourceId(
              resourceIndex, androidManifest.getLabelRef(), androidManifest.getPackageName());
      applicationInfo.labelRes = id != null ? id : 0;
    }

    packageInfo.applicationInfo = applicationInfo;
    addPackage(packageInfo);
  }