类android.content.IntentFilter源码实例Demo

下面列出了怎么用android.content.IntentFilter的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Shelter   文件: FreezeService.java
@Override
public void onReceive(Context context, Intent intent) {
    // Save usage statistics right now!
    // We need to use the statics at this moment
    // for "skipping foreground apps"
    // No app is foreground after the screen is locked.
    mScreenLockTime = new Date().getTime();
    if (SettingsManager.getInstance().getSkipForegroundEnabled() &&
            Utility.checkUsageStatsPermission(FreezeService.this)) {
        UsageStatsManager usm = getSystemService(UsageStatsManager.class);
        mUsageStats = usm.queryAndAggregateUsageStats(mScreenLockTime - APP_INACTIVE_TIMEOUT, mScreenLockTime);
    }

    // Delay the work so that it can be canceled if the screen
    // gets unlocked before the delay passes
    mHandler.postDelayed(mFreezeWork,
            ((long) SettingsManager.getInstance().getAutoFreezeDelay()) * 1000);
    registerReceiver(mUnlockReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
 
源代码2 项目: Cirrus_depricated   文件: FolderPickerActivity.java
@Override
protected void onResume() {
    super.onResume();
    Log_OC.e(TAG, "onResume() start");

    // refresh list of files
    refreshListOfFilesFragment();

    // Listen for sync messages
    IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
    syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
    syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
    syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
    syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
    mSyncBroadcastReceiver = new SyncBroadcastReceiver();
    registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);

    Log_OC.d(TAG, "onResume() end");
}
 
@Override
protected List<String> getMessageContents() {
    if (!getSharedPreferences().getBoolean(SEND_BATTERY_MESSAGE, false)) {
        HyperLog.d(TAG, "Battery messages disabled, not generating any messages");
        return Collections.emptyList();
    }

    HyperLog.i(TAG, "Scheduling battery message");
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = getApplicationContext().registerReceiver(null, filter);

    if (batteryStatus == null) {
        HyperLog.w(TAG, "No battery status received, unable to generate message");
        return Collections.emptyList();
    }

    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    int batteryPct = (int) (level / (0.01f * scale));

    return Collections.singletonList(Integer.toString(batteryPct));
}
 
源代码4 项目: zen4android   文件: ZenNotificationActivity.java
@Override
protected void onResume() {
	super.onResume();
	try {
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(ZenNotificationModel.ZEN_NEW_NOTIFICATION);
		filter.addAction(ZenNotificationModel.ZEN_NOTIFICATION_EMPTY);
		filter.addAction(ZenNotificationModel.ZEN_LOAD_NOTIFICATION_FAILED);
		registerReceiver(mBroadcastReceiver, filter);
		
		if (ZenUtils.getToken() != null) {
			// loged in
			mLoadingView.show();
			model.load();
		}
		refresh();
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
/**
 * To be called from an Activity or Fragment's onResume method.
 */
public void onResume() {
    Session session = Session.getActiveSession();
    if (session != null) {
        if (callback != null) {
            session.addCallback(callback);
        }
        if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())) {
            session.openForRead(null);
        }
    }

    // add the broadcast receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(Session.ACTION_ACTIVE_SESSION_SET);
    filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET);

    // Add a broadcast receiver to listen to when the active Session
    // is set or unset, and add/remove our callback as appropriate
    broadcastManager.registerReceiver(receiver, filter);
}
 
源代码6 项目: custom-tabs-client   文件: CustomTabsHelper.java
/**
 * Used to check whether there is a specialized handler for a given intent.
 * @param intent The intent to check with.
 * @return Whether there is a specialized handler for the given intent.
 */
private static boolean hasSpecializedHandlerIntents(Context context, Intent intent) {
    try {
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> handlers = pm.queryIntentActivities(
                intent,
                PackageManager.GET_RESOLVED_FILTER);
        if (handlers == null || handlers.size() == 0) {
            return false;
        }
        for (ResolveInfo resolveInfo : handlers) {
            IntentFilter filter = resolveInfo.filter;
            if (filter == null) continue;
            if (filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0) continue;
            if (resolveInfo.activityInfo == null) continue;
            return true;
        }
    } catch (RuntimeException e) {
        Log.e(TAG, "Runtime exception while getting specialized handlers");
    }
    return false;
}
 
