Beispiel #1
1
 @Override
 public int compare(Intent i1, Intent i2) {
   if (i1 == null && i2 == null) return 0;
   if (i1 == null && i2 != null) return -1;
   if (i1 != null && i2 == null) return 1;
   if (i1.equals(i2)) return 0;
   String action1 = i1.getAction();
   String action2 = i2.getAction();
   if (action1 == null && action2 != null) return -1;
   if (action1 != null && action2 == null) return 1;
   if (action1 != null && action2 != null) {
     if (!action1.equals(action2)) {
       return action1.compareTo(action2);
     }
   }
   Uri data1 = i1.getData();
   Uri data2 = i2.getData();
   if (data1 == null && data2 != null) return -1;
   if (data1 != null && data2 == null) return 1;
   if (data1 != null && data2 != null) {
     if (!data1.equals(data2)) {
       return data1.compareTo(data2);
     }
   }
   ComponentName component1 = i1.getComponent();
   ComponentName component2 = i2.getComponent();
   if (component1 == null && component2 != null) return -1;
   if (component1 != null && component2 == null) return 1;
   if (component1 != null && component2 != null) {
     if (!component1.equals(component2)) {
       return component1.compareTo(component2);
     }
   }
   String package1 = i1.getPackage();
   String package2 = i2.getPackage();
   if (package1 == null && package2 != null) return -1;
   if (package1 != null && package2 == null) return 1;
   if (package1 != null && package2 != null) {
     if (!package1.equals(package2)) {
       return package1.compareTo(package2);
     }
   }
   Set<String> categories1 = i1.getCategories();
   Set<String> categories2 = i2.getCategories();
   if (categories1 == null) return categories2 == null ? 0 : -1;
   if (categories2 == null) return 1;
   if (categories1.size() > categories2.size()) return 1;
   if (categories1.size() < categories2.size()) return -1;
   String[] array1 = categories1.toArray(new String[0]);
   String[] array2 = categories2.toArray(new String[0]);
   Arrays.sort(array1);
   Arrays.sort(array2);
   for (int i = 0; i < array1.length; ++i) {
     int val = array1[i].compareTo(array2[i]);
     if (val != 0) return val;
   }
   return 0;
 }
 @Override
 public int compare(Intent i1, Intent i2) {
   if (i1 == null && i2 == null) return 0;
   if (i1 == null && i2 != null) return -1;
   if (i1 != null && i2 == null) return 1;
   if (i1.equals(i2)) return 0;
   if (i1.getAction() == null && i2.getAction() != null) return -1;
   if (i1.getAction() != null && i2.getAction() == null) return 1;
   if (i1.getAction() != null && i2.getAction() != null) {
     if (!i1.getAction().equals(i2.getAction())) {
       return i1.getAction().compareTo(i2.getAction());
     }
   }
   if (i1.getData() == null && i2.getData() != null) return -1;
   if (i1.getData() != null && i2.getData() == null) return 1;
   if (i1.getData() != null && i2.getData() != null) {
     if (!i1.getData().equals(i2.getData())) {
       return i1.getData().compareTo(i2.getData());
     }
   }
   if (i1.getComponent() == null && i2.getComponent() != null) return -1;
   if (i1.getComponent() != null && i2.getComponent() == null) return 1;
   if (i1.getComponent() != null && i2.getComponent() != null) {
     if (!i1.getComponent().equals(i2.getComponent())) {
       return i1.getComponent().compareTo(i2.getComponent());
     }
   }
   if (i1.getPackage() == null && i2.getPackage() != null) return -1;
   if (i1.getPackage() != null && i2.getPackage() == null) return 1;
   if (i1.getPackage() != null && i2.getPackage() != null) {
     if (!i1.getPackage().equals(i2.getPackage())) {
       return i1.getPackage().compareTo(i2.getPackage());
     }
   }
   Set<String> categories1 = i1.getCategories();
   Set<String> categories2 = i2.getCategories();
   if (categories1 == null) return categories2 == null ? 0 : -1;
   if (categories2 == null) return 1;
   if (categories1.size() > categories2.size()) return 1;
   if (categories1.size() < categories2.size()) return -1;
   String[] array1 = categories1.toArray(new String[0]);
   String[] array2 = categories2.toArray(new String[0]);
   Arrays.sort(array1);
   Arrays.sort(array2);
   for (int i = 0; i < array1.length; ++i) {
     int val = array1[i].compareTo(array2[i]);
     if (val != 0) return val;
   }
   return 0;
 }
