下面列出了android.content.Intent#getCategories ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testCategories() throws Exception {
Intent intent = intents.getActionIntent();
Set<String> categories = intent.getCategories();
assertEquals(0, categories == null ? 0 : categories.size()); // Have to test this way since robolectric doesn't return null for categories.
intent = intents.getSingleCategory();
categories = intent.getCategories();
assertEquals(1, categories.size());
assertTrue(categories.containsAll(Collections.singletonList("ONE")));
intent = intents.getCategories();
categories = intent.getCategories();
assertEquals(4, categories.size());
assertTrue(categories.containsAll(Arrays.asList("ONE", "TWO", "THREE", "FOUR")));
intent = intents.getAllPlusExtra("data", 0);
categories = intent.getCategories();
assertEquals(4, categories.size());
assertTrue(categories.containsAll(Arrays.asList("ONE", "TWO", "THREE", "FOUR")));
}
/**
* Updates |mIntentHistory| and |mLastIntentUpdatedTime|. If |intent| comes from chrome and
* currently |mIsOnEffectiveIntentRedirectChain| is true, that means |intent| was sent from
* this tab because only the front tab or a new tab can receive an intent from chrome. In that
* case, |intent| is added to |mIntentHistory|.
* Otherwise, |mIntentHistory| and |mPreviousResolvers| are cleared, and then |intent| is put
* into |mIntentHistory|.
*/
public void updateIntent(Intent intent) {
clear();
if (mContext == null || intent == null || !Intent.ACTION_VIEW.equals(intent.getAction())) {
return;
}
String chromePackageName = mContext.getPackageName();
// If an intent is heading explicitly to Chrome, we should stay in Chrome.
if (TextUtils.equals(chromePackageName, intent.getPackage())
|| TextUtils.equals(chromePackageName, IntentUtils.safeGetStringExtra(intent,
Browser.EXTRA_APPLICATION_ID))) {
mIsInitialIntentHeadingToChrome = true;
}
mIsCustomTabIntent = ChromeLauncherActivity.isCustomTabIntent(intent);
// Copies minimum information to retrieve resolvers.
mInitialIntent = new Intent(Intent.ACTION_VIEW);
mInitialIntent.setData(intent.getData());
if (intent.getCategories() != null) {
for (String category : intent.getCategories()) {
mInitialIntent.addCategory(category);
}
}
}
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()]));
}
public static boolean isShortcutToApp(String uri) {
try {
Intent intent = Intent.parseUri(uri, 0);
if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(intent.getAction())) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
private static ShortcutInfo getShortcutInfo(Context context, Intent data,
Intent launchIntent) {
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);
}
LauncherAppState app = LauncherAppState.getInstance();
ShortcutInfo info = app.getModel().infoFromShortcutIntent(context, data, null);
info.title = ensureValidName(context, launchIntent, info.title);
return info;
}
/**
* When handling an {@code Intent} from Messenger, call this to parse the parameters of the
* intent.
*
* @param intent the intent of the activity
* @return a {@link MessengerThreadParams} or null if this intent wasn't recognized as a request
* from Messenger to share.
*/
public static MessengerThreadParams getMessengerThreadParamsForIntent(Intent intent) {
Set<String> categories = intent.getCategories();
if (categories == null) {
return null;
}
if (categories.contains(ORCA_THREAD_CATEGORY_20150314)) {
Bundle appLinkExtras = AppLinks.getAppLinkExtras(intent);
String threadToken = appLinkExtras.getString(EXTRA_THREAD_TOKEN_KEY);
String metadata = appLinkExtras.getString(EXTRA_METADATA);
String participants = appLinkExtras.getString(EXTRA_PARTICIPANTS);
boolean isReply = appLinkExtras.getBoolean(EXTRA_IS_REPLY);
boolean isCompose = appLinkExtras.getBoolean(EXTRA_IS_COMPOSE);
MessengerThreadParams.Origin origin = MessengerThreadParams.Origin.UNKNOWN;
if (isReply) {
origin = MessengerThreadParams.Origin.REPLY_FLOW;
} else if (isCompose) {
origin = MessengerThreadParams.Origin.COMPOSE_FLOW;
}
return new MessengerThreadParams(
origin,
threadToken,
metadata,
parseParticipants(participants));
} else {
return null;
}
}
/**
* Finishes the activity and returns the media item the user picked to Messenger.
*
* @param activity the activity that received the original intent from Messenger
* @param shareToMessengerParams parameters for what to share
*/
public static void finishShareToMessenger(
Activity activity,
ShareToMessengerParams shareToMessengerParams) {
Intent originalIntent = activity.getIntent();
Set<String> categories = originalIntent.getCategories();
if (categories == null) {
// This shouldn't happen.
activity.setResult(Activity.RESULT_CANCELED, null);
activity.finish();
return;
}
if (categories.contains(ORCA_THREAD_CATEGORY_20150314)) {
Bundle appLinkExtras = AppLinks.getAppLinkExtras(originalIntent);
Intent resultIntent = new Intent();
if (categories.contains(ORCA_THREAD_CATEGORY_20150314)) {
resultIntent.putExtra(EXTRA_PROTOCOL_VERSION, MessengerUtils.PROTOCOL_VERSION_20150314);
String threadToken = appLinkExtras.getString(MessengerUtils.EXTRA_THREAD_TOKEN_KEY);
resultIntent.putExtra(EXTRA_THREAD_TOKEN_KEY, threadToken);
} else {
throw new RuntimeException(); // Can't happen.
}
resultIntent.setDataAndType(shareToMessengerParams.uri, shareToMessengerParams.mimeType);
resultIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
resultIntent.putExtra(EXTRA_APP_ID, FacebookSdk.getApplicationId());
resultIntent.putExtra(EXTRA_METADATA, shareToMessengerParams.metaData);
resultIntent.putExtra(EXTRA_EXTERNAL_URI, shareToMessengerParams.externalUri);
activity.setResult(Activity.RESULT_OK, resultIntent);
activity.finish();
} else {
// This shouldn't happen.
activity.setResult(Activity.RESULT_CANCELED, null);
activity.finish();
}
}
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 boolean isAppLink(String uri) {
try {
Intent intent = Intent.parseUri(uri, 0);
if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(intent.getAction())) {
return true;
}
} catch (Exception e) {}
return false;
}
private static String unwrapIntent(Intent intent) {
Set<String> categories = intent.getCategories();
if (categories == null) return null;
// Get plugin activity class name from categories
Iterator<String> it = categories.iterator();
while (it.hasNext()) {
String category = it.next();
if (category.charAt(0) == REDIRECT_FLAG) {
return category.substring(1);
}
}
return null;
}
private void launchDownloader() {
try {
Intent launchIntent = SampleDownloaderActivity.this
.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(
SampleDownloaderActivity
.this, SampleDownloaderActivity.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);
}
}
if (DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
PendingIntent.getActivity(SampleDownloaderActivity
.this,
0, intentToLaunchThisActivityFromNotification,
PendingIntent.FLAG_UPDATE_CURRENT),
SampleDownloaderService.class) != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
initializeDownloadUI();
return;
} // otherwise we fall through to starting the movie
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Intent.ACTION_MAIN.equals(getIntent().getAction())) {
Intent selector = getIntent().getSelector();
Set<String> categories = selector != null ? selector.getCategories() : getIntent().getCategories();
if(categories.contains(Intent.CATEGORY_APP_CALENDAR))
U.lockDevice(this);
}
finish();
}
/**
* 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;
}
/**
* 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;
}
/**
* Returns true if the app should ignore a given intent.
*
* @param context Android Context.
* @param intent Intent to check.
* @return true if the intent should be ignored.
*/
public boolean shouldIgnoreIntent(Context context, Intent intent) {
// Although not documented to, many/most methods that retrieve values from an Intent may
// throw. Because we can't control what packages might send to us, we should catch any
// Throwable and then fail closed (safe). This is ugly, but resolves top crashers in the
// wild.
try {
// Ignore all invalid URLs, regardless of what the intent was.
if (!intentHasValidUrl(intent)) {
return true;
}
// Determine if this intent came from a trustworthy source (either Chrome or Google
// first party applications).
boolean isInternal = isIntentChromeOrFirstParty(intent, context);
// "Open new incognito tab" is currently limited to Chrome or first parties.
if (!isInternal
&& IntentUtils.safeGetBooleanExtra(
intent, EXTRA_OPEN_NEW_INCOGNITO_TAB, false)) {
return true;
}
// Now if we have an empty URL and the intent was ACTION_MAIN,
// we are pretty sure it is the launcher calling us to show up.
// We can safely ignore the screen state.
String url = getUrlFromIntent(intent);
if (url == null && Intent.ACTION_MAIN.equals(intent.getAction())) {
return false;
}
// Ignore all intents that specify a Chrome internal scheme if they did not come from
// a trustworthy source.
String scheme = getSanitizedUrlScheme(url);
if (!isInternal && scheme != null
&& (intent.hasCategory(Intent.CATEGORY_BROWSABLE)
|| intent.hasCategory(Intent.CATEGORY_DEFAULT)
|| intent.getCategories() == null)) {
String lowerCaseScheme = scheme.toLowerCase(Locale.US);
if ("chrome".equals(lowerCaseScheme) || "chrome-native".equals(lowerCaseScheme)
|| "about".equals(lowerCaseScheme)) {
// Allow certain "safe" internal URLs to be launched by external
// applications.
String lowerCaseUrl = url.toLowerCase(Locale.US);
if ("about:blank".equals(lowerCaseUrl)
|| "about://blank".equals(lowerCaseUrl)) {
return false;
}
Log.w(TAG, "Ignoring internal Chrome URL from untrustworthy source.");
return true;
}
}
// We must check for screen state at this point.
// These might be slow.
boolean internalOrVisible = isInternal || isIntentUserVisible(context);
return !internalOrVisible;
} catch (Throwable t) {
return true;
}
}
@Override
public void onNewIntent(final Intent newIntent) {
Log.i(TAG, "onNewIntent 1 " + newIntent + ", " + newIntent.getBooleanExtra(KEY_INTENT_COMPRESS, false) + ", " + newIntent.getExtras());
this.intent = newIntent;
onNewIntent = new Runnable() {
@Override
public void run() {
final Uri data = newIntent.getData();
final String path = newIntent.getStringExtra(Constants.EXTRA_ABSOLUTE_PATH) == null ? data == null ? null : Uri.decode(data.getPath()) : newIntent.getStringExtra(Constants.EXTRA_ABSOLUTE_PATH);
final String action = newIntent.getAction();
Log.i(TAG, "onNewIntent 2 path " + path + ", " + newIntent + ", " + newIntent.getExtras());
if (path != null) {
final File file = new File(path);
if (file.isDirectory()) {
dir = path;
curContentFrag.suffix = newIntent.getStringExtra(Constants.EXTRA_FILTER_FILETYPE);
curContentFrag.suffix = (curContentFrag.suffix == null) ? "*" : curContentFrag.suffix;
curContentFrag.multiFiles = newIntent.getBooleanExtra(Constants.EXTRA_MULTI_SELECT, true);
curContentFrag.mimes = newIntent.getStringExtra(Constants.EXTRA_FILTER_MIMETYPE);
curContentFrag.mimes = curContentFrag.mimes == null ? "*/*" : curContentFrag.mimes.toLowerCase();
curContentFrag.mWriteableOnly = newIntent.getBooleanExtra(Constants.EXTRA_WRITEABLE_ONLY, false);
curContentFrag.previousSelectedStr = newIntent.getStringArrayExtra(Constants.PREVIOUS_SELECTED_FILES);
curContentFrag.changeDir(path, true);
// slideFrag.addNewTab(path, i.getStringExtra(ExplorerActivity.EXTRA_SUFFIX), i.getBooleanExtra(ExplorerActivity.EXTRA_MULTI_SELECT, true), true);
// slideFrag.setCurrentItem(slideFrag.getCount() - 1);
} else {
if (FileUtil.extractiblePattern.matcher(new File(path).getName()).matches()) {
final SlidingTabsFragment.PagerAdapter pagerAdapter = slideFrag.pagerAdapter;
final int tabIndex2 = slideFrag.getFragIndex(Frag.TYPE.ZIP);
if (tabIndex2 >= 0) {
final ZipFragment zFrag = (ZipFragment) pagerAdapter.getItem(tabIndex2);
zFrag.load(path, null);
slideFrag.setCurrentItem(tabIndex2, true);
} else {
horizontalDivider5.postDelayed(new Runnable() {
@Override
public void run() {
slideFrag.addTab(Frag.TYPE.ZIP, path);
}
}, 200);
}
} else {
getFutils().openFile(file, ExplorerActivity.this);
}
}
} else if (newIntent.getStringArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS) != null) {
ArrayList<BaseFile> failedOps = newIntent.getParcelableArrayListExtra(TAG_INTENT_FILTER_FAILED_OPS);
if (failedOps != null) {
mainActivityHelper.showFailedOperationDialog(failedOps, newIntent.getBooleanExtra("move", false), ExplorerActivity.this);
}
} else if (newIntent.getCategories() != null && newIntent.getCategories().contains(CLOUD_AUTHENTICATOR_GDRIVE)) {
// we used an external authenticator instead of APIs. Probably for Google Drive
CloudRail.setAuthenticationResponse(newIntent);
} else if (decompressFrag != null && newIntent.getBooleanExtra(KEY_INTENT_DECOMPRESS, false)) {
if (!decompressFrag.isAdded()) {
decompressFrag.show(getSupportFragmentManager(), DECOMPRESS);
}
} else if (compressFrag != null && newIntent.getBooleanExtra(KEY_INTENT_COMPRESS, false)) {
if (!compressFrag.isAdded()) {
compressFrag.show(getSupportFragmentManager(), COMPRESS);
}
} else if ((openProcesses = newIntent.getBooleanExtra(KEY_INTENT_PROCESS_VIEWER, false))) {
Fragment findFragmentByTag;
FragmentManager supportFragmentManager = getSupportFragmentManager();
if ((findFragmentByTag = supportFragmentManager.findFragmentByTag(KEY_INTENT_PROCESS_VIEWER)) != null) {
processViewer = (ProcessViewer)findFragmentByTag;
} else {
processViewer = new ProcessViewer();
}
processViewer.show(supportFragmentManager, KEY_INTENT_PROCESS_VIEWER);
// FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.replace(R.id.content_frame, new ProcessViewer(), KEY_INTENT_PROCESS_VIEWER);
// // transaction.addToBackStack(null);
selectedStorage = SELECT_102;
openProcesses = false;
// //title.setText(utils.getString(con, R.string.process_viewer));
// //Commit the transaction
// transaction.commitAllowingStateLoss();
// supportInvalidateOptionsMenu();
} else {
if (SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
if (sharedPref.getString(KEY_PREF_OTG, null) == null) {
sharedPref.edit().putString(KEY_PREF_OTG, VALUE_PREF_OTG_NULL).apply();
refreshDrawer();
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
sharedPref.edit().putString(KEY_PREF_OTG, null).apply();
refreshDrawer();
}
}
}
}
};
}
private void buildResolveList(Intent intent, boolean debug, boolean defaultOnly,
String resolvedType, String scheme, List<F> src, List<R> dest) {
Set<String> categories = intent.getCategories();
final int N = src != null ? src.size() : 0;
boolean hasNonDefaults = false;
int i;
for (i=0; i<N; i++) {
F filter = src.get(i);
int match;
if (debug) Slog.v(TAG, "Matching against filter " + filter);
// Do we already have this one?
if (!allowFilterResult(filter, dest)) {
if (debug) {
Slog.v(TAG, " Filter's target already added");
}
continue;
}
match = filter.match(
intent.getAction(), resolvedType, scheme, intent.getData(), categories, TAG);
if (match >= 0) {
if (debug) Slog.v(TAG, " Filter matched! match=0x" +
Integer.toHexString(match));
if (!defaultOnly || filter.hasCategory(Intent.CATEGORY_DEFAULT)) {
final R oneResult = newResult(filter, match);
if (oneResult != null) {
dest.add(oneResult);
}
} else {
hasNonDefaults = 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;
}
Slog.v(TAG, " Filter did not match: " + reason);
}
}
}
if (dest.size() == 0 && hasNonDefaults) {
Slog.w(TAG, "resolveIntent failed: found match, but none with Intent.CATEGORY_DEFAULT");
}
}
/**
* 根据 Intent 匹配组件
*
* @param context Context
* @param intent 调用方传来的 Intent
* @param filtersMap 插件中声明的所有组件和 IntentFilter
* @return ComponentInfo
*/
public static String doMatchIntent(Context context, Intent intent, Map<String, List<IntentFilter>> filtersMap) {
if (filtersMap == null) {
return null;
}
final String action = intent.getAction();
final String type = intent.resolveTypeIfNeeded(context.getContentResolver());
final Uri data = intent.getData();
final String scheme = intent.getScheme();
final Set<String> categories = intent.getCategories();
for (Map.Entry<String, List<IntentFilter>> entry : filtersMap.entrySet()) {
String pluginName = entry.getKey();
List<IntentFilter> filters = entry.getValue();
if (filters == null) {
continue;
}
for (IntentFilter filter : filters) {
int match = filter.match(action, type, scheme, data, categories, "ComponentList");
if (match >= 0) {
if (LOG) {
LogDebug.d(TAG, "IntentFilter 匹配成功: " + entry.getKey());
}
return pluginName;
} else {
if (LOG) {
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;
}
LogDebug.d(TAG, " Filter did not match: " + reason);
}
}
}
}
return "";
}
private JSONObject buildIntent(
Intent intent
) throws JSONException {
JSONObject jsonIntent = new JSONObject();
jsonIntent.put("action", intent.getAction());
jsonIntent.put("flags", intent.getFlags());
Set<String> categories = intent.getCategories();
if (categories != null) {
jsonIntent.put("categories", new JSONArray(categories));
}
Uri data = intent.getData();
if (data != null) {
jsonIntent.put("data", data.toString());
}
Bundle extras = intent.getExtras();
if (extras != null) {
JSONObject jsonExtras = new JSONObject();
jsonIntent.put("extras", jsonExtras);
Iterator<String> keys = extras.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
Object value = extras.get(key);
if (value instanceof Boolean) {
jsonExtras.put(key, (Boolean)value);
}
else if (value instanceof Integer) {
jsonExtras.put(key, (Integer)value);
}
else if (value instanceof Long) {
jsonExtras.put(key, (Long)value);
}
else if (value instanceof Float) {
jsonExtras.put(key, (Float)value);
}
else if (value instanceof Double) {
jsonExtras.put(key, (Double)value);
}
else {
jsonExtras.put(key, value.toString());
}
}
}
return jsonIntent;
}
/**
* 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;
}