源代码7 项目: android-browser-helper   文件: CustomTabsHelper.java
/**
 * Used to check whether there is a specialized handler for a given intent.
 * @param intent The intent to check with.
 * @return Whether there is a specialized handler for the given intent.
 */
private static boolean hasSpecializedHandlerIntents(Context context, Intent intent) {
    try {
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> handlers = pm.queryIntentActivities(
                intent,
                PackageManager.GET_RESOLVED_FILTER);
        if (handlers.size() == 0) {
            return false;
        }
        for (ResolveInfo resolveInfo : handlers) {
            IntentFilter filter = resolveInfo.filter;
            if (filter == null) continue;
            if (filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0) continue;
            if (resolveInfo.activityInfo == null) continue;
            return true;
        }
    } catch (RuntimeException e) {
        Log.e(TAG, "Runtime exception while getting specialized handlers");
    }
    return false;
}
 
@Override
protected void onResume() {
    super.onResume();

    // register GCM registration complete receiver.
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(REGISTRATION_COMPLETE));

    // register new push message receiver.
    // by doing this, the activity will be notified each time a new message arrives
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(PUSH_NOTIFICATION));

    // clear the notification area when the app is opened.
    NotificationUtils.clearNotifications(getApplicationContext());
}
 
源代码9 项目: iBeebo   文件: MentionsCommentTimeLineFragment.java
@Override
    public void onResume() {
        super.onResume();
        setListViewPositionFromPositionsCache();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(newBroadcastReceiver,
                new IntentFilter(AppEventAction.NEW_MSG_BROADCAST));
        // setActionBarTabCount(newMsgTipBar.getValues().size());
        getNewMsgTipBar().setOnChangeListener(new TopTipsView.OnChangeListener() {
            @Override
            public void onChange(int count) {
//                ((MainTimeLineActivity) getActivity()).setMentionsCommentCount(count);
                // setActionBarTabCount(count);
            }
        });
        checkUnreadInfo();
    }
 
源代码10 项目: AppTroy   文件: ActivityHook.java
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
    Log.d("cc", "before, register receiver");
    if (NEED_DEBUG) {
        Activity activity = (Activity) param.thisObject;
        Log.d(LOG_TAG, activity.toString());
    }
    if (!ModuleContext.HAS_REGISTER_LISENER) {
        Activity app = (Activity) param.thisObject;
        IntentFilter filter = new IntentFilter(CommandBroadcastReceiver.INTENT_ACTION);
        app.registerReceiver(new CommandBroadcastReceiver(), filter);
        ModuleContext.HAS_REGISTER_LISENER = true;
        ModuleContext.getInstance().setFirstApplication(app.getApplication());
        Log.d("cc", "register over");
    }
}
 
源代码11 项目: Trigger   文件: TriggerLoop.java
@Override
public void onCreate() {
    super.onCreate();
    jobSet = new ConcurrentHashMap<>();
    receivers = new ConcurrentHashMap<>();
    jobHappens = new ConcurrentHashMap<>();
    binder = new TriggerBinder();
    executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new TriggerWorkerFactory());
    mainHandler = new Handler(Looper.getMainLooper());
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    shortDeadlineHandler = new Handler();
    deadlineCheck = new DeadlineCheck();
    sDeviceStatus = DeviceStatus.get(this);
    registerReceiver(deadlineCheck, new IntentFilter(DEADLINE_BROADCAST));
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    int granted = checkCallingOrSelfPermission("android.permission.WAKE_LOCK");
    if (granted == PackageManager.PERMISSION_GRANTED) {
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    } else {
        wakeLock = null;
    }
    handlerThread = new HandlerThread("Trigger-HandlerThread");
    handlerThread.start();
    checker = new CheckHandler(handlerThread.getLooper());
    mayRecoverJobsFromFile();
}
 
