Example usage for android.os Looper getMainLooper

List of usage examples for android.os Looper getMainLooper

Introduction

In this page you can find the example usage for android.os Looper getMainLooper.

Prototype

public static Looper getMainLooper() 

Source Link

Document

Returns the application's main looper, which lives in the main thread of the application.

Usage

From source file:android.bus.EventBus.java

EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new ArrayMap<Class<?>, CopyOnWriteArrayList<Subscription>>();
    typesBySubscriber = new ArrayMap<Object, List<Class<?>>>();
    stickyEvents = new ConcurrentHashMap<Class<?>, Object>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
    backgroundPoster = new BackgroundPoster(this);
    asyncPoster = new AsyncPoster(this);
    subscriberMethodFinder = new SubscriberMethodFinder();

    logSubscriberExceptions = builder.logSubscriberExceptions;
    logNoSubscriberMessages = builder.logNoSubscriberMessages;
    sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
    sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
    throwSubscriberException = builder.throwSubscriberException;
    eventInheritance = builder.eventInheritance;
    executorService = builder.executorService;
}

From source file:com.example.android.bluetoothchat.BluetoothChatFragment2.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/*from   www  .  j  a v  a 2  s.  c o m*/
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = getActivity();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermission();
    }

    mMainHandler = new Handler(Looper.getMainLooper());

}

From source file:com.sspai.dkjt.service.GenerateFrameService.java

@Override
public void doneImage(final Uri imageUri) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override/*from w w  w . j  a  v  a 2  s  .c o m*/
        public void run() {
            bus.post(new Events.SingleImageProcessed(device, imageUri));
        }
    });

    // Create the intent to let the user share the image
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
    Intent chooserIntent = Intent.createChooser(sharingIntent, null);
    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationBuilder.addAction(R.drawable.ic_action_share, getResources().getString(R.string.share),
            PendingIntent.getActivity(this, 0, chooserIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to let the user rate the app
    Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(ConfigString.MARKET_URL));
    notificationBuilder.addAction(R.drawable.ic_action_rate, getResources().getString(R.string.rate),
            PendingIntent.getActivity(this, 0, rateIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to show the screenshot in gallery
    Intent launchIntent = new Intent(Intent.ACTION_VIEW);
    launchIntent.setDataAndType(imageUri, "image/png");
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationBuilder.setContentTitle(resources.getString(R.string.screenshot_saved_title))
            .setContentText(resources.getString(R.string.single_screenshot_saved, device.name()))
            .setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
            .setWhen(System.currentTimeMillis()).setProgress(0, 0, false).setAutoCancel(true);

    notificationManager.notify(DFG_NOTIFICATION_ID, notificationBuilder.build());
}

From source file:cn.edu.gdmec.t00385.lightsensor.LightSensorListener.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action                The action to execute.
 * @param args                 JSONArry of arguments for the plugin.
 * @param callbackS=Context     The callback id used when calling back into JavaScript.
 * @return                     True if the action was valid.
 * @throws JSONException /*from w  ww. j  a  v  a2 s.  c o  m*/
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("start")) {
        this.start();
    } else if (action.equals("stop")) {
        this.stop();
    } else if (action.equals("getStatus")) {
        int i = this.getStatus();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i));
    } else if (action.equals("getLumen")) {
        // If not running, then this is an async call, so don't worry about waiting
        if (this.status != LightSensorListener.RUNNING) {
            int r = this.start();
            if (r == LightSensorListener.ERROR_FAILED_TO_START) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION,
                        LightSensorListener.ERROR_FAILED_TO_START));
                return true;
            }
            // Set a timeout callback on the main thread.
            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(new Runnable() {
                public void run() {
                    LightSensorListener.this.timeout();
                }
            }, 2000);
        }
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getCompassHeading()));
    } else if (action.equals("setTimeout")) {
        this.setTimeout(args.getLong(0));
    } else if (action.equals("getTimeout")) {
        long l = this.getTimeout();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
    } else {
        // Unsupported action
        return false;
    }
    return true;
}

From source file:com.nuvolect.securesuite.data.SqlSyncTest.java

/**
 * Test the network performance between this device and a companion device.
 * CONCEPT://ww w  .  ja  va  2s.  c om
 * A package is constructed of minimal size and sent to the companion device.
 * The companion tests the package for integrity and if successful, creates a larger package and sends it back.
 * The process is continued until communications fail.
 *
 * TODO complete ping pong test.  Show running data rate, success and failure.
 *
 * @param ctx
 * @return
 */
