Java Code Examples for android.os.Looper#prepare()

The following examples show how to use android.os.Looper#prepare() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VideoStream.java    From spydroid-ipcamera with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Opens the camera in a new Looper thread so that the preview callback is not called from the main thread
 * If an exception is thrown in this Looper thread, we bring it back into the main thread.
 * @throws RuntimeException Might happen if another app is already using the camera.
 */
private void openCamera() throws RuntimeException {
	final Semaphore lock = new Semaphore(0);
	final RuntimeException[] exception = new RuntimeException[1];
	mCameraThread = new Thread(new Runnable() {
		@Override
		public void run() {
			Looper.prepare();
			mCameraLooper = Looper.myLooper();
			try {
				mCamera = Camera.open(mCameraId);
			} catch (RuntimeException e) {
				exception[0] = e;
			} finally {
				lock.release();
				Looper.loop();
			}
		}
	});
	mCameraThread.start();
	lock.acquireUninterruptibly();
	if (exception[0] != null) throw new CameraInUseException(exception[0].getMessage());
}
 
Example 2
Source File: SensorHubService.java    From sensorhub with Mozilla Public License 2.0 6 votes vote down vote up
public void startSensorHub(final IModuleConfigRepository config)
{
    if (bgThread == null)
    {
        bgThread = new Thread() {
            
            public void run() 
            {
                // prepare for processing sensor messages
                Looper.prepare();
                bgLooper = Looper.myLooper();
                
                // start sensorhub
                SensorHub.createInstance(null, new ModuleRegistry(config)).start();
                Log.i("SensorHub", "SensorHub started...");     
                sensorhub = SensorHub.getInstance();
                
                Looper.loop();
            }        
        };
        
        bgThread.start();
    }
}
 
Example 3
Source File: AbsTaskHandlerRunner.java    From BaseProject with Apache License 2.0 6 votes vote down vote up
@Override
public final void run() {
    if (isQuit) {
        return;
    }
    Thread.currentThread().setName(theTaskName);
    mTid = Process.myTid();
    Looper.prepare();
    if (isQuit) {
        return;
    }
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(taskPriority);
    taskDispatchHandler = new WeakHandler<>(this, mLooper);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}
 
Example 4
Source File: InstantCameraView.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    synchronized (sync) {
        handler = new EncoderHandler(this);
        ready = true;
        sync.notify();
    }
    Looper.loop();

    synchronized (sync) {
        ready = false;
    }
}
 
Example 5
Source File: MoneroHandlerThread.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}
 
Example 6
Source File: DecodeThread.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    handler = new DecodeHandler(activity, hints);
    handlerInitLatch.countDown();
    Looper.loop();
}
 
Example 7
Source File: SlickForm.java    From SlickForm with MIT License 5 votes vote down vote up
@Override
protected final Boolean doInBackground(Void... params) {
    if (Looper.myLooper() == null)
        Looper.prepare();

    return mActionListener != null && mActionListener.workInBackground(formFields);
}
 
Example 8
Source File: SdlRemoteDisplayTest.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    if(Looper.myLooper() == null){
        Looper.prepare();
    }
}
 
Example 9
Source File: DecodeThread.java    From android-quick-response-code with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    handler = new DecodeHandler(activity, hints);
    handlerInitLatch.countDown();
    Looper.loop();
}
 
Example 10
Source File: P_TaskQueue.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
private void initHandler()
{
	final Thread thread = new Thread()
	{
		@Override public void run()
		{
			Looper.prepare();
			m_executeHandler = new Handler(Looper.myLooper());
			Looper.loop();
		}
	};

	thread.start();
}
 
Example 11
Source File: SdlRouterServiceTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test router service correctly acquires Hash ID from V5 start service ACK
 */
public void testStartSessionAckV5HashId() {
	if (Looper.myLooper() == null) {
		Looper.prepare();
	}
	Method method;
	try {
		SdlRouterService sdlRouterService = new SdlRouterService();

		initFields(sdlRouterService);
		addDummyRegisteredApp(sdlRouterService, "12345", sessionId);

		// create packet and invoke sendPacketToRegisteredApp
		int hashId = 0x123456;
		SdlPacket packet = new SdlPacket(5, false, SdlPacket.FRAME_TYPE_CONTROL, SdlPacket.SERVICE_TYPE_RPC, SdlPacket.FRAME_INFO_START_SERVICE_ACK, sessionId, 0, 2, null);
		packet.putTag(ControlFrameTags.RPC.StartServiceACK.PROTOCOL_VERSION, "5.0.0");
		packet.putTag(ControlFrameTags.RPC.StartServiceACK.HASH_ID, hashId);
		packet.putTag(ControlFrameTags.RPC.StartServiceACK.MTU, 1024);
		packet.setTransportRecord(new TransportRecord(TransportType.BLUETOOTH,null));
		packet.constructPacket(); // update 'payload' field in the packet instance

		method = sdlRouterService.getClass().getDeclaredMethod("sendPacketToRegisteredApp", SdlPacket.class);
		method.setAccessible(true);
		Boolean success = (Boolean) method.invoke(sdlRouterService, packet);
		Assert.assertTrue(success);

		// verify hash id map contains the correct ID
		Field field = sdlRouterService.getClass().getDeclaredField("sessionHashIdMap");
		field.setAccessible(true);
		SparseIntArray sessionHashIdMap = (SparseIntArray)field.get(sdlRouterService);

		Assert.assertTrue(sessionHashIdMap.indexOfKey(sessionId) >= 0);
		int value = sessionHashIdMap.get(sessionId, -1);
		Assert.assertEquals(hashId, value);
	} catch (Exception e) {
		Assert.fail("Exception in sendPacketToRegisteredApp, " + e);
	}
}
 