Beispiel #3
1
  @Test
  public void shouldFillIn() throws Exception {
    Intent intentA = new Intent();
    Intent intentB = new Intent();

    intentB.setAction("foo");
    Uri uri = Uri.parse("http://www.foo.com");
    intentB.setDataAndType(uri, "text/html");
    String category = "category";
    intentB.addCategory(category);
    intentB.setPackage("com.foobar.app");
    ComponentName cn = new ComponentName("com.foobar.app", "fragmentActivity");
    intentB.setComponent(cn);
    intentB.putExtra("FOO", 23);

    int flags =
        Intent.FILL_IN_ACTION
            | Intent.FILL_IN_DATA
            | Intent.FILL_IN_CATEGORIES
            | Intent.FILL_IN_PACKAGE
            | Intent.FILL_IN_COMPONENT;

    int result = intentA.fillIn(intentB, flags);
    assertEquals("foo", intentA.getAction());
    assertSame(uri, intentA.getData());
    assertEquals("text/html", intentA.getType());
    assertTrue(intentA.getCategories().contains(category));
    assertEquals("com.foobar.app", intentA.getPackage());
    assertSame(cn, intentA.getComponent());
    assertEquals(23, intentA.getIntExtra("FOO", -1));
    assertEquals(result, flags);
  }
Beispiel #4
1
 @Test
 public void shouldAddCategories() throws Exception {
   Intent intent = new Intent();
   Intent self = intent.addCategory("foo");
   assertTrue(intent.getCategories().contains("foo"));
   assertSame(self, intent);
 }
  private static String findClassNameByIntent(
      Intent intent, HashMap<String, ArrayList<PluginIntentFilter>> intentFilter) {
    if (intentFilter != null) {

      Iterator<Entry<String, ArrayList<PluginIntentFilter>>> entry =
          intentFilter.entrySet().iterator();
      while (entry.hasNext()) {
        Entry<String, ArrayList<PluginIntentFilter>> item = entry.next();
        Iterator<PluginIntentFilter> values = item.getValue().iterator();
        while (values.hasNext()) {
          PluginIntentFilter filter = values.next();
          int result =
              filter.match(
                  intent.getAction(),
                  intent.getType(),
                  intent.getScheme(),
                  intent.getData(),
                  intent.getCategories());

          if (result != PluginIntentFilter.NO_MATCH_ACTION
              && result != PluginIntentFilter.NO_MATCH_CATEGORY
              && result != PluginIntentFilter.NO_MATCH_DATA
              && result != PluginIntentFilter.NO_MATCH_TYPE) {
            return item.getKey();
          }
        }
      }
    }
    return null;
  }
 private static FastImmutableArraySet<String> getFastIntentCategories(Intent intent) {
   final Set<String> categories = intent.getCategories();
   if (categories == null) {
     return null;
   }
   return new FastImmutableArraySet<String>(categories.toArray(new String[categories.size()]));
 }
 private static void dumpIntent(String prefix, Intent intent) {
   Log.v(prefix + "Flags:" + dumpFlags(intent.getFlags()));
   Log.v(prefix + "Action:" + intent.getAction());
   Log.v(prefix + "Categories:");
   if (intent.getCategories() != null) {
     for (String str : intent.getCategories()) Log.v(prefix + "  " + str);
   }
   Log.v(prefix + "Type:" + intent.getType());
   Log.v(prefix + "Data:" + intent.getDataString());
   Log.v(prefix + "Pkg:" + intent.getPackage());
   ComponentName comp = intent.getComponent();
   Log.v(prefix + "Comp:" + (comp == null ? null : intent.getComponent().flattenToString()));
   Bundle extra = intent.getExtras();
   if (extra != null) {
     for (String key : extra.keySet()) {
       dumpKeyValue(prefix + "  ", key, extra.get(key));
     }
   }
 }
Beispiel #8
0
  @Override
  public void onReceive(Context context, Intent intent) {
    Intent start_service = new Intent();
    start_service.putExtras(intent);

    if (intent.getCategories().contains("com.mwr.dz.START_EMBEDDED")) {
      start_service.addCategory("com.mwr.dz.START_EMBEDDED");
      start_service.setComponent(
          new ComponentName("com.mwr.dz", "com.mwr.dz.services.ServerService"));
    } else {
      if (intent.getCategories().contains("com.mwr.dz.CREATE_ENDPOINT"))
        start_service.addCategory("com.mwr.dz.CREATE_ENDPOINT");
      if (intent.getCategories().contains("com.mwr.dz.START_ENDPOINT"))
        start_service.addCategory("com.mwr.dz.START_ENDPOINT");

      start_service.setComponent(
          new ComponentName("com.mwr.dz", "com.mwr.dz.services.ClientService"));
    }

    context.startService(start_service);
  }
 /**
  * Returns true if the intent is a valid launch intent for a shortcut. This is used to identify
  * shortcuts which are different from the ones exposed by the applications' manifest file.
  *
  * <p>When DISABLE_ALL_APPS is true, shortcuts exposed via the app's manifest should never be
  * duplicated or removed(unless the app is un-installed).
  *
  * @param launchIntent The intent that will be launched when the shortcut is clicked.
  */
 static boolean isValidShortcutLaunchIntent(Intent launchIntent) {
   if (launchIntent != null
       && Intent.ACTION_MAIN.equals(launchIntent.getAction())
       && launchIntent.getComponent() != null
       && launchIntent.getCategories() != null
       && launchIntent.getCategories().size() == 1
       && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
       && launchIntent.getExtras() == null
       && TextUtils.isEmpty(launchIntent.getDataString())) {
     return false;
   }
   return true;
 }
