Example usage for android.os Looper prepare

List of usage examples for android.os Looper prepare

Introduction

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

Prototype

public static void prepare() 

Source Link

Document

Initialize the current thread as a looper.

Usage

From source file:com.cellbots.communication.CustomHttpCommChannel.java

@Override
public void listenForMessages(final long waitTimeBetweenPolling, final boolean returnStream) {
    if (inUrl == null || doDisconnect)
        return;/* w  w  w  . j a v  a 2  s  . c o m*/
    stopReading = false;
    listenThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            while (!stopReading) {
                try {
                    if (waitTimeBetweenPolling >= 0)
                        Thread.sleep(waitTimeBetweenPolling);
                    if (commandUrl == null) {
                        commandUrl = new URL(inUrl);
                    }
                    URLConnection cn = commandUrl.openConnection();
                    cn.connect();
                    if (returnStream) {
                        if (mMessageListener != null) {
                            mMessageListener.onMessage(new CommMessage(null, cn.getInputStream(), null, null,
                                    null, mChannelName, CommunicationManager.CHANNEL_HTTP));
                        }
                    } else {
                        BufferedReader rd = new BufferedReader(new InputStreamReader(cn.getInputStream()),
                                1024);
                        String cmd = rd.readLine();
                        if (cmd != null && !cmd.equals(prevCmd) && mMessageListener != null) {
                            prevCmd = cmd;
                            // TODO (chaitanyag): Change this after we come
                            // up with a better protocol. The first (space
                            // separated) token in the command string could
                            // be a timestamp. This is useful if the same
                            // commands are sent back to back. For example,
                            // the controller sends consecutive "hu"
                            // (head up) commands to tilt the head up in
                            // small increments.
                            if (cmd.indexOf(' ') >= 0) {
                                try {
                                    Long.parseLong(cmd.substring(0, cmd.indexOf(' ')));
                                    cmd = cmd.substring(cmd.indexOf(' ') + 1);
                                } catch (NumberFormatException e) {
                                }
                            }
                            mMessageListener.onMessage(new CommMessage(cmd, null, null, null, null,
                                    mChannelName, CommunicationManager.CHANNEL_HTTP));
                        }
                    }
                    if (waitTimeBetweenPolling < 0) { // Do not repeat this loop
                        break;
                    }
                } catch (MalformedURLException e) {
                    Log.e(TAG, "Error processing URL: " + e.getMessage());
                } catch (IOException e) {
                    Log.e(TAG, "Error reading command from URL: " + commandUrl + " : " + e.getMessage());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    listenThread.start();
}

From source file:com.vuzix.samplewebrtc.android.SessionChannel.java

private synchronized void open() {
    close();/*from   ww  w . j  a va2  s .  c  o  m*/

    // ???
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            mSendHandler = new Handler();
            Looper.loop();
        }
    }.start();

    mConnectionThread = new ConnectionThread();
    mConnectionThread.start();
}

From source file:com.z3r0byte.magistify.Fragments.HomeworkFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_homework, container, false);
    listView = view.findViewById(R.id.list_homework);
    swipeRefreshLayout = view.findViewById(R.id.layout_refresh);
    swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.setup_color_3,
            R.color.setup_color_5);/*from   ww w  .  j  av a 2 s .c  o m*/
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.d(TAG, "onRefresh: Refreshing!");
            refresh();
        }
    });
    errorView = view.findViewById(R.id.error_view_homework);

    homework = new Appointment[0];
    homeworkAdapter = new HomeworkAdapter(getActivity(), homework);
    listView.setAdapter(homeworkAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(getActivity(), AppointmentDetailsActivity.class);
            intent.putExtra("Appointment", new Gson().toJson(homework[i]));
            startActivity(intent);
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
            swipeRefreshLayout.setRefreshing(true);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    Appointment appointment = homework[i];
                    AppointmentHandler appointmentHandler = new AppointmentHandler(GlobalAccount.MAGISTER);
                    try {
                        appointment.finished = !appointment.finished;
                        Boolean finished = appointmentHandler.finishAppointment(appointment);
                        Log.d(TAG, "run: Gelukt: " + finished);
                        if (finished) {
                            SharedListener.finishInitiator.finished();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                swipeRefreshLayout.setRefreshing(false);
                                Toast.makeText(getActivity(), R.string.err_no_connection, Toast.LENGTH_SHORT)
                                        .show();
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), R.string.err_unknown, Toast.LENGTH_SHORT).show();
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        });
                    }
                }
            }).start();

            return true;
        }
    });

    configUtil = new ConfigUtil(getActivity());

    SharedListener.finishInitiator = new FinishInitiator();
    FinishResponder responder = new FinishResponder(this);
    SharedListener.finishInitiator.addListener(responder);

    swipeRefreshLayout.setRefreshing(true);
    refresh();

    return view;
}