源代码12 项目: TwistyTimer   文件: TTIntent.java
/**
 * Registers a broadcast receiver. The receiver will only be notified of intents that require
 * the category given and only for the actions that are supported for that category. If the
 * receiver is used by a fragment, create an instance of {@link TTFragmentBroadcastReceiver}
 * and register it with the {@link #registerReceiver(TTFragmentBroadcastReceiver)} method
 * instead, as it will be easier to maintain.
 *
 * @param receiver
 *     The broadcast receiver to be registered.
 * @param category
 *     The category for the actions to be received. Must not be {@code null} and must be a
 *     supported category.
 *
 * @throws IllegalArgumentException
 *     If the category is {@code null}, or is not one of the supported categories.
 */
public static void registerReceiver(BroadcastReceiver receiver, String category) {
    final String[] actions = ACTIONS_SUPPORTED_BY_CATEGORY.get(category);

    if (category == null || actions.length == 0) {
        throw new IllegalArgumentException("Category is not supported: " + category);
    }

    final IntentFilter filter = new IntentFilter();

    filter.addCategory(category);

    for (String action : actions) {
        // IntentFilter will only match Intents with one of these actions.
        filter.addAction(action);
    }

    LocalBroadcastManager.getInstance(TwistyTimer.getAppContext())
            .registerReceiver(receiver, filter);
}
 
源代码13 项目: habpanelviewer   文件: ServerConnection.java
public ServerConnection(Context context) {
    mCertListener = () -> {
        Log.d(TAG, "cert added, reconnecting to server...");

        if (mSseConnection.getStatus() == SseConnection.Status.CERTIFICATE_ERROR) {
            mSseConnection.connect();
        }
    };

    mSseConnection.addListener(new SseConnectionListener());
    mSseConnection.addItemValueListener(new SseStateUpdateListener());

    CertificateManager.getInstance().addCertListener(mCertListener);
    CredentialManager.getInstance().addCredentialsListener(mSseConnection);

    IntentFilter f = new IntentFilter();
    f.addAction(Constants.INTENT_ACTION_SET_WITH_TIMEOUT);

    LocalBroadcastManager.getInstance(context).registerReceiver(mReceiver, f);
}
 
源代码14 项目: container   文件: IntentResolver.java
private ArrayList<F> collectFilters(F[] array, IntentFilter matching) {
	ArrayList<F> res = null;
	if (array != null) {
		for (int i = 0; i < array.length; i++) {
			F cur = array[i];
			if (cur == null) {
				break;
			}
			if (filterEquals(cur, matching)) {
				if (res == null) {
					res = new ArrayList<>();
				}
				res.add(cur);
			}
		}
	}
	return res;
}
 
源代码15 项目: slide-android   文件: SystemSettings.java
public boolean isUsbConnected(final Activity a)
{
    final Intent intent = a.registerReceiver(
        null, new IntentFilter(
            "android.hardware.usb.action.USB_STATE")
    );
    return intent != null && intent.getExtras().getBoolean("connected");
}
 
源代码16 项目: oversec   文件: App.java
@Override
public void onCreate() {

    int pid = Process.myPid();
    ActivityManager manager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    String currentProcName = null;
    for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
        if (processInfo.pid == pid) {
            currentProcName = processInfo.processName;
            break;
        }
    }

    if (currentProcName.endsWith("zxcvbn")) {
        super.onCreate();
        return;
    }

    CrashHandler.init(this);

    LoggingConfig.INSTANCE.init(BuildConfig.DEBUG);

    super.onCreate();

    if (IabUtil.isGooglePlayInstalled(this)) {
        RateThisApp.Config config = new RateThisApp.Config(7, 30);
        RateThisApp.init(config);
    }

    //need to register from code, registering from manifest is ignored
    IntentFilter packageChangeFilter = new IntentFilter();
    packageChangeFilter.addAction("android.intent.action.PACKAGE_ADDED");
    packageChangeFilter.addAction("android.intent.action.PACKAGE_REMOVED");
    packageChangeFilter.addAction("android.intent.action.PACKAGE_CHANGED");
    packageChangeFilter.addDataScheme("package");
    registerReceiver(new AppsReceiver(), packageChangeFilter);

    IabUtil.getInstance(this);
    Core.getInstance(this);
}
 
