Search in sources :

Example 11 with Messenger

use of android.os.Messenger in project platform_frameworks_base by android.

the class SettingInjectorService method sendStatus.

/**
     * Send the enabled values back to the caller via the messenger encoded in the
     * intent.
     */
private void sendStatus(Intent intent, boolean enabled) {
    Message message = Message.obtain();
    Bundle bundle = new Bundle();
    bundle.putBoolean(ENABLED_KEY, enabled);
    message.setData(bundle);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, mName + ": received " + intent + ", enabled=" + enabled + ", sending message: " + message);
    }
    Messenger messenger = intent.getParcelableExtra(MESSENGER_KEY);
    try {
        messenger.send(message);
    } catch (RemoteException e) {
        Log.e(TAG, mName + ": sending dynamic status failed", e);
    }
}
Also used : Message(android.os.Message) Bundle(android.os.Bundle) Messenger(android.os.Messenger) RemoteException(android.os.RemoteException)

Example 12 with Messenger

use of android.os.Messenger in project platform_frameworks_base by android.

the class NetworkStatsManager method registerUsageCallback.

/**
     * Registers to receive notifications about data usage on specified networks.
     *
     * <p>The callbacks will continue to be called as long as the process is live or
     * {@link #unregisterUsageCallback} is called.
     *
     * @param networkType Type of network to monitor. Either
                  {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}.
     * @param subscriberId If applicable, the subscriber id of the network interface.
     * @param thresholdBytes Threshold in bytes to be notified on.
     * @param callback The {@link UsageCallback} that the system will call when data usage
     *            has exceeded the specified threshold.
     * @param handler to dispatch callback events through, otherwise if {@code null} it uses
     *            the calling thread.
     */
public void registerUsageCallback(int networkType, String subscriberId, long thresholdBytes, UsageCallback callback, @Nullable Handler handler) {
    checkNotNull(callback, "UsageCallback cannot be null");
    final Looper looper;
    if (handler == null) {
        looper = Looper.myLooper();
    } else {
        looper = handler.getLooper();
    }
    if (DBG) {
        Log.d(TAG, "registerUsageCallback called with: {" + " networkType=" + networkType + " subscriberId=" + subscriberId + " thresholdBytes=" + thresholdBytes + " }");
    }
    NetworkTemplate template = createTemplate(networkType, subscriberId);
    DataUsageRequest request = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, template, thresholdBytes);
    try {
        CallbackHandler callbackHandler = new CallbackHandler(looper, networkType, subscriberId, callback);
        callback.request = mService.registerUsageCallback(mContext.getOpPackageName(), request, new Messenger(callbackHandler), new Binder());
        if (DBG)
            Log.d(TAG, "registerUsageCallback returned " + callback.request);
        if (callback.request == null) {
            Log.e(TAG, "Request from callback is null; should not happen");
        }
    } catch (RemoteException e) {
        if (DBG)
            Log.d(TAG, "Remote exception when registering callback");
        throw e.rethrowFromSystemServer();
    }
}
Also used : Looper(android.os.Looper) DataUsageRequest(android.net.DataUsageRequest) Binder(android.os.Binder) NetworkTemplate(android.net.NetworkTemplate) Messenger(android.os.Messenger) RemoteException(android.os.RemoteException)

Example 13 with Messenger

use of android.os.Messenger in project platform_frameworks_base by android.

the class NsdManager method init.

/**
     * Initialize AsyncChannel
     */
private void init() {
    final Messenger messenger = getMessenger();
    if (messenger == null)
        throw new RuntimeException("Failed to initialize");
    HandlerThread t = new HandlerThread("NsdManager");
    t.start();
    mHandler = new ServiceHandler(t.getLooper());
    mAsyncChannel.connect(mContext, mHandler, messenger);
    try {
        mConnected.await();
    } catch (InterruptedException e) {
        Log.e(TAG, "interrupted wait at init");
    }
}
Also used : HandlerThread(android.os.HandlerThread) Messenger(android.os.Messenger)