From source file:org.sigimera.app.android.StatisticFragment.java

@Override
public final View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.statistic, container, false);

    progessDialog = ProgressDialog.show(getActivity(), "Preparing crises information!",
            "Please be patient until the information are ready...", false);
    progessDialog.setCancelable(true);/*ww w. ja v a2s .com*/
    Thread worker = new Thread() {
        @Override
        public void run() {
            try {
                Looper.prepare();
                authToken = ApplicationController.getInstance().getSessionHandler().getAuthenticationToken();
                userLocation = LocationController.getInstance().getLastKnownLocation();

                authToken = ApplicationController.getInstance().getSessionHandler().getAuthenticationToken();
                try {
                    if (!ApplicationController.getInstance().isUpdatedOne())
                        PersistanceController.getInstance().updateEverything(authToken);
                } catch (InterruptedException e) {
                    Log.e("[StatisticFragment]", "Failed to update everything.");
                }

                crisesStats = PersistanceController.getInstance().getCrisesStats(authToken);

                guiHandler.post(updateGUI);
            } catch (AuthenticationErrorException e) {
                // SHOULD NEVER OCCUR: Check before calling this window
                Log.e(Constants.LOG_TAG_SIGIMERA_APP, "Error on authentification" + e.getLocalizedMessage());
            }
        }
    };
    worker.start();

    return view;
}

From source file:de.nware.app.hsDroid.logic.LoginThread.java

License:asdf

@Override
public void run() {
    // flags setzen
    mStoppingThread = false;//from   w w  w  .j  a  v  a2 s . com
    mThreadStatus = STATE_RUNNING;

    // prepare Looper
    Looper.prepare();

    mThreadHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HANLDER_MSG_LOGIN:
                try {
                    doLogin();

                } catch (Exception e) {
                    mThreadStatus = STATE_ERROR;
                    Message oMessage = mParentHandler.obtainMessage();
                    Bundle oBundle = new Bundle();
                    String strMessage = e.getMessage();
                    oBundle.putString("Message", strMessage);
                    oMessage.setData(oBundle);
                    oMessage.what = MESSAGE_ERROR;
                    mParentHandler.sendMessage(oMessage);
                } catch (Throwable e) {
                    Log.e("Login Handler", e.getMessage());
                    e.printStackTrace();
                }
                break;

            case HANLDER_MSG_LOGOUT:
                try {
                    doLogout();

                } catch (Exception e) {
                    mThreadStatus = STATE_ERROR;
                    Message oMessage = mParentHandler.obtainMessage();
                    Bundle oBundle = new Bundle();
                    String strMessage = e.getMessage();
                    oBundle.putString("Message", strMessage);
                    oMessage.setData(oBundle);
                    oMessage.what = MESSAGE_ERROR;
                    mParentHandler.sendMessage(oMessage);
                } catch (Throwable e) {
                    Log.e("Login Handler", e.getMessage());
                    e.printStackTrace();
                }
                break;
            case HANLDER_MSG_KILL:
                getLooper().quit();
                break;
            default:
                break;
            }
        }
    };

    Looper.loop();
}

From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java