Beispiel #10
0
  private boolean resolveIntent(Intent intent) {
    Uri data = intent.getData();
    String host = data.getHost();

    if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
      log("resolveIntent: host=" + host);
    }

    if (TextUtils.isEmpty(host)) {
      Set<String> categories = intent.getCategories();
      if (categories != null) {
        Iterator<String> iter = categories.iterator();
        if (iter.hasNext()) {
          String category = iter.next();
          String providerName = getProviderNameForCategory(category);
          mProviderName = findMatchingProvider(providerName);
          if (mProviderName == null) {
            Log.w(ImApp.LOG_TAG, "resolveIntent: IM provider " + category + " not supported");
            return false;
          }
        }
      }
      mToAddress = data.getSchemeSpecificPart();
    } else {
      mProviderName = findMatchingProvider(host);

      if (mProviderName == null) {
        Log.w(ImApp.LOG_TAG, "resolveIntent: IM provider " + host + " not supported");
        return false;
      }

      String path = data.getPath();

      if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) log("resolveIntent: path=" + path);

      if (!TextUtils.isEmpty(path)) {
        int index;
        if ((index = path.indexOf('/')) != -1) {
          mToAddress = path.substring(index + 1);
        }
      }
    }

    if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
      log("resolveIntent: provider=" + mProviderName + ", to=" + mToAddress);
    }

    return true;
  }