Example 12
Source File: CacheThread.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	Looper.prepare();
	_handler = new CacheThreadHandler();
	_ready = true;
	synchronized(_readyLock) {
		_readyLock.notify();
	}
	Looper.loop();
}
 
Example 13
Source File: DecodeThread.java    From myapplication with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    handler = new DecodeHandler(activity, hints);
    handlerInitLatch.countDown();
    Looper.loop();
}
 
Example 14
Source File: DecodeThread.java    From ProjectX with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    handler = new DecodeHandler(cameraManager, mHandler, hints);
    handlerInitLatch.countDown();
    Looper.loop();
}
 
Example 15
Source File: DecodeThread.java    From barcodescanner-lib-aar with MIT License 5 votes vote down vote up
@Override
public void run() {
  Looper.prepare();
  handler = new DecodeHandler(activity, hints);
  handlerInitLatch.countDown();
  Looper.loop();
}
 
Example 16
Source File: DecodeThread.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  Looper.prepare();
  handler = new DecodeHandler(activity, hints);
  handlerInitLatch.countDown();
  Looper.loop();
}
 
Example 17
Source File: BackgroundService.java    From GeoLog with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
	Debug.log("Thread init");
				
	databaseHelper = Database.Helper.getInstance(context);
	
	alarm = (AlarmManager)context.getSystemService(ALARM_SERVICE);
	{
		Intent i = new Intent(context.getApplicationContext(), BackgroundService.class);
		i.putExtra(EXTRA_ALARM_CALLBACK, 1);
		alarmCallback =	PendingIntent.getService(BackgroundService.this, 0, i, 0);
	}

	Looper.prepare();
	handler = new Handler();
			
	Debug.log("Registering for updates");			
	prefs = PreferenceManager.getDefaultSharedPreferences(context);					
	long id = prefs.getLong(SettingsFragment.PREF_CURRENT_PROFILE, 0);
	if (id > 0) currentProfile = Database.Profile.getById(databaseHelper, id, null);
	if (currentProfile == null) currentProfile = Database.Profile.getOffProfile(databaseHelper);
	metric = !prefs.getString(SettingsFragment.PREF_UNITS, SettingsFragment.PREF_UNITS_DEFAULT).equals(SettingsFragment.VALUE_UNITS_IMPERIAL);
	prefs.registerOnSharedPreferenceChangeListener(preferencesUpdated);
	LocalBroadcastManager.getInstance(context).registerReceiver(databaseUpdated, new IntentFilter(Database.Helper.NOTIFY_BROADCAST));
	
	Debug.log("Registering for power levels");
	context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	
	Debug.log("Connecting ActivityRecognitionClient");
	activityIntent = PendingIntent.getService(context, 1, new Intent(context, BackgroundService.class), 0);
	activityClient = new ActivityRecognitionClient(context, activityConnectionCallbacks, activityConnectionFailed);
	activityClient.connect();

	Debug.log("Connecting LocationClient");
	locationClient = new LocationClient(context, locationConnectionCallbacks, locationConnectionFailed);
	locationClient.connect();
	
	Debug.log("Entering loop");
	handler.post(new Runnable() {				
		@Override
		public void run() {
			updateListeners(FLAG_SETUP);
		}
	});						
	Looper.loop();			
	Debug.log("Exiting loop");
	
	context.unregisterReceiver(batteryReceiver);
	
	LocalBroadcastManager.getInstance(context).unregisterReceiver(databaseUpdated);
	prefs.unregisterOnSharedPreferenceChangeListener(preferencesUpdated);			
	
	if (activityConnected) {
		activityClient.removeActivityUpdates(activityIntent);
		activityClient.disconnect();
	}
	if (locationConnected) {
		locationClient.removeLocationUpdates(locationListener);
		locationClient.disconnect();
	}			
}
 