public void run() {
    // Start the thread
    mNotificationManager = (NotificationManager) App.mApp.getSystemService(Context.NOTIFICATION_SERVICE);

    Looper.prepare();
    mHandler = new ClementineConnectionHandler(this);

    mPebble = new Pebble();

    // Get a Wakelock Object
    PowerManager pm = (PowerManager) App.mApp.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Clementine");

    Resources res = App.mApp.getResources();
    mNotificationHeight = (int) res.getDimension(android.R.dimen.notification_large_icon_height);
    mNotificationWidth = (int) res.getDimension(android.R.dimen.notification_large_icon_width);

    mAudioManager = (AudioManager) App.mApp.getSystemService(Context.AUDIO_SERVICE);
    mClementineMediaButtonEventReceiver = new ComponentName(App.mApp.getPackageName(),
            ClementineMediaButtonEventReceiver.class.getName());

    mMediaButtonBroadcastReceiver = new ClementineMediaButtonEventReceiver();

    fireOnConnectionReady();//  w w w .j av a  2s  . co  m

    Looper.loop();
}

From source file:com.prey.actions.location.PreyGooglePlayServiceLocation.java

protected void startLocationUpdates() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || (ActivityCompat.checkSelfPermission(ctx,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(ctx,
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
        try {//from w  ww . j  ava  2 s.c o  m
            Looper.prepare();
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            Looper.loop();
        } catch (Exception e) {
            PreyLogger.d("Error startLocationUpdates: " + e.getMessage());
        }
    }

}

From source file:org.lsc.hellocordova.BluetoothPlugin.java

@Override
public PluginResult execute(String action, JSONArray arg1, String callbackId) {
    Log.d("BluetoothPlugin", "Plugin Called");
    PluginResult result = null;/*from w  w w  .  jav a 2s  . c o  m*/
    context = (Context) this.ctx;

    // Register for broadcasts when a device is discovered
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    context.registerReceiver(mReceiver, filter);

    // Register for broadcasts when discovery starts
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    context.registerReceiver(mReceiver, filter);

    // Register for broadcasts when discovery has finished
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    context.registerReceiver(mReceiver, filter);

    // Register for broadcasts when connectivity state changes
    filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    context.registerReceiver(mReceiver, filter);

    Looper.prepare();
    btadapter = BluetoothAdapter.getDefaultAdapter();
    found_devices = new ArrayList<BluetoothDevice>();

    if (ACTION_DISCOVER_DEVICES.equals(action)) {
        try {

            Log.d("BluetoothPlugin", "We're in " + ACTION_DISCOVER_DEVICES);

            found_devices.clear();
            discovering = true;

            if (btadapter.isDiscovering()) {
                btadapter.cancelDiscovery();
            }

            Log.i("BluetoothPlugin", "Discovering devices...");
            btadapter.startDiscovery();

            while (discovering) {
            }

            String devicesFound = null;
            int count = 0;
            devicesFound = "[";
            for (BluetoothDevice device : found_devices) {
                Log.i("BluetoothPlugin",
                        device.getName() + " " + device.getAddress() + " " + device.getBondState());
                if ((device.getName() != null) && (device.getBluetoothClass() != null)) {
                    devicesFound = devicesFound + " { \"name\" : \"" + device.getName() + "\" ,"
                            + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \""
                            + device.getBluetoothClass().getDeviceClass() + "\" }";
                    if (count < found_devices.size() - 1)
                        devicesFound = devicesFound + ",";
                } else
                    Log.i("BluetoothPlugin",
                            device.getName() + " Problems retrieving attributes. Device not added ");
                count++;
            }

            devicesFound = devicesFound + "] ";

            Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Returning: " + devicesFound);
            result = new PluginResult(Status.OK, devicesFound);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_IS_BT_ENABLED.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_IS_BT_ENABLED);

            boolean isEnabled = btadapter.isEnabled();

            Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED,
                    "Returning " + "is Bluetooth Enabled? " + isEnabled);
            result = new PluginResult(Status.OK, isEnabled);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_ENABLE_BT.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_ENABLE_BT);

            boolean enabled = false;

            Log.d("BluetoothPlugin", "Enabling Bluetooth...");

            if (btadapter.isEnabled()) {
                enabled = true;
            } else {
                enabled = btadapter.enable();
            }

            Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Returning " + "Result: " + enabled);
            result = new PluginResult(Status.OK, enabled);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_DISABLE_BT.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_DISABLE_BT);

            boolean disabled = false;

            Log.d("BluetoothPlugin", "Disabling Bluetooth...");

            if (btadapter.isEnabled()) {
                disabled = btadapter.disable();
            } else {
                disabled = true;
            }

            Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Returning " + "Result: " + disabled);
            result = new PluginResult(Status.OK, disabled);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_PAIR_BT.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_PAIR_BT);

            String addressDevice = arg1.getString(0);

            if (btadapter.isDiscovering()) {
                btadapter.cancelDiscovery();
            }

            BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
            boolean paired = false;

            Log.d("BluetoothPlugin", "Pairing with Bluetooth device with name " + device.getName()
                    + " and address " + device.getAddress());

            try {
                Method m = device.getClass().getMethod("createBond");
                paired = (Boolean) m.invoke(device);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Returning " + "Result: " + paired);
            result = new PluginResult(Status.OK, paired);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_UNPAIR_BT.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_UNPAIR_BT);

            String addressDevice = arg1.getString(0);

            if (btadapter.isDiscovering()) {
                btadapter.cancelDiscovery();
            }

            BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
            boolean unpaired = false;

            Log.d("BluetoothPlugin", "Unpairing Bluetooth device with " + device.getName() + " and address "
                    + device.getAddress());

            try {
                Method m = device.getClass().getMethod("removeBond");
                unpaired = (Boolean) m.invoke(device);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Returning " + "Result: " + unpaired);
            result = new PluginResult(Status.OK, unpaired);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_LIST_BOUND_DEVICES.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_LIST_BOUND_DEVICES);

            Log.d("BluetoothPlugin", "Getting paired devices...");
            Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices();
            int count = 0;
            String resultBoundDevices = "[ ";
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    Log.i("BluetoothPlugin",
                            device.getName() + " " + device.getAddress() + " " + device.getBondState());

                    if ((device.getName() != null) && (device.getBluetoothClass() != null)) {
                        resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ,"
                                + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \""
                                + device.getBluetoothClass().getDeviceClass() + "\" }";
                        if (count < pairedDevices.size() - 1)
                            resultBoundDevices = resultBoundDevices + ",";
                    } else
                        Log.i("BluetoothPlugin",
                                device.getName() + " Problems retrieving attributes. Device not added ");
                    count++;
                }

            }

            resultBoundDevices = resultBoundDevices + "] ";

            Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Returning " + resultBoundDevices);
            result = new PluginResult(Status.OK, resultBoundDevices);

        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_STOP_DISCOVERING_BT.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_STOP_DISCOVERING_BT);

            boolean stopped = true;

            Log.d("BluetoothPlugin", "Stop Discovering Bluetooth Devices...");

            if (btadapter.isDiscovering()) {
                Log.i("BluetoothPlugin", "Stop discovery...");
                stopped = btadapter.cancelDiscovery();
                discovering = false;
            }

            Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Returning " + "Result: " + stopped);
            result = new PluginResult(Status.OK, stopped);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_IS_BOUND_BT.equals(action)) {
        try {
            Log.d("BluetoothPlugin", "We're in " + ACTION_IS_BOUND_BT);
            String addressDevice = arg1.getString(0);
            BluetoothDevice device = btadapter.getRemoteDevice(addressDevice);
            Log.i("BluetoothPlugin", "BT Device in state " + device.getBondState());

            boolean state = false;

            if (device != null && device.getBondState() == 12)
                state = true;
            else
                state = false;

            Log.d("BluetoothPlugin", "Is Bound with " + device.getName() + " - address " + device.getAddress());

            Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Returning " + "Result: " + state);
            result = new PluginResult(Status.OK, state);

        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_OPEN_SOCKET.equals(action)) {
        Log.d("BluetoothPlugin", "We're in " + ACTION_OPEN_SOCKET);
        try {
            String addressDevice = arg1.getString(0);
            openSocket(addressDevice);
            result = new PluginResult(Status.OK, "true");

        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_OPEN_SOCKET, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_MESSAGE_SOCKET.equals(action)) {
        Log.d("BluetoothPlugin", "We're in " + ACTION_MESSAGE_SOCKET);
        try {
            String msg = arg1.getString(0);
            sendData(msg);
            result = new PluginResult(Status.OK, "true");

        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_MESSAGE_SOCKET, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_CLOSE_SOCKET.equals(action)) {
        Log.d("BluetoothPlugin", "We're in " + ACTION_CLOSE_SOCKET);
        try {
            closeSocket();
            result = new PluginResult(Status.OK, "true");

        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_CLOSE_SOCKET, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    } else if (ACTION_PING_SOCKET.equals(action)) {
        try {

            Log.d("BluetoothPlugin", "We're in " + ACTION_PING_SOCKET);

            String data = "{";
            data = data + "\"count\": " + Integer.toString(pingCount) + ",";

            String items = "";
            for (String item : pingData) {
                items = items + ",\"" + item + "\"";
            }

            data = data + "  \"data\" : [" + items.substring(1) + " ]";
            data = data + "}";

            result = new PluginResult(Status.OK, data);
        } catch (Exception Ex) {
            Log.d("BluetoothPlugin - " + ACTION_PING_SOCKET, "Got Exception " + Ex.getMessage());
            result = new PluginResult(Status.ERROR);
        }

    }

    else {
        result = new PluginResult(Status.INVALID_ACTION);
        Log.d("BluetoothPlugin", "Invalid action : " + action + " passed");
    }
    return result;
}

From source file:com.ubikod.urbantag.ContentViewerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();

    /* If we are coming from Notification delete notification */
    if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_CONTENT_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closeContentNotif();
    } else if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_PLACE_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closePlaceNotif();
    }/*from w  w w  .ja  v a2 s  . c om*/

    /* Fetch content info */
    ContentManager contentManager = new ContentManager(new DatabaseHelper(this, null));
    Log.i(UrbanTag.TAG, "View content : " + extras.getInt(CONTENT_ID));
    this.content = contentManager.get(extras.getInt(CONTENT_ID));
    if (this.content == null) {
        Toast.makeText(this, R.string.error_occured, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    setTitle(content.getName());
    com.actionbarsherlock.app.ActionBar actionBar = this.getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.content_viewer);

    /* Find webview and create url for content */
    final WebView webView = (WebView) findViewById(R.id.webview);
    final String URL = UrbanTag.API_URL + ACTION_GET_CONTENT.replaceAll("%", "" + this.content.getId());

    /* Display progress animation */
    final ProgressDialog progress = ProgressDialog.show(this, "",
            this.getResources().getString(R.string.loading_content), false, true,
            new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    timeOutHandler.interrupt();
                    webView.stopLoading();
                    ContentViewerActivity.this.finish();
                }

            });

    /* Go fetch content */
    contentFetcher = new Thread(new Runnable() {

        DefaultHttpClient httpClient;

        @Override
        public void run() {
            Looper.prepare();
            Log.i(UrbanTag.TAG, "Fetching content...");
            httpClient = new DefaultHttpClient();
            try {
                String responseBody = httpClient.execute(new HttpGet(URL), new BasicResponseHandler());
                webView.loadDataWithBaseURL("fake://url/for/encoding/hack...", responseBody, mimeType, encoding,
                        "");
                timeOutHandler.interrupt();
                if (progress.isShowing())
                    progress.dismiss();
            } catch (ClientProtocolException cpe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            } catch (IOException ioe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            }

            Looper.loop();
        }

    });
    contentFetcher.start();

    /* TimeOut Handler */
    timeOutHandler = new Thread(new Runnable() {
        private int INCREMENT = 1000;

        @Override
        public void run() {
            Looper.prepare();
            try {
                for (int time = 0; time < TIMEOUT; time += INCREMENT) {
                    Thread.sleep(INCREMENT);
                }

                Log.w(UrbanTag.TAG, "TimeOut !");
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });

                contentFetcher.interrupt();
                progress.cancel();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Looper.loop();

        }

    });
    timeOutHandler.start();

}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

ClipboardManager getClipboardManager() {
    Object clipboard = null;/*  w w  w.ja  va  2 s.  co  m*/
    if (mClipboard == null) {
        try {
            clipboard = mService.getSystemService(Context.CLIPBOARD_SERVICE);
        } catch (Exception e) {
            Looper.prepare(); // Clipboard manager won't work without this on higher SDK levels...
            clipboard = mService.getSystemService(Context.CLIPBOARD_SERVICE);
        }
        mClipboard = (ClipboardManager) clipboard;
        if (mClipboard == null) {
            Log.w("Clipboard managed not accessible.");
        }
    }
    return mClipboard;
}