Beispiel #11
0
  @Test
  public void shouldSupportCategories() throws Exception {
    Intent intent = new Intent();
    Intent self = intent.addCategory("category.name.1");
    intent.addCategory("category.name.2");

    assertTrue(intent.hasCategory("category.name.1"));
    assertTrue(intent.hasCategory("category.name.2"));

    Set<String> categories = intent.getCategories();
    assertTrue(categories.contains("category.name.1"));
    assertTrue(categories.contains("category.name.2"));

    intent.removeCategory("category.name.1");
    assertFalse(intent.hasCategory("category.name.1"));
    assertTrue(intent.hasCategory("category.name.2"));

    intent.removeCategory("category.name.2");
    assertFalse(intent.hasCategory("category.name.2"));

    assertEquals(0, intent.getCategories().size());

    assertSame(self, intent);
  }
 private void fillIntent(@Nullable Intent intent, @NonNull TextView textView) {
   if (intent == null) {
     textView.setText(Printer.EMPTY);
     return;
   }
   Truss truss = new Truss();
   Printer.append(truss, "action", intent.getAction());
   Printer.append(truss, "categories", intent.getCategories());
   Printer.append(truss, "type", intent.getType());
   Printer.append(truss, "flags", Flags.decode(intent.getFlags()));
   Printer.append(truss, "package", intent.getPackage());
   Printer.append(truss, "component", intent.getComponent());
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
     Printer.append(truss, "referrer", getReferrer());
   }
   textView.setText(truss.build());
 }
 /**
  * Returns true if the intent is a valid launch intent for a launcher activity of an app. This is
  * used to identify shortcuts which are different from the ones exposed by the applications'
  * manifest file.
  *
  * @param launchIntent The intent that will be launched when the shortcut is clicked.
  */
 public static boolean isLauncherAppTarget(Intent launchIntent) {
   if (launchIntent != null
       && Intent.ACTION_MAIN.equals(launchIntent.getAction())
       && launchIntent.getComponent() != null
       && launchIntent.getCategories() != null
       && launchIntent.getCategories().size() == 1
       && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
       && TextUtils.isEmpty(launchIntent.getDataString())) {
     // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
     Bundle extras = launchIntent.getExtras();
     if (extras == null) {
       return true;
     } else {
       Set<String> keys = extras.keySet();
       return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
     }
   }
   ;
   return false;
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    Set<String> cats = intent.getCategories();

    // Show the category of this notification
    for (String currentCat : cats) {
      String msg = "Received notification : " + intent.getAction() + "\nC:[" + currentCat + "]";
      Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    // If there is custom params, display each of these
    try {
      Set<String> extras = intent.getExtras().keySet();
      for (String extra : extras) {
        String msg = "Key: " + extra + " Value: " + intent.getExtras().getString(extra);
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
      }

    } catch (Exception e) {
      Toast.makeText(context, "No extras", Toast.LENGTH_SHORT).show();
    }
  }
Beispiel #15
0
 private static String intentToString(Intent intent) {
   // TODO temporary implementation - needs to order categories
   Bundle extras = intent.getExtras();
   TreeSet<String> keys = new TreeSet<String>(intent.getExtras().keySet());
   String intentString =
       intent.getClass()
           + "|"
           + intent.getAction()
           + "|"
           + intent.getDataString()
           + "|"
           + intent.getType()
           + "|"
           + intent.getCategories();
   Iterator<String> it = keys.iterator();
   while (it.hasNext()) {
     String key = it.next();
     intentString += "|" + key + ":" + extras.get(key).toString();
   }
   Log.i("Veecheck", intentString);
   return intentString;
 }
Beispiel #16
0
  private Map<String, Object> parseIntent(Intent intent) {
    Map<String, Object> params = new HashMap<String, Object>();

    if (intent != null) {
      String action = intent.getAction();
      if (action != null) {
        params.put(HK_ACTION, action);
      }

      Set<String> categories = intent.getCategories();
      if (categories != null) {
        params.put(HK_CATEGORIES, categories);
      }

      String appName = intent.getPackage();
      if (appName != null) {
        params.put(HK_APP_NAME, appName);
      }

      String uri = intent.getDataString();
      if (uri != null) {
        uri = Uri.decode(uri);
        params.put(HK_URI, uri);
      }

      String mime = intent.getType();
      if (mime != null) {
        params.put(HK_MIME_TYPE, mime);
      }

      Bundle extras = intent.getExtras();
      if (extras != null) {
        params.put(HK_DATA, extras);
      }
    }

    return params;
  }
 public boolean sendBroadcast(Intent paramIntent)
 {
   int i;
   label57: int j;
   label162: int l;
   ArrayList localArrayList2;
   synchronized (this.mReceivers)
   {
     String str1 = paramIntent.getAction();
     String str2 = paramIntent.resolveTypeIfNeeded(this.mAppContext.getContentResolver());
     Uri localUri = paramIntent.getData();
     String str3 = paramIntent.getScheme();
     Set localSet = paramIntent.getCategories();
     if ((0x8 & paramIntent.getFlags()) == 0)
       break label500;
     i = 1;
     if (i != 0)
       Log.v("LocalBroadcastManager", "Resolving type " + str2 + " scheme " + str3 + " of intent " + paramIntent);
     ArrayList localArrayList1 = (ArrayList)this.mActions.get(paramIntent.getAction());
     if (localArrayList1 == null)
       break label481;
     if (i == 0)
       break label485;
     Log.v("LocalBroadcastManager", "Action list: " + localArrayList1);
     break label485:
     if (j >= localArrayList1.size())
       break label534;
     ReceiverRecord localReceiverRecord = (ReceiverRecord)localArrayList1.get(j);
     if (i != 0)
       Log.v("LocalBroadcastManager", "Matching against filter " + localReceiverRecord.filter);
     if (localReceiverRecord.broadcasting)
     {
       if (i != 0)
         Log.v("LocalBroadcastManager", "  Filter's target already added");
     }
     else
     {
       l = localReceiverRecord.filter.match(str1, str2, str3, localUri, localSet, "LocalBroadcastManager");
       if (l >= 0)
       {
         if (i != 0)
           Log.v("LocalBroadcastManager", "  Filter matched!  match=0x" + Integer.toHexString(l));
         if (localArrayList2 == null)
           localArrayList2 = new ArrayList();
         localArrayList2.add(localReceiverRecord);
         localReceiverRecord.broadcasting = true;
       }
     }
   }
   String str4;
   if (i != 0)
     switch (l)
     {
     default:
       str4 = "unknown reason";
       label380: Log.v("LocalBroadcastManager", "  Filter did not match: " + str4);
       break;
     case -3:
     case -4:
     case -2:
     case -1:
     }
   while (true)
   {
     if (k < localArrayList2.size())
     {
       ((ReceiverRecord)localArrayList2.get(k)).broadcasting = false;
       ++k;
     }
     this.mPendingBroadcasts.add(new BroadcastRecord(paramIntent, localArrayList2));
     if (!this.mHandler.hasMessages(1))
       this.mHandler.sendEmptyMessage(1);
     monitorexit;
     return true;
     do
     {
       label481: monitorexit;
       return false;
       label485: j = 0;
       localArrayList2 = null;
       break label162:
       ++j;
       break label162:
       label500: i = 0;
       break label57:
       str4 = "action";
       break label380:
       str4 = "category";
       break label380:
       str4 = "data";
       break label380:
       str4 = "type";
       label534: break label380:
     }
     while (localArrayList2 == null);
     int k = 0;
   }
 }
  /**
   * Called when the activity is first create; we wouldn't create a layout in the case where we have
   * the file and are moving to another activity without downloading.
   */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GameActivity.Log.debug("Starting DownloaderActivity...");
    _download = this;
    // Create somewhere to place the output - we'll check this on 'finish' to make sure we are
    // returning 'something'
    OutputData = new Intent();

    /** Both downloading and validation make use of the "download" UI */
    initializeDownloadUI();
    GameActivity.Log.debug("... UI setup. Checking for files.");

    /**
     * Before we do anything, are the files we expect already here and delivered (presumably by
     * Market) For free titles, this is probably worth doing. (so no Market request is necessary)
     */
    if (!expansionFilesDelivered()) {
      GameActivity.Log.debug("... Whoops... missing; go go go download system!");

      try {

        // Make sure we have a key before we try to start the service
        if (OBBDownloaderService.getPublicKeyLength() == 0) {
          AlertDialog.Builder builder = new AlertDialog.Builder(this);

          builder
              .setCancelable(false)
              .setTitle("No Google Play Store Key")
              .setMessage(
                  "No OBB found and no store key to try to download. Please set one up in Android Project Settings")
              .setPositiveButton(
                  "Exit",
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                      OutputData.putExtra(
                          GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_NO_PLAY_KEY);
                      setResult(RESULT_OK, OutputData);
                      finish();
                    }
                  });

          AlertDialog alert = builder.create();
          alert.show();
        } else {

          Intent launchIntent = DownloaderActivity.this.getIntent();
          Intent intentToLaunchThisActivityFromNotification =
              new Intent(DownloaderActivity.this, DownloaderActivity.this.getClass());
          intentToLaunchThisActivityFromNotification.setFlags(
              Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
          intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());

          if (launchIntent.getCategories() != null) {
            for (String category : launchIntent.getCategories()) {
              intentToLaunchThisActivityFromNotification.addCategory(category);
            }
          }

          // Build PendingIntent used to open this activity from
          // Notification
          PendingIntent pendingIntent =
              PendingIntent.getActivity(
                  DownloaderActivity.this,
                  0,
                  intentToLaunchThisActivityFromNotification,
                  PendingIntent.FLAG_UPDATE_CURRENT);
          // Request to start the download
          int startResult =
              DownloaderClientMarshaller.startDownloadServiceIfRequired(
                  this, pendingIntent, OBBDownloaderService.class);

          if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
            // The DownloaderService has started downloading the files,
            // show progress
            initializeDownloadUI();
            return;
          } // otherwise, download not needed so we fall through to saying all is OK
          else {
            OutputData.putExtra(
                GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_FILES_PRESENT);
            setResult(RESULT_OK, OutputData);
            finish();
          }
        }

      } catch (NameNotFoundException e) {
        Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
        e.printStackTrace();
      }

    } else {
      GameActivity.Log.debug("... Can has! Check 'em Dano!");
      if (!onlySingleExpansionFileFound()) {
        // Do some UI here to figure out which we want to keep

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder
            .setCancelable(false)
            .setTitle("Select OBB to use")
            .setItems(
                OBBSelectItems,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int item) {
                    DownloaderActivity.RemoveOBBFile(item);
                    ProcessOBBFiles();
                  }
                });

        AlertDialog alert = builder.create();
        alert.show();
      } else {
        ProcessOBBFiles();
      }
    }
  }