Example 14 with Messenger

use of android.os.Messenger in project platform_frameworks_base by android.

the class NetworkStatsServiceTest method testRegisterUsageCallback.

@Test
public void testRegisterUsageCallback() throws Exception {
    // pretend that wifi network comes online; service should ask about full
    // network state, and poll any existing interfaces before updating.
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkState(buildWifiState());
    expectNetworkStatsSummary(buildEmptyStats());
    expectNetworkStatsUidDetail(buildEmptyStats());
    expectBandwidthControlCheck();
    mService.forceUpdateIfaces();
    // verify service has empty history for wifi
    assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    String callingPackage = "the.calling.package";
    // very small; should be overriden by framework
    long thresholdInBytes = 1L;
    DataUsageRequest inputRequest = new DataUsageRequest(DataUsageRequest.REQUEST_ID_UNSET, sTemplateWifi, thresholdInBytes);
    // Create a messenger that waits for callback activity
    ConditionVariable cv = new ConditionVariable(false);
    LatchedHandler latchedHandler = new LatchedHandler(Looper.getMainLooper(), cv);
    Messenger messenger = new Messenger(latchedHandler);
    // Force poll
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsSummary(buildEmptyStats());
    expectNetworkStatsUidDetail(buildEmptyStats());
    // Register and verify request and that binder was called
    DataUsageRequest request = mService.registerUsageCallback(callingPackage, inputRequest, messenger, mBinder);
    assertTrue(request.requestId > 0);
    assertTrue(Objects.equals(sTemplateWifi, request.template));
    // 2 MB
    long minThresholdInBytes = 2 * 1024 * 1024;
    assertEquals(minThresholdInBytes, request.thresholdInBytes);
    // Send dummy message to make sure that any previous message has been handled
    mHandler.sendMessage(mHandler.obtainMessage(-1));
    mHandlerThread.waitForIdle(WAIT_TIMEOUT);
    // Make sure that the caller binder gets connected
    verify(mBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
    // modify some number on wifi, and trigger poll event
    // not enough traffic to call data usage callback
    incrementCurrentTime(HOUR_IN_MILLIS);
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 1024L, 1L, 2048L, 2L));
    expectNetworkStatsUidDetail(buildEmptyStats());
    forcePollAndWaitForIdle();
    // verify service recorded history
    assertNetworkTotal(sTemplateWifi, 1024L, 1L, 2048L, 2L, 0);
    // make sure callback has not being called
    assertEquals(INVALID_TYPE, latchedHandler.mLastMessageType);
    // and bump forward again, with counters going higher. this is
    // important, since it will trigger the data usage callback
    incrementCurrentTime(DAY_IN_MILLIS);
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsSummary(new NetworkStats(getElapsedRealtime(), 1).addIfaceValues(TEST_IFACE, 4096000L, 4L, 8192000L, 8L));
    expectNetworkStatsUidDetail(buildEmptyStats());
    forcePollAndWaitForIdle();
    // verify service recorded history
    assertNetworkTotal(sTemplateWifi, 4096000L, 4L, 8192000L, 8L, 0);
    // Wait for the caller to ack receipt of CALLBACK_LIMIT_REACHED
    assertTrue(cv.block(WAIT_TIMEOUT));
    assertEquals(NetworkStatsManager.CALLBACK_LIMIT_REACHED, latchedHandler.mLastMessageType);
    cv.close();
    // Allow binder to disconnect
    when(mBinder.unlinkToDeath(any(IBinder.DeathRecipient.class), anyInt())).thenReturn(true);
    // Unregister request
    mService.unregisterUsageRequest(request);
    // Wait for the caller to ack receipt of CALLBACK_RELEASED
    assertTrue(cv.block(WAIT_TIMEOUT));
    assertEquals(NetworkStatsManager.CALLBACK_RELEASED, latchedHandler.mLastMessageType);
    // Make sure that the caller binder gets disconnected
    verify(mBinder).unlinkToDeath(any(IBinder.DeathRecipient.class), anyInt());
}
Also used : ConditionVariable(android.os.ConditionVariable) DataUsageRequest(android.net.DataUsageRequest) NetworkStats(android.net.NetworkStats) Messenger(android.os.Messenger) Test(org.junit.Test)

