Example usage for android.os Looper myLooper

List of usage examples for android.os Looper myLooper

Introduction

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

Prototype

public static @Nullable Looper myLooper() 

Source Link

Document

Return the Looper object associated with the current thread.

Usage

From source file:cn.edu.zzu.wemall.http.AsyncHttpResponseHandler.java

/**
 * Creates a new AsyncHttpResponseHandler
 *///from  www  . j av a  2  s  . c o  m
public AsyncHttpResponseHandler() {
    // Set up a handler to post events back to the correct thread if possible
    if (Looper.myLooper() != null) {
        handler = new ResponderHandler(this);
    }
}

From source file:com.mta.sharedutils.Util.java

/**
 * This is//  w  w w  .j  a  va2 s .  com
 *
 * @return
 */
public static @THREAD_TYPE int getThreadType() {
    return Looper.myLooper().equals(Looper.getMainLooper()) ? TH_UI : TH_WORKER;
}

From source file:org.traccar.client.ShortcutActivity.java

@SuppressWarnings("MissingPermission")
private void sendAlarm() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    String provider = PositionProvider.getProvider(preferences.getString(MainFragment.KEY_ACCURACY, "medium"));

    try {//from w w  w .j  a va2 s.c  o m
        Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        if (location != null) {
            sendAlarmLocation(location);
        } else {
            locationManager.requestSingleUpdate(provider, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    sendAlarmLocation(location);
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            }, Looper.myLooper());
        }
    } catch (RuntimeException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:cn.com.loopj.android.http.AsyncHttpResponseHandler.java

/**
 * Creates a new AsyncHttpResponseHandler and decide whether the callbacks
 * will be fired on current thread's looper or the pool thread's.
 *
 * @param usePoolThread Whether to use the pool's thread to fire callbacks
 *///w ww .j  a  v a  2  s .c o m
public AsyncHttpResponseHandler(boolean usePoolThread) {
    // Whether to use the pool's thread to fire callbacks.
    setUsePoolThread(usePoolThread);

    // When using the pool's thread, there's no sense in having a looper.
    if (!getUsePoolThread()) {
        // Use the current thread's looper.
        this.looper = Looper.myLooper();

        // Use asynchronous mode by default.
        setUseSynchronousMode(false);
    }
}

From source file:com.precisosol.llgeofence.GeofencePlugin.java

@Override
public PluginResult execute(String action, JSONArray data, String callback) {
    Looper.myLooper().prepare();
    PluginResult result = null;// w  w w .  j  ava  2s .  c o m
    if (action.equalsIgnoreCase(INITIALIZE_SERVICE)) {
        try {

            receiver = new GeofenceReceiver();
            ctx.registerReceiver(receiver, new IntentFilter(GEOFENCE_FIRED));
            ctx.registerReceiver(receiver, new IntentFilter(AUTH_SUCCESS));
            ctx.registerReceiver(receiver, new IntentFilter(AUTH_FAILURE));
            // create our ServiceConnection
            serviceConnection = new ServiceConnection() {

                public void onServiceConnected(ComponentName name, IBinder service) {
                    mService = ((GeofenceService.ServiceBinder) service).getService();
                    mService.setConsumerKeyAndSecret(CONSUMER_KEY, CONSUMER_SECRET);
                    mService.setAuthorizationActions(AUTH_SUCCESS, AUTH_FAILURE, GeofenceReceiver.class);
                    mService.authorize();
                    mService.enable();

                }

                public void onServiceDisconnected(ComponentName name) {
                    // geofences still persist
                    mService = null;
                }

            };

            if (!(ctx.bindService(new Intent(ctx, GeofenceService.class), serviceConnection,
                    Context.BIND_AUTO_CREATE))) {
                Log.w(LOG, "Failed to bind to GeofenceService");
            }

            result = new PluginResult(PluginResult.Status.OK, "Service start signal sent.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }

    } else if (action.equalsIgnoreCase(CREATE_GEOFENCE)) {

        try {
            int externalIdentifier = data.getInt(0); //identifier to identify the related object internally
            double latitude = data.getDouble(1);
            double longitude = data.getDouble(2);
            float radius = (float) data.getDouble(3);
            int crossingType = data.getInt(4);
            Geofence g = AddGeofence(latitude, longitude, radius, crossingType);
            org.yajl.JSONObject tmp = new org.yajl.JSONObject(g);
            tmp.append("EID", externalIdentifier);
            String str = tmp.toString();
            tmp = null;
            Log.d("Service_Output", str);
            JSONObject resultobject = new JSONObject(str);
            str = null;
            result = new PluginResult(PluginResult.Status.OK, resultobject);

        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }

    } else if (action.equalsIgnoreCase(DELETE_GEOFENCE)) {
        try {
            long id = data.getLong(0);
            DeleteGeofence(id);
            result = new PluginResult(PluginResult.Status.OK, "Geofence deleted successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }

    } else if (action.equalsIgnoreCase(DELETE_ALL_GEOFENCES)) {
        try {
            DeleteAllGeofences();
            result = new PluginResult(PluginResult.Status.OK, "Geofences deleted successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(FIND_GEOFENCE)) {
        try {
            long id = data.getLong(0);
            Geofence g = FindGeofence(id);
            org.yajl.JSONObject tmp = new org.yajl.JSONObject(g);
            String str = tmp.toString();
            tmp = null;
            Log.d("Service_Output", str);
            JSONObject resultobject = new JSONObject(str);
            str = null;
            result = new PluginResult(PluginResult.Status.OK, resultobject);
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(GET_ALL_GEOFENCES)) {
        try {
            ArrayList<Geofence> geofences = GetAllGeofences();
            org.yajl.JSONArray tmp = new org.yajl.JSONArray(geofences);
            String str = tmp.toString();
            tmp = null;
            Log.d("Service_Output", str);
            JSONArray resultobject = new JSONArray(str);
            str = null;
            result = new PluginResult(PluginResult.Status.OK, resultobject);

        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(GET_CURRENT_LOCATION)) {
        try {
            if (mService != null) {
                Thread.sleep(5000);
                Location loc = location;
                org.yajl.JSONObject obj = new org.yajl.JSONObject(loc);
                JSONObject resultobject = new JSONObject(obj.toString());
                result = new PluginResult(PluginResult.Status.OK, resultobject);
            } else {
                result = new PluginResult(PluginResult.Status.ERROR, "Service not running.");
            }
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(GET_LAST_KNOWN_LOCATION)) {
        try {
            if (mService != null) {
                Location loc = mService.getLastKnownLocation();
                org.yajl.JSONObject obj = new org.yajl.JSONObject(loc);
                JSONObject resultobject = new JSONObject(obj.toString());
                result = new PluginResult(PluginResult.Status.OK, resultobject);
            }
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(SET_CALLBACKS)) {
        try {
            AUTH_SUCCESS_CALLBACK = data.getString(0);
            AUTH_FAILURE_CALLBACK = data.getString(1);
            GEOFENCE_ENTRY_CALLBACK = data.getString(2);
            GEOFENCE_EXIT_CALLBACK = data.getString(3);
            SERVICE_FAILURE_CALLBACK = data.getString(4);
            result = new PluginResult(Status.OK, "Callbacks setup Successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(ENABLE)) {
        try {
            mService.enable();
            result = new PluginResult(Status.OK, "Service Enabled Successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    } else if (action.equalsIgnoreCase(DISABLE)) {
        try {
            mService.disable();
            result = new PluginResult(Status.OK, "Service Disabled Successfully.");
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR, e.getMessage());
        }
    }

    return result;
}

From source file:com.example.administrator.newsdaily.model.httpclient.AsyncHttpResponseHandler.java

/**
 * Creates a new AsyncHttpResponseHandler
 *//*from  w w  w. j av  a 2s.co m*/
public AsyncHttpResponseHandler() {
    boolean missingLooper = null == Looper.myLooper();
    // Try to create handler
    if (!missingLooper)
        handler = new ResponderHandler(this);
    else {
        // There is no Looper on this thread so synchronous mode should be used.
        handler = null;
        setUseSynchronousMode(true);
        Log.i(LOG_TAG, "Current thread has not called Looper.prepare(). Forcing synchronous mode.");
    }

    // Init Looper by calling postRunnable without an argument.
    postRunnable(null);
}

From source file:com.android.yijiang.kzx.http.AsyncHttpResponseHandler.java

@Override
public void setUseSynchronousMode(boolean value) {
    // A looper must be prepared before setting asynchronous mode.
    if (!value && Looper.myLooper() == null) {
        value = true;//from   www . j  av  a 2 s . com
        Log.w(LOG_TAG, "Current thread has not called Looper.prepare(). Forcing synchronous mode.");
    }

    // If using asynchronous mode.
    if (!value && handler == null) {
        // Create a handler on current thread to submit tasks
        handler = new ResponderHandler(this);
    } else if (value && handler != null) {
        // TODO: Consider adding a flag to remove all queued messages.
        handler = null;
    }

    useSynchronousMode = value;
}

From source file:io.jxcore.node.jxcore.java

public static boolean CallJSMethod(String id, String json) {
    if (jxcore.coreThread == null) {
        Log.e(LOGTAG, "JXcore wasn't initialized yet");
        return false;
    }/*w  w w .ja  v a2s  .com*/

    if (Looper.myLooper() != coreThread.handler.getLooper()) {
        coreThread.handler.post(new CoreRunnable(id, json) {
            @Override
            public void run() {
                callJSMethod(callback_id_, str_param_);
            }
        });
    } else {
        callJSMethod(id, json);
    }

    return true;
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void getAnUser(View view) {
    RxAndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_OBJECT).addPathParameter("userId", "1")
            .setUserAgent("getAnUser").build().setAnalyticsListener(new AnalyticsListener() {
                @Override/*  w  w  w.  j a  v  a2  s. c om*/
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived,
                        boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            }).getParseObservable(new TypeToken<User>() {
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<User>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : getAnUser completed");
                }

                @Override
                public void onError(Throwable e) {
                    Utils.logError(TAG, e);
                }

                @Override
                public void onNext(User user) {
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                    Log.d(TAG, "id : " + user.id);
                    Log.d(TAG, "firstname : " + user.firstname);
                    Log.d(TAG, "lastname : " + user.lastname);
                }
            });
}

From source file:com.hypers.frame.http.core.AsyncHttpResponseHandler.java

/**
 * Creates a new AsyncHttpResponseHandler
 *///from w  ww  . jav a2  s.  c  om
public AsyncHttpResponseHandler(Context context, boolean isShowProgress) {
    this.context = context;
    this.isShowProgress = isShowProgress;

    if (this.isShowProgress) {
        this.progressDialog = new ProgressDialog(context);
    }

    // Set up a handler to post events back to the correct thread if possible
    if (Looper.myLooper() != null) {
        handler = new ResponderHandler(this);
    }
}