Beispiel #19
0
  private boolean matchIntentFilter(ActivityData activityData, Intent intent) {
    for (IntentFilterData intentFilterData : activityData.getIntentFilters()) {
      List<String> actionList = intentFilterData.getActions();
      List<String> categoryList = intentFilterData.getCategories();
      IntentFilter intentFilter = new IntentFilter();

      for (String action : actionList) {
        intentFilter.addAction(action);
      }

      for (String category : categoryList) {
        intentFilter.addCategory(category);
      }

      for (String scheme : intentFilterData.getSchemes()) {
        intentFilter.addDataScheme(scheme);
      }

      for (String mimeType : intentFilterData.getMimeTypes()) {
        try {
          intentFilter.addDataType(mimeType);
        } catch (IntentFilter.MalformedMimeTypeException ex) {
          throw new RuntimeException(ex);
        }
      }

      for (String path : intentFilterData.getPaths()) {
        intentFilter.addDataPath(path, PatternMatcher.PATTERN_LITERAL);
      }

      for (String pathPattern : intentFilterData.getPathPatterns()) {
        intentFilter.addDataPath(pathPattern, PatternMatcher.PATTERN_SIMPLE_GLOB);
      }

      for (String pathPrefix : intentFilterData.getPathPrefixes()) {
        intentFilter.addDataPath(pathPrefix, PatternMatcher.PATTERN_PREFIX);
      }

      for (IntentFilterData.DataAuthority authority : intentFilterData.getAuthorities()) {
        intentFilter.addDataAuthority(authority.getHost(), authority.getPort());
      }

      // match action
      boolean matchActionResult = intentFilter.matchAction(intent.getAction());
      // match category
      String matchCategoriesResult = intentFilter.matchCategories(intent.getCategories());
      // match data

      int matchResult =
          intentFilter.matchData(
              intent.getType(),
              (intent.getData() != null ? intent.getData().getScheme() : null),
              intent.getData());
      if (matchActionResult
          && (matchCategoriesResult == null)
          && (matchResult != IntentFilter.NO_MATCH_DATA
              && matchResult != IntentFilter.NO_MATCH_TYPE)) {
        return true;
      }
    }
    return false;
  }
