How to properly implement a sensor with SensorManager in a thread?

How to properly implement a sensor with SensorManager in a thread?

Content Index :

How to properly implement a sensor with SensorManager in a thread?
Tag : java , By : cashshadow
Date : December 01 2020, 04:45 PM

it should still fix some issue Outside of an Activity, getSystemService() requires Context. Pass through a Context when initialising your thread and use context.getSystemService().
class MyThread extends Thread {

private Context context;
public SensorManager sensorManager;

public MyThread(Context context) {
    this.context = context;

public void run()
    sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
    sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
/** In Activity **/ 
public static void main(String[] args) {
    new MyThread(getContext()).start();

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to properly implement and close sleeping thread in a Windows DLL

Tag : multithreading , By : sadboy
Date : March 29 2020, 07:55 AM
should help you out I have a native Windows DLL written in C. This DLL is designed to be loaded (injected) in different Windos processes. This DLL creates some working threads that look like this: , Create an event:
HANDLE threadTerminationEvent = CreateEvent(.....);
while (1)
    if (WaitForSingleObject(threadTerminationEvent, few secs) != WAIT_TIMEOUT)
// release resources and end thread
SetEvent(threadTerminationEvent); // “please, die”
WaitForSingleObject(hThread, INFINITE);

How to know if my SensorManager has a registered Sensor

Tag : android , By : user133834
Date : March 29 2020, 07:55 AM
I wish this helpful for you As far as I know, there is no native way to check if you have already registered listener. I would not worry too much about this check since this check is already done by Android, so if you have already registered listener, Android is not gonna add the same listener twice:
private boolean registerLegacyListener(int legacyType, int type,
        SensorListener listener, int sensors, int rate)
        if (listener == null) {
            return false;
        boolean result = false;
        // Are we activating this legacy sensor?
        if ((sensors & legacyType) != 0) {
            // if so, find a suitable Sensor
            Sensor sensor = getDefaultSensor(type);
            if (sensor != null) {
                // If we don't already have one, create a LegacyListener
                // to wrap this listener and process the events as
                // they are expected by legacy apps.
                LegacyListener legacyListener = null;
                synchronized (mLegacyListenersMap) {
                    legacyListener = mLegacyListenersMap.get(listener);
                    if (legacyListener == null) {
                        // we didn't find a LegacyListener for this client,
                        // create one, and put it in our list.
                        legacyListener = new LegacyListener(listener);
                        mLegacyListenersMap.put(listener, legacyListener);
                // register this legacy sensor with this legacy listener
                // and finally, register the legacy listener with the new apis
                result = registerListener(legacyListener, sensor, rate);
        return result;

Android: implement sensormanager in a class

Tag : android , By : Stuka
Date : March 29 2020, 07:55 AM
help you fix your problem You have named your activity as SensorManager which is wrong because there is already a SensorManager Class in SDK
Try re-naming your activity.

Android: Algorithms for SensorManager.getRotationMatrix and SensorManager.getOrientation()

Tag : android , By : user113409
Date : March 29 2020, 07:55 AM
I wish this helpful for you Let me try to explain: getRotationMatrix compose rotation matrix on the basis of gravity and megnetic vector.
Our main goal here is to construct NED frame
float Hx = Ey*Az - Ez*Ay;
float Hy = Ez*Ax - Ex*Az;
float Hz = Ex*Ay - Ey*Ax;
final float normH = (float)Math.sqrt(Hx*Hx + Hy*Hy + Hz*Hz);
final float invH = 1.0f / normH;
    Hx *= invH;
    Hy *= invH;
    Hz *= invH;
final float invA = 1.0f / (float)Math.sqrt(Ax*Ax + Ay*Ay + Az*Az);
    Ax *= invA;
    Ay *= invA;
    Az *= invA;
double Mx = Ay * Hz - Az * Hy;
double My = Az * Hx - Ax * Hz;
double Mz = Ax * Hy - Ay * Hx;
R[0] = Hx;     R[1] = Hy;     R[2] = Hz;
R[3] = Mx;     R[4] = My;     R[5] = Mz;
R[6] = Ax;     R[7] = Ay;     R[8] = Az;
azimuth = (float)Math.atan2(R[1], R[4]);
pitch = (float)Math.asin(-R[7]);
roll = (float)Math.atan2(-R[6], R[8]);

How do I properly implement a cancellable, long-running thread in C#?

Tag : chash , By : Moe Skeeto
Date : March 29 2020, 07:55 AM
Any of those help Tasks aren't necessarily for I/O bound operations. In fact, this is a good use-case for Task.Delay (which internally wraps a timer):
public static async Task ProcessAsync(CancellationToken cancellationToken)
        while (true)
            await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken).ConfigureAwait(false);

    catch (TaskCanceledException)
        // Cancellation requested, do whatever cleanup you need then exit gracefully
var cancellationTokenSource = new CancellationTokenSource();

var task = ProcessAsync(cancellationTokenSource.Token);

string response;
    Console.WriteLine("Press 'q' to quit");
    response = Console.ReadLine();
} while (response != "q");


task.Wait(); // Wait for the task to finish
var timer = new Timer(_ => Process(), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));

string response;
    Console.WriteLine("Press 'q' to quit");
    response = Console.ReadLine();
} while (response != "q");

timer.Dispose(); // Stop the timer
Related Posts Related QUESTIONS :
  • What's the behavior of onBackpressureBuffer in RxJava2
  • Java regex can only use 1 quantifier in a lookback (need 2)
  • How to fix error in native query : it is showing syntax error near or at
  • How to retrieve nested object from a document and display it in FirestoreRecyclerOptions?
  • Why not use ListIterator for full LinkedList Operation?
  • Android Webview EvaluateJavascript sometimes does not return a response
  • Matcher java doesn't work but regex seems to be good
  • Finding dimensions of a .gif file
  • Java Number format how to change +/- sign to custom text
  • Entity partially saved when using JOINED inheritance strategy and setting spring.jpa.properties.hibernate.jdbc.batch_siz
  • Stored Procedure in Java Spring Boot Project returns null as Output
  • How to solve org.hibernate.MappingException which is causing due to inheriting a class
  • Clean Archtecture. Understanding of scheme
  • Processing 3 triangle not showing in Javafx 8 Window tab
  • How to specify a sequence-based generated value in Hibernate 5 via legacy mapping
  • Spring-boot application not getting auto-deployed on startup
  • How to only pass strings that the user select
  • Is there a way to SELECT using "GREATEST(field1, field2)" where field1 and field2 are aggregate sums in the sa
  • How to handle JSON objects wrapped into one JSON object with retrofit2?
  • Configure Hazelcast CPSubsystem Retries Timeout
  • how to use onBindViewHolder with multiple items in android RecyclerView
  • No ParameterResolver registered for parameter in BeforeAll method
  • Finding the path in a graph with the least casualties according to the lanchester square law
  • MongoWriteException when inserting into Mongodb with composite custom _id
  • Fetch Oracle procedure metadata with Java when multiple procedure signatures
  • Value modification of key-pair in HashMap and impact for a HashCode
  • Migration from solrj to spring-data-solr
  • How to check if you're still connected to the database with jpa
  • Use Date type in the graphql scheme
  • Split and add the string based on length
  • Is "main" method of spring boot application required when deploy as war
  • Getting the average within specific numbers in an array
  • how to use izpack to make my jar application to installer?
  • What is meant by src in Java Eclipse?
  • Create a mirrored linked list in Java
  • Examples of good JPA Java Desktop Application
  • Translate Java to Python -- signing strings with PEM certificate files
  • Algorithm Analysis tool for java
  • Java serial comm API - what does inputstream.read() return if a timeout occurs?
  • How do I make a background thread in Java that allows the main application to exit completely? This works in Linux, but
  • How to add an image dynamically at runtime in java
  • Java App on Mac asking for allow network connections everytime
  • Best actively maintained Java XMPP Library?
  • Multi-Threaded Application - Help with some pseudo code!
  • Scoping a StringBuilder inside a for loop
  • How to specify hash algorithm when updating LDAP via Java?
  • Class not found exception (org.apache.openjpa.enhance.PersistenceCapable) thrown in a client of WLS 10
  • In Java ,where in memory are class functions put?
  • How do I test expectedExceptionsMessageRegExp (exception message) using TestNG?
  • Help In understanding Multi Dimentional Arrays
  • No bean named '...' is defined and Spring @Resource annotation
  • Singleton design pattern vs Singleton beans in Spring container
  • flashvars object was not working in mozilla browser
  • Shell script to import mysql dump file
  • What are the best practices to separate data from users
  • May I use com.google.code prefix for my packages?
  • How to set classpath in manifest file , while creating JAR from eclipse?
  • dealing with voice in java
  • Error: java.security.AccessControlException: Access denied
  • How to verify the root trust of a ceritifcate
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com