源代码17 项目: a   文件: ReadAloudService.java
private void initBroadcastReceiver() {
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
                pauseReadAloud(true);
            }
        }
    };
    IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    registerReceiver(broadcastReceiver, intentFilter);
}
 
源代码18 项目: Bolts-Android   文件: AppLinkTest.java
public void testGeneralMeasurementEventsBroadcast() throws Exception {
  Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
  i.putExtra("foo", "bar");
  ArrayList<String> arr = new ArrayList<>();
  arr.add("foo2");
  arr.add("bar2");
  i.putExtra("foobar", arr);
  Map<String, String> other = new HashMap<>();
  other.put("yetAnotherFoo", "yetAnotherBar");

  final CountDownLatch lock = new CountDownLatch(1);
  final String[] receivedStrings = new String[5];
  LocalBroadcastManager manager = LocalBroadcastManager.getInstance(instrumentation.getTargetContext());
  manager.registerReceiver(
      new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          String eventName = intent.getStringExtra("event_name");
          Bundle eventArgs = intent.getBundleExtra("event_args");
          receivedStrings[0] = eventName;
          receivedStrings[1] = eventArgs.getString("foo");
          receivedStrings[2] = eventArgs.getString("foobar");
          receivedStrings[3] = eventArgs.getString("yetAnotherFoo");
          receivedStrings[4] = eventArgs.getString("intentData");
          lock.countDown();
        }
      },
      new IntentFilter("com.parse.bolts.measurement_event")
  );

  MeasurementEvent.sendBroadcastEvent(instrumentation.getTargetContext(), "myEventName", i, other);
  lock.await(20000, TimeUnit.MILLISECONDS);

  assertEquals("myEventName", receivedStrings[0]);
  assertEquals("bar", receivedStrings[1]);
  assertEquals((new JSONArray(arr)).toString(), receivedStrings[2]);
  assertEquals("yetAnotherBar", receivedStrings[3]);
  assertEquals("http://www.example.com", receivedStrings[4]);
}
 
public synchronized void onResume() {
	if (registered) {
		Log.w(TAG, "PowerStatusReceiver was already registered?");
	} else {
		activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
		registered = true;
	}
	onActivity();
}
 
源代码20 项目: wearable   文件: BatmanWatchFaceService.java
private void registerReceiver() {
    if (mRegisteredTimeZoneReceiver) {
        return;
    }
    mRegisteredTimeZoneReceiver = true;
    IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
    BatmanWatchFaceService.this.registerReceiver(mTimeZoneReceiver, filter);
}
 
源代码21 项目: Camera-Roll-Android-App   文件: AlbumActivity.java
@Override
public IntentFilter getBroadcastIntentFilter() {
    IntentFilter filter = FileOperation.Util.getIntentFilter(super.getBroadcastIntentFilter());
    filter.addAction(ALBUM_ITEM_REMOVED);
    filter.addAction(ALBUM_ITEM_RENAMED);
    filter.addAction(DATA_CHANGED);
    return filter;
}
 