Beispiel #20
0
  /**
   * Parses Intents from the named package's dependency metadata, and returns them as a list.
   * Returns null if no such metadata was found.
   */
  public static List<Intent> parseIntents(Context context, String packageName) {
    // Grab applicaton info.
    PackageManager pm = context.getPackageManager();
    ApplicationInfo appInfo;
    try {
      appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException ex) {
      Log.e(LTAG, String.format("Package '%s' not found!", packageName));
      return null;
    }

    if (null == appInfo) {
      Log.e(LTAG, String.format("Package '%s' not found!", packageName));
      return null;
    }

    // Start parsing metadata
    XmlResourceParser xml = appInfo.loadXmlMetaData(pm, Schemas.Client.META_DATA_LABEL);
    if (null == xml) {
      Log.e(
          LTAG,
          String.format(
              "Package '%s' does not contain meta-data named '%s'",
              packageName, Schemas.Client.META_DATA_LABEL));
      return null;
    }

    LinkedList<Intent> result = null;
    Intent intent = null;
    try {
      int tagType = xml.next();
      while (XmlPullParser.END_DOCUMENT != tagType) {

        if (XmlPullParser.START_TAG == tagType) {

          AttributeSet attr = Xml.asAttributeSet(xml);

          if (xml.getName().equals(Schemas.Client.ELEM_DEPENDENCIES)) {
            result = new LinkedList<Intent>();
          } else if (xml.getName().equals(Schemas.Client.ELEM_INTENT)) {
            intent = new Intent();

            String ctype =
                attr.getAttributeValue(Schemas.Client.SCHEMA, Schemas.Client.ATTR_COMPONENT_TYPE);
            if (null != ctype) {
              intent.putExtra(Schemas.Client.EXTRA_COMPONENT_TYPE, ctype);
            }
          } else if (xml.getName().equals(Schemas.Client.ELEM_COMPONENT)) {
            String name = attr.getAttributeValue(Schemas.Client.SCHEMA, Schemas.Client.ATTR_NAME);
            if (null != name) {
              ComponentName cname = ComponentName.unflattenFromString(name);
              intent.setComponent(cname);
            }
          } else if (xml.getName().equals(Schemas.Client.ELEM_ACTION)) {
            if (null != intent.getAction()) {
              Log.w(
                  LTAG,
                  String.format(
                      "Only one <%s> tag is supported per " + "<%s>; overwriting previous values.",
                      Schemas.Client.ELEM_ACTION, Schemas.Client.ELEM_INTENT));
            }
            String name = attr.getAttributeValue(Schemas.Client.SCHEMA, Schemas.Client.ATTR_NAME);
            if (null != name) {
              intent.setAction(name);
            }
          } else if (xml.getName().equals(Schemas.Client.ELEM_CATEGORY)) {
            String name = attr.getAttributeValue(Schemas.Client.SCHEMA, Schemas.Client.ATTR_NAME);
            if (null != name) {
              intent.addCategory(name);
            }
          } else if (xml.getName().equals(Schemas.Client.ELEM_DATA)) {
            String uri_string =
                attr.getAttributeValue(Schemas.Client.SCHEMA, Schemas.Client.ATTR_URI);
            Uri uri = null;
            if (null != uri_string) {
              uri = Uri.parse(uri_string);
            }

            String mimeType =
                attr.getAttributeValue(Schemas.Client.SCHEMA, Schemas.Client.ATTR_MIME_TYPE);

            if (null != uri && null != mimeType) {
              intent.setDataAndType(uri, mimeType);
            } else if (null != uri) {
              intent.setData(uri);
            } else if (null != mimeType) {
              intent.setType(mimeType);
            }
          }
        } else if (XmlPullParser.END_TAG == tagType) {

          if (xml.getName().equals(Schemas.Client.ELEM_INTENT)) {
            if (null != intent
                && (null != intent.getData()
                    || null != intent.getAction()
                    || null != intent.getCategories()
                    || null != intent.getType()
                    || null != intent.getComponent())) {
              result.add(intent);
            }
          }
        }

        tagType = xml.next();
      }

    } catch (XmlPullParserException ex) {
      Log.e(
          LTAG,
          String.format(
              "XML parse exception when parsing metadata for '%s': %s",
              packageName, ex.getMessage()));
    } catch (IOException ex) {
      Log.e(
          LTAG,
          String.format(
              "I/O exception when parsing metadata for '%s': %s", packageName, ex.getMessage()));
    }

    xml.close();

    if (null == result || 0 >= result.size()) {
      return null;
    }

    return result;
  }
  /**
   * Broadcast the given intent to all interested BroadcastReceivers. This call is asynchronous; it
   * returns immediately, and you will continue executing while the receivers are run.
   *
   * @param intent The Intent to broadcast; all receivers matching this Intent will receive the
   *     broadcast.
   * @see #registerReceiver
   */
  public boolean sendBroadcast(Intent intent) {
    synchronized (mReceivers) {
      final String action = intent.getAction();
      final String type = intent.resolveTypeIfNeeded(mAppContext.getContentResolver());
      final Uri data = intent.getData();
      final String scheme = intent.getScheme();
      final Set<String> categories = intent.getCategories();

      final boolean debug = DEBUG || ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
      if (debug)
        Log.v(TAG, "Resolving type " + type + " scheme " + scheme + " of intent " + intent);

      ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
      if (entries != null) {
        if (debug) Log.v(TAG, "Action list: " + entries);

        ArrayList<ReceiverRecord> receivers = null;
        for (int i = 0; i < entries.size(); i++) {
          ReceiverRecord receiver = entries.get(i);
          if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);

          if (receiver.broadcasting) {
            if (debug) {
              Log.v(TAG, "  Filter's target already added");
            }
            continue;
          }

          int match =
              receiver.filter.match(
                  action, type, scheme, data, categories, "LocalBroadcastManager");
          if (match >= 0) {
            if (debug) Log.v(TAG, "  Filter matched!  match=0x" + Integer.toHexString(match));
            if (receivers == null) {
              receivers = new ArrayList<ReceiverRecord>();
            }
            receivers.add(receiver);
            receiver.broadcasting = true;
          } else {
            if (debug) {
              String reason;
              switch (match) {
                case IntentFilter.NO_MATCH_ACTION:
                  reason = "action";
                  break;
                case IntentFilter.NO_MATCH_CATEGORY:
                  reason = "category";
                  break;
                case IntentFilter.NO_MATCH_DATA:
                  reason = "data";
                  break;
                case IntentFilter.NO_MATCH_TYPE:
                  reason = "type";
                  break;
                default:
                  reason = "unknown reason";
                  break;
              }
              Log.v(TAG, "  Filter did not match: " + reason);
            }
          }
        }

        if (receivers != null) {
          for (int i = 0; i < receivers.size(); i++) {
            receivers.get(i).broadcasting = false;
          }
          mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
          if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
            mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
          }
          return true;
        }
      }
    }
    return false;
  }
  private Intent makeIntent() {
    Intent intent = new Intent();
    boolean hasIntentInfo = false;

    mDebugOption = false;
    Uri data = null;
    String type = null;

    try {
      String opt;
      while ((opt = nextOption()) != null) {
        if (opt.equals("-a")) {
          intent.setAction(nextOptionData());
          hasIntentInfo = true;
        } else if (opt.equals("-d")) {
          data = Uri.parse(nextOptionData());
          hasIntentInfo = true;
        } else if (opt.equals("-t")) {
          type = nextOptionData();
          hasIntentInfo = true;
        } else if (opt.equals("-c")) {
          intent.addCategory(nextOptionData());
          hasIntentInfo = true;
        } else if (opt.equals("-e") || opt.equals("--es")) {
          String key = nextOptionData();
          String value = nextOptionData();
          intent.putExtra(key, value);
          hasIntentInfo = true;
        } else if (opt.equals("--ei")) {
          String key = nextOptionData();
          String value = nextOptionData();
          intent.putExtra(key, Integer.valueOf(value));
          hasIntentInfo = true;
        } else if (opt.equals("--ez")) {
          String key = nextOptionData();
          String value = nextOptionData();
          intent.putExtra(key, Boolean.valueOf(value));
          hasIntentInfo = true;
        } else if (opt.equals("-n")) {
          String str = nextOptionData();
          ComponentName cn = ComponentName.unflattenFromString(str);
          if (cn == null) {
            System.err.println("Error: Bad component name: " + str);
            showUsage();
            return null;
          }
          intent.setComponent(cn);
          hasIntentInfo = true;
        } else if (opt.equals("-f")) {
          String str = nextOptionData();
          intent.setFlags(Integer.decode(str).intValue());
        } else if (opt.equals("-D")) {
          mDebugOption = true;
        } else {
          System.err.println("Error: Unknown option: " + opt);
          showUsage();
          return null;
        }
      }
    } catch (RuntimeException ex) {
      System.err.println("Error: " + ex.toString());
      showUsage();
      return null;
    }
    intent.setDataAndType(data, type);

    String uri = nextArg();
    if (uri != null) {
      try {
        Intent oldIntent = intent;
        try {
          intent = Intent.getIntent(uri);
        } catch (java.net.URISyntaxException ex) {
          System.err.println("Bad URI: " + uri);
          showUsage();
          return null;
        }
        if (oldIntent.getAction() != null) {
          intent.setAction(oldIntent.getAction());
        }
        if (oldIntent.getData() != null || oldIntent.getType() != null) {
          intent.setDataAndType(oldIntent.getData(), oldIntent.getType());
        }
        Set cats = oldIntent.getCategories();
        if (cats != null) {
          Iterator it = cats.iterator();
          while (it.hasNext()) {
            intent.addCategory((String) it.next());
          }
        }
      } catch (RuntimeException ex) {
        System.err.println("Error creating from URI: " + ex.toString());
        showUsage();
        return null;
      }
    } else if (!hasIntentInfo) {
      System.err.println("Error: No intent supplied");
      showUsage();
      return null;
    }

    return intent;
  }
    public String encodeToString() {
      if (activityInfo != null) {
        try {
          // If it a launcher target, we only need component name, and user to
          // recreate this.
          return new JSONStringer()
              .object()
              .key(LAUNCH_INTENT_KEY)
              .value(launchIntent.toUri(0))
              .key(APP_SHORTCUT_TYPE_KEY)
              .value(true)
              .key(USER_HANDLE_KEY)
              .value(UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user))
              .endObject()
              .toString();
        } catch (JSONException e) {
          Log.d(TAG, "Exception when adding shortcut: " + e);
          return null;
        }
      }

      if (launchIntent.getAction() == null) {
        launchIntent.setAction(Intent.ACTION_VIEW);
      } else if (launchIntent.getAction().equals(Intent.ACTION_MAIN)
          && launchIntent.getCategories() != null
          && launchIntent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
        launchIntent.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      }

      // This name is only used for comparisons and notifications, so fall back to activity
      // name if not supplied
      String name = ensureValidName(mContext, launchIntent, label).toString();
      Bitmap icon = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
      Intent.ShortcutIconResource iconResource =
          data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);

      // Only encode the parameters which are supported by the API.
      try {
        JSONStringer json =
            new JSONStringer()
                .object()
                .key(LAUNCH_INTENT_KEY)
                .value(launchIntent.toUri(0))
                .key(NAME_KEY)
                .value(name);
        if (icon != null) {
          byte[] iconByteArray = ItemInfo.flattenBitmap(icon);
          json =
              json.key(ICON_KEY)
                  .value(
                      Base64.encodeToString(
                          iconByteArray, 0, iconByteArray.length, Base64.DEFAULT));
        }
        if (iconResource != null) {
          json = json.key(ICON_RESOURCE_NAME_KEY).value(iconResource.resourceName);
          json = json.key(ICON_RESOURCE_PACKAGE_NAME_KEY).value(iconResource.packageName);
        }
        return json.endObject().toString();
      } catch (JSONException e) {
        Log.d(TAG, "Exception when adding shortcut: " + e);
      }
      return null;
    }
  /**
   * Called when the activity is first create; we wouldn't create a layout in the case where we have
   * the file and are moving to another activity without downloading.
   */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mMe = this;

    /** Both downloading and validation make use of the "download" UI */
    initializeDownloadUI();

    /**
     * Before we do anything, are the files we expect already here and delivered (presumably by
     * Market) For free titles, this is probably worth doing. (so no Market request is necessary)
     */
    if (!expansionFilesDelivered()) {

      try {
        Intent launchIntent = GNURootDownloaderActivity.this.getIntent();
        Intent intentToLaunchThisActivityFromNotification =
            new Intent(GNURootDownloaderActivity.this, GNURootDownloaderActivity.this.getClass());
        intentToLaunchThisActivityFromNotification.setFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());

        if (launchIntent.getCategories() != null) {
          for (String category : launchIntent.getCategories()) {
            intentToLaunchThisActivityFromNotification.addCategory(category);
          }
        }

        // Build PendingIntent used to open this activity from
        // Notification
        PendingIntent pendingIntent =
            PendingIntent.getActivity(
                GNURootDownloaderActivity.this,
                0,
                intentToLaunchThisActivityFromNotification,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // Request to start the download
        int startResult =
            DownloaderClientMarshaller.startDownloadServiceIfRequired(
                this, pendingIntent, GNURootDownloaderService.class);

        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
          // The DownloaderService has started downloading the files,
          // show progress
          initializeDownloadUI();
          return;
        } // otherwise, download not needed so we fall through to
        // starting the movie
      } catch (NameNotFoundException e) {
        Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
        e.printStackTrace();
      }

      //        } else {
      //            validateXAPKZipFiles();
    } else {
      Intent intent = this.getIntent();
      this.setResult(xAPKS[0].mFileVersion, intent);
      finish();
    }
  }