Example 15 with Messenger

use of android.os.Messenger in project platform_frameworks_base by android.

the class PhoneWindowManager method takeScreenshot.

// Assume this is called from the Handler thread.
private void takeScreenshot(final int screenshotType) {
    synchronized (mScreenshotLock) {
        if (mScreenshotConnection != null) {
            return;
        }
        final ComponentName serviceComponent = new ComponentName(SYSUI_PACKAGE, SYSUI_SCREENSHOT_SERVICE);
        final Intent serviceIntent = new Intent();
        serviceIntent.setComponent(serviceComponent);
        ServiceConnection conn = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                synchronized (mScreenshotLock) {
                    if (mScreenshotConnection != this) {
                        return;
                    }
                    Messenger messenger = new Messenger(service);
                    Message msg = Message.obtain(null, screenshotType);
                    final ServiceConnection myConn = this;
                    Handler h = new Handler(mHandler.getLooper()) {

                        @Override
                        public void handleMessage(Message msg) {
                            synchronized (mScreenshotLock) {
                                if (mScreenshotConnection == myConn) {
                                    mContext.unbindService(mScreenshotConnection);
                                    mScreenshotConnection = null;
                                    mHandler.removeCallbacks(mScreenshotTimeout);
                                }
                            }
                        }
                    };
                    msg.replyTo = new Messenger(h);
                    msg.arg1 = msg.arg2 = 0;
                    if (mStatusBar != null && mStatusBar.isVisibleLw())
                        msg.arg1 = 1;
                    if (mNavigationBar != null && mNavigationBar.isVisibleLw())
                        msg.arg2 = 1;
                    try {
                        messenger.send(msg);
                    } catch (RemoteException e) {
                    }
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                synchronized (mScreenshotLock) {
                    if (mScreenshotConnection != null) {
                        mContext.unbindService(mScreenshotConnection);
                        mScreenshotConnection = null;
                        mHandler.removeCallbacks(mScreenshotTimeout);
                        notifyScreenshotError();
                    }
                }
            }
        };
        if (mContext.bindServiceAsUser(serviceIntent, conn, Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE, UserHandle.CURRENT)) {
            mScreenshotConnection = conn;
            mHandler.postDelayed(mScreenshotTimeout, 10000);
        }
    }
}
Also used : ServiceConnection(android.content.ServiceConnection) IBinder(android.os.IBinder) Message(android.os.Message) Handler(android.os.Handler) ComponentName(android.content.ComponentName) Intent(android.content.Intent) RecognizerIntent(android.speech.RecognizerIntent) Messenger(android.os.Messenger) RemoteException(android.os.RemoteException)

Aggregations

Messenger (android.os.Messenger)108 RemoteException (android.os.RemoteException)44 Message (android.os.Message)42 Intent (android.content.Intent)38 Handler (android.os.Handler)27 ComponentName (android.content.ComponentName)23 IBinder (android.os.IBinder)23 ServiceConnection (android.content.ServiceConnection)19 DataUsageRequest (android.net.DataUsageRequest)9 Looper (android.os.Looper)9 ConditionVariable (android.os.ConditionVariable)8 AsyncChannel (com.android.internal.util.AsyncChannel)8 PendingIntent (android.app.PendingIntent)7 Bundle (android.os.Bundle)7 HandlerThread (android.os.HandlerThread)7 Binder (android.os.Binder)6 File (java.io.File)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 NetworkTemplate (android.net.NetworkTemplate)5 RecognizerIntent (android.speech.RecognizerIntent)5