Example 18
Source File: AndroidOpenAccessoryBridge.java    From android-open-accessory-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case STOP_THREAD:
                Looper.myLooper().quit();
                break;
            case MAYBE_READ:
                final boolean readResult;
                try {
                    readResult = mReadBuffer.read(mInputStream);
                } catch (IOException exception) {
                    terminate();
                    break;
                }
                if (readResult) {
                    if (mReadBuffer.size == 0) {
                        mHandler.sendEmptyMessage(STOP_THREAD);
                    } else {
                        mListener.onAoabRead(mReadBuffer);
                        mReadBuffer.reset();
                        mHandler.sendEmptyMessage(MAYBE_READ);
                    }
                } else {
                    mHandler.sendEmptyMessageDelayed(MAYBE_READ, READ_COOLDOWN_MS);
                }
                break;
            }
        }
    };
    detectAccessory();
    Looper.loop();
    detachAccessory();
    mIsShutdown = true;
    mListener.onAoabShutdown();

    // Clean stuff up
    mHandler = null;
    mListener = null;
    mUsbManager = null;
    mReadBuffer = null;
    mInternalThread = null;
}
 
Example 19
Source File: LoginActivity.java    From pe-protector-moe with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 初始化界面
    loginAlertDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
    loginAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
    loginAlertDialog.setTitleText("正在登录,请稍候...");
    loginAlertDialog.setCancelable(false);
    // 透明
    setContentView(R.layout.activity_login);
    // 设置标题栏
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // 读取帐号密码
    EditText ed_username = findViewById(R.id.ed_username);
    EditText ed_pwd = findViewById(R.id.ed_pwd);
    SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
    ed_username.setText(preferences.getString("username", ""));
    ed_pwd.setText(preferences.getString("pwd", ""));

    // 设置按钮事件
    Button actionButton = findViewById(R.id.bt_login);
    actionButton.setOnClickListener((v -> firstLogin()));
    // 设置服务器
    NiceSpinner sp_server = findViewById(R.id.sp_server);
    sp_server.attachDataSource(Arrays.asList("安卓", "IOS", "台服", "国际"));
    sp_server.setSelectedIndex(preferences.getInt("server", 0));
    // 连接更新服务器
    final CheckVersionCallBack callBack = new CheckVersionCallBack() {
        @Override
        public void onFinish() {
        }

        @Override
        public void onUpgrade(String newVersion, String newData) {
            if (Config.hasLogin) {
                return;
            }
            Looper.prepare();
            new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("发现新版本")
                    .setContentText(String.format("新版本:%s\n更新日志:\n%s", newVersion, newData))
                    .setConfirmText("去下载")
                    .setCancelText("下次再说")
                    .setCancelClickListener(SweetAlertDialog::cancel)
                    .setConfirmClickListener((sweetAlertDialog) -> {
                        Uri uri = Uri.parse("https://github.com/ProtectorMoe/pe-protector-moe/releases");
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                        sweetAlertDialog.cancel();
                        setResult(RESULT_CANCELED);
                        finish();
                    })
                    .show();
            Looper.loop();
        }

        @Override
        public void onError(String errMsg) {
            if (Config.hasLogin) {
                return;
            }
            Looper.prepare();
            new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("错误")
                    .setContentText("连接更新服务器失败")
                    .setConfirmText("确定")
                    .setConfirmClickListener(SweetAlertDialog::cancel)
                    .show();
            Looper.loop();
        }
    };

    // 检测软件更新
    new Thread(() -> {
        try {
            PackageManager manager = getApplicationContext().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getApplicationContext().getPackageName(), 0);
            int versionCode = info.versionCode;
            CheckVersionBean bean = NetSender.getInstance().checkVersion();
            if (bean.versionCode > versionCode) {
                callBack.onUpgrade(bean.versionName, bean.history.get(String.valueOf(bean.versionCode)));
            } else {
                callBack.onFinish();
            }
        } catch (Exception e) {
            callBack.onError(e.getMessage() + e.getLocalizedMessage());
        }
    }).start();
}
 
Example 20
Source File: ExecuteCmd.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
private void initThread() {
    mThread = new Thread(() -> {
        Looper.prepare();

        int count = 0;
        String str = "";
        try {
            //execute the command
            final Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));

            //handler that can stop the thread
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    process.destroy();

                    mThread.interrupt();
                    mThread = null;

                    try {
                        process.waitFor();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };

            //read the lines
            int i;
            final char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();

            while ((i = reader.read(buffer)) > 0) {
                output.append(buffer, 0, i);

                Handler h = new Handler(Looper.getMainLooper());
                final int finalI = i;
                h.post(() -> {
                    ReturnObject o = new ReturnObject();
                    o.put("value", finalI + " " + String.valueOf(buffer));
                    callbackfn.event(o);
                });

            }
            reader.close();

            str = output.toString();
        } catch (IOException e) {
            // Log.d(TAG, "Error");
            e.printStackTrace();
        }
        Looper.loop();
    });
}