public JSONObject ping_test(final Context ctx) {

    managePayloadSize();

    /**
     * Build the payload and generate MD5
     */
    Map<String, String> params = makeParameters();
    params.put(CConst.CMD, SyncRest.CMD.ping_test.toString());
    params.put(CConst.COUNTER, String.valueOf(++ping_counter));

    String url = WebUtil.getCompanionServerUrl(CConst.SYNC);
    startTime = System.currentTimeMillis();

    Comm.sendPost(ctx, url, params, new Comm.CommPostCallbacks() {
        @Override
        public void success(String response) {

            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.ping_test + " response: " + response);

            if (WebUtil.responseMatch(response, CConst.RESPONSE_CODE_SUCCESS_100)) {

                if (m_pingPongCallbacks != null) {

                    Handler handler = new Handler(Looper.getMainLooper());
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {

                            m_pingPongCallbacks.progressUpdate(m_pingPongCallbacksAct, ping_counter,
                                    pong_counter, payloadSize);

                            if (!m_continueTest)
                                m_pingPongCallbacks.cancelDialog(m_pingPongCallbacksAct);
                        }
                    };
                    handler.post(r);
                }
                /**
                 * To alternate volleys, pong is kicked off by the response sender
                 * versus the machine receiving the response
                 *
                 * if( m_continueTest) WorkerCommand.quePongTest(ctx);
                 */
            }
        }

        @Override
        public void fail(String error) {

            LogUtil.log(LogUtil.LogType.SQL_SYNC_TEST, SyncRest.CMD.ping_test + " error: " + error);
        }
    });
    if (m_continueTest)
        return WebUtil.response(CConst.RESPONSE_CODE_SUCCESS_100);
    else
        return WebUtil.response(CConst.RESPONSE_CODE_USER_CANCEL_102);
}

From source file:com.google.dartino.immisamples.Drawer.java

@Override
public void present(final DrawerNode node) {
    root = node;//from w  w w .  ja v a2s . c om
    presentPane(node.getLeft(), leftPresenter);
    if (centerPresenter != null)
        centerPresenter.present(node.getCenter());
    presentPane(node.getRight(), rightPresenter);
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            setPaneOpenedState(node.getLeftVisible(), leftPresenter);
            setPaneOpenedState(node.getRightVisible(), rightPresenter);
        }
    });
}

From source file:com.google.android.apps.muzei.featuredart.FeaturedArtSource.java

@Override
protected void onCustomCommand(int id) {
    super.onCustomCommand(id);
    if (COMMAND_ID_SHARE == id) {
        Artwork currentArtwork = getCurrentArtwork();
        if (currentArtwork == null) {
            LOGW(TAG, "No current artwork, can't share.");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override/*from  w ww  . j  av  a 2 s  .  co m*/
                public void run() {
                    Toast.makeText(FeaturedArtSource.this,
                            R.string.featuredart_source_error_no_artwork_to_share, Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        String detailUrl = ("initial".equals(currentArtwork.getToken()))
                ? "http://www.wikipaintings.org/en/vincent-van-gogh/the-starry-night-1889"
                : currentArtwork.getViewIntent().getDataString();
        String artist = currentArtwork.getByline().replaceFirst("\\.\\s*($|\\n).*", "").trim();

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "My Android wallpaper today is '"
                + currentArtwork.getTitle().trim() + "' by " + artist + ". #MuzeiFeaturedArt\n\n" + detailUrl);
        shareIntent = Intent.createChooser(shareIntent, "Share artwork");
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(shareIntent);

    } else if (COMMAND_ID_DEBUG_INFO == id) {
        long nextUpdateTimeMillis = getSharedPreferences().getLong("scheduled_update_time_millis", 0);
        final String nextUpdateTime;
        if (nextUpdateTimeMillis > 0) {
            Date d = new Date(nextUpdateTimeMillis);
            nextUpdateTime = SimpleDateFormat.getDateTimeInstance().format(d);
        } else {
            nextUpdateTime = "None";
        }

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(FeaturedArtSource.this, "Next update time: " + nextUpdateTime, Toast.LENGTH_LONG)
                        .show();
            }
        });
    }
}

From source file:com.alexandreroman.nrelay.NmeaRelayService.java

@Override
public void onCreate() {
    super.onCreate();

    uiHandler = new Handler(Looper.getMainLooper()) {
        @Override/*  w w w  . ja  va  2 s  .  co  m*/
        public void handleMessage(Message msg) {
            for (final WeakReference<NmeaRelayListener> listenerRef : listenerRefs) {
                final NmeaRelayListener listener = listenerRef.get();
                if (listener != null) {
                    try {
                        listener.onNmeaRelayContextChanged(context);
                    } catch (Exception e) {
                        Log.w(TAG, "Error in NMEA relay listener: " + listener, e);
                    }
                }
            }
        }
    };

    openMainActivityIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class),
            PendingIntent.FLAG_CANCEL_CURRENT);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    prefs = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
}

From source file:com.connectsdk.discovery.provider.CastDiscoveryProvider.java

private void sendSearch() {
    List<String> killKeys = new ArrayList<String>();

    long killPoint = new Date().getTime() - SSDP_TIMEOUT;

    for (String key : foundServices.keySet()) {
        ServiceDescription service = foundServices.get(key);
        if (service == null || service.getLastDetection() < killPoint) {
            killKeys.add(key);//from  www . j a v a  2  s.  c o  m
        }
    }

    for (String key : killKeys) {
        final ServiceDescription service = foundServices.get(key);

        if (service != null) {
            Util.runOnUI(new Runnable() {

                @Override
                public void run() {
                    for (DiscoveryProviderListener listener : serviceListeners) {
                        listener.onServiceRemoved(CastDiscoveryProvider.this, service);
                    }
                }
            });
        }

        if (foundServices.containsKey(key))
            foundServices.remove(key);
    }

    new Handler(Looper.getMainLooper()).post(new Runnable() {

        @Override
        public void run() {
            mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
                    MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
        }
    });
}