源代码22 项目: bither-android   文件: BlockchainService.java
private synchronized void startPeer() {
    try {
        if (peerCanNotRun) {
            return;
        }
        if (UpgradeUtil.needUpgrade()) {
            return;
        }
        if (!AppSharedPreference.getInstance().getDownloadSpvFinish()) {
            Block block = BlockUtil.dowloadSpvBlock();
            if (block == null) {
                return;
            }
        }
        if (AppSharedPreference.getInstance().getAppMode() != BitherjSettings.AppMode.COLD) {
            if (!AppSharedPreference.getInstance().getBitherjDoneSyncFromSpv()) {
                if (!PeerManager.instance().isConnected()) {
                    PeerManager.instance().start();
                    if (!spvFinishedReceivered) {
                        final IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(NotificationAndroidImpl.ACTION_SYNC_FROM_SPV_FINISHED);
                        spvFinishedReceiver = new SPVFinishedReceiver();
                        registerReceiver(spvFinishedReceiver, intentFilter);
                        spvFinishedReceivered = true;
                    }
                }
            } else {
                if (!AddressManager.getInstance().addressIsSyncComplete()) {
                    TransactionsUtil.getMyTxFromBither();
                }
                startPeerManager();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
源代码23 项目: NightWatch   文件: ShareGlucose.java
public int getBatteryLevel() {
    Intent batteryIntent = mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if(level == -1 || scale == -1) {
        return 50;
    }
    return (int)(((float)level / (float)scale) * 100.0f);
}
 
源代码24 项目: xDrip   文件: PowerStateReceiver.java
@SuppressWarnings("ConstantConditions")
public static int getBatteryLevel(Context context) {
    final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    try {
        int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        if (level == -1 || scale == -1) {
            return 50;
        }
        return (int) (((float) level / (float) scale) * 100.0f);
    } catch (NullPointerException e) {
        return 50;
    }
}
 
源代码25 项目: YCVideoPlayer   文件: FloatLifecycle.java
FloatLifecycle(Context applicationContext, boolean showFlag, Class[] activities, LifecycleListener lifecycleListener) {
    this.showFlag = showFlag;
    this.activities = activities;
    mLifecycleListener = lifecycleListener;
    mHandler = new Handler();
    ((Application) applicationContext).registerActivityLifecycleCallbacks(this);
    applicationContext.registerReceiver(this, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
 
源代码26 项目: android-openslmediaplayer   文件: AppEventBus.java
private static IntentFilter createIntentFilter(Receiver<?> receiver) {
    int[] categories = receiver.getCategoryFilter();
    IntentFilter filter = new IntentFilter();

    if (categories != null) {
        for (int category : categories) {
            filter.addAction(categoryToActionName(category));
        }
    }

    return filter;
}
 
@Override
protected void provide() {
    BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();               // Set up the adaptor
    if (BTAdapter == null || !BTAdapter.isEnabled()) {
        this.finish();
        return;
    }
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(android.bluetooth.BluetoothDevice.ACTION_FOUND);
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    getContext().registerReceiver(mReceiver, intentFilter);
    BTAdapter.startDiscovery();
}
 
源代码28 项目: Taskbar   文件: StartMenuLayoutTest.java
@Test
public void testDispatchKeyEvent() {
    IntentFilter filter = new IntentFilter(ACTION_HIDE_START_MENU);
    TestBroadcastReceiver receiver = new TestBroadcastReceiver();
    LocalBroadcastManager.getInstance(context).registerReceiver(receiver, filter);
    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
    layout.dispatchKeyEvent(keyEvent);
    assertFalse(receiver.onReceived);
    layout.viewHandlesBackButton();
    layout.dispatchKeyEvent(keyEvent);
    assertTrue(receiver.onReceived);
}
 
源代码29 项目: Meshenger   文件: ContactListActivity.java
@Override
protected void onResume() {
    super.onResume();

    LocalBroadcastManager.getInstance(this).registerReceiver(refreshReceiver, new IntentFilter("contact_refresh"));

    bindService(new Intent(this, MainService.class), this, Service.BIND_AUTO_CREATE);
}
 
源代码30 项目: android_9.0.0_r45   文件: Watchdog.java
public void init(Context context, ActivityManagerService activity) {
    mResolver = context.getContentResolver();
    mActivity = activity;

    context.registerReceiver(new RebootRequestReceiver(),
            new IntentFilter(Intent.ACTION_REBOOT),
            android.Manifest.permission.REBOOT, null);
}
 
 类所在包
 同包方法