下面列出了android.os.Looper#prepare ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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());
}
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();
}
}
@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;
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(cameraManager, mHandler, hints);
handlerInitLatch.countDown();
Looper.loop();
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
@Override
public void run() {
Looper.prepare();
_handler = new CacheThreadHandler();
_ready = true;
synchronized(_readyLock) {
_readyLock.notify();
}
Looper.loop();
}
/**
* 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);
}
}
private void initHandler()
{
final Thread thread = new Thread()
{
@Override public void run()
{
Looper.prepare();
m_executeHandler = new Handler(Looper.myLooper());
Looper.loop();
}
};
thread.start();
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
@Override
protected void setUp() throws Exception {
super.setUp();
if(Looper.myLooper() == null){
Looper.prepare();
}
}
@Override
protected final Boolean doInBackground(Void... params) {
if (Looper.myLooper() == null)
Looper.prepare();
return mActionListener != null && mActionListener.workInBackground(formFields);
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
@Override
public void run() {
Looper.prepare();
synchronized (sync) {
handler = new EncoderHandler(this);
ready = true;
sync.notify();
}
Looper.loop();
synchronized (sync) {
ready = false;
}
}
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();
});
}
@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();
}
@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();
}
}
@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;
}