Turn off screen with light sensor - Android Q&A, Help & Troubleshooting

Hi guys,
I'm trying to develop an application that use the sensor light, when the light is less than a threshold the screen turn off.
I'm gained the light value but I've difficul to force the screen to turn off.
Someone can help me??
Code:
package com.example.screen_on_off;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private SensorManager mySensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private WakeLock mWakeLock;
TextView textLIGHT_available, textLIGHT_reading;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLIGHT_available = (TextView)findViewById(R.id.LIGHT_available);
textLIGHT_reading = (TextView)findViewById(R.id.LIGHT_reading);
mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.getDefaultDisplay();
Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(LightSensor != null){
textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
mySensorManager.registerListener(
LightSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}else{
textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
}
}
private final SensorEventListener LightSensorListener = new SensorEventListener(){
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
[user=1299008]@supp[/user]ressWarnings("deprecation")
 [user=439709]@override[/user]
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
textLIGHT_reading.setText("LIGHT: " + event.values[0]);
if (event.values[0]<250.00f) {
Toast.makeText(MainActivity.this,"The value is less than 250",Toast.LENGTH_LONG).show();
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
mWakeLock.acquire();
}
//else mWakeLock.release();
}
}
};
}

Related

[Q] Screen Turn Off with light sensor

Hi guys,
I'm trying to develop an application that use the sensor light, when the light is less than a threshold the screen turn off.
I'm gained the light value but I've difficult to force the screen to turn off
Someone can help me??
Code:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private SensorManager mySensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private WakeLock mWakeLock;
TextView textLIGHT_available, textLIGHT_reading;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLIGHT_available = (TextView)findViewById(R.id.LIGHT_available);
textLIGHT_reading = (TextView)findViewById(R.id.LIGHT_reading);
mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.getDefaultDisplay();
Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(LightSensor != null){
textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
mySensorManager.registerListener(
LightSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}else{
textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
}
}
private final SensorEventListener LightSensorListener = new SensorEventListener(){
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
textLIGHT_reading.setText("LIGHT: " + event.values[0]);
if (event.values[0]<250.00f) {
Toast.makeText(MainActivity.this,"The value is less than 250",Toast.LENGTH_LONG).show();
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
mWakeLock.acquire();
}
//else mWakeLock.release();
}
}
};
}

Help: reading out sensor data

Hi folks,
well ... first of all: I'm completely new to programming related to Android. I do have basic knowledge in programming with Basic and C. But im all new to Java and programming with the Android ecosystem (I am familiar with the Android ecosystem, though ... I've just never written code for Android).
Now I wanted a simple app to read out and display some sensor data, such as acceleration along y-axis and rotation angle around y-axis.
But I found the whole way you get stuff out of the sensors very confusing ans somehow unnecessarily complicated. However....
I've successfully managed to code an app, that checks whether certain sensors are available or not - and show an according text in a TextView for the user to read.
The next step was, I wanted to code an app that reads the rotation angle and shows the current angle in a TextView for the user. But I haven't managed that.
I found the whole System of reading the rotation data very complex..... why isn't there just a simple function like "get the y-axis rotation angle" and thats it .... I've searched a lot in the Interwebz, tried to understand how that stuff works, and used some code of some examples i thought i understood ... well, I obviously didn't ....
This is what I've got so far:
Code:
package test.sensor4;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//float A[] = new float[9];
//float I[] = new float[9];
float[] mGravity;
float[] mGeomagnetic;
float azimut;
float pitch;
float roll;
Button btn1;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(this);
//SensorManager.registerListener(this)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float A[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(A, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(A, orientation);
azimut = orientation[0]; // orientation contains: azimut, pitch and roll
pitch = orientation[1];
roll = orientation[2];
TextView tv1 = (TextView)findViewById(R.id.text1);
tv1.setText(String.valueOf(+roll));
}
}
}
@Override
public void onClick(View e) {
TextView tv2 = (TextView)findViewById(R.id.text2);
tv2.setText(String.valueOf(+pitch));
}
}
what this does is: it doesn't change the text from the first textview at all ... in the second textview it prints "0.0"
I don't understand why .... Maybe you guys can help me.
Thanks in advance.
Best wishes.

How can i create a common messagebox?

Hi Guys,
Total N00b so apologies for this but i'm looking at using a default / std messagebox.
I've spent roughly about 30 minutes looking on XDA & Stack Overflows but the examples I've found seem to be really over complicated, I was just hoping I can use a standard one like there is C# i.e
Code:
messagebox.show("message");
The smallest one (which i still cannot fathom out) is from Androids website about developer.android.com/guide/topics/ui/dialogs.html
But i don't know how I can encorperate that into 'blank' activity.
My Current Code:
Code:
package com.example.scramph.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Dialog;
import android.widget.Button;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
changeText(button);}});
messageBox("Text Here");
}
private void changeText(Button b){
if (b.getText() == "Hello")
{
b.setText("Good Bye");
}
else if (b.getText() == "Good Bye") {
b.setText("Hello");
}
else
{
b.setText("Hello");
}
}
// want a function to bring up a messagebox
private void messageBox(String s){
//messagebox.show(s);
}
}
Many thanks for any input!!
Sam

Help: Printing a custom EditText into listview

I do not really know how to finish this code?
All i want is to print whatever is entered within the editText to be listed in listview.
I am creating a dice game app, and within the xml part I have 1 edittext (in which you can type the name of the player), 1 button for adding another player. Basically every time some1 types in a name I want it to show up in the list once the button "add" is pressed. Likewise as more players are added the list should expand. Im using a lot of youtube examples, however simply do not know how to finish the code exactly.
Any help would be much appreciated
package nl.dut.ide.software.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class LoginPage extends AppCompatActivity {
EditText typeplayers;
Button submitbutton;
ListView list;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
typeplayers = (EditText)findViewById(R.id.edittext);
submitbutton = (Button)findViewById(R.id.Submitbutton);
list = (ListView)findViewById(R.id.list);
submitbutton.setOnClickListener(View.OnClickListener() {
@override
public void onClick (View, v){
String str = typeplayers.getText().toString();
list.add
}
}
}
}

How come Im getting the default value the first time running the app?

Im following the steps laid out here for using the Settings Activity Template and despite some changes (e.g. now a root_preferences.xml file gets created instead of multiple xml files for different preference screens when selecting the Settings Activity template) I pretty much have nailed down the steps very similarly.
It says towards the end:
The first time you run the app, you should see "-1" displayed in the Toast because you haven't changed the setting yet.
Click to expand...
Click to collapse
However, instead of -1, Im seeing US as the toast message. Im thinking thats because its the default value, but they also set the default value as the US, yet the expectation according to the instructions is -1 the first time they run the app...how come?
Here is my code and the result Im getting first time running the app
SettingsActivity.java:
package com.example.droidcafe;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent =
new Intent(MainActivity.this, OrderActivity.class);
intent.putExtra(EXTRA_MESSAGE, mOrderMessage);
startActivity(intent);
}
});
PreferenceManager.setDefaultValues(this,
R.xml.root_preferences, false);
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
String marketPref = sharedPref
.getString("market", "-1");
displayToast(marketPref);
}
root_preferences.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/pref_header_account">
<ListPreference
app:defaultValue="US"
app:entries="@array/pref_market_titles"
app:entryValues="@array/pref_market_values"
app:key="market"
app:negativeButtonText="@null"
app:positiveButtonText="@null"
app:title="@string/pref_title_account" />
</PreferenceCategory>
</PreferenceScreen>
strings.xml:
<string name="pref_header_account">Account</string>
<!-- Sync Preferences -->
<string name="pref_title_account">Market</string>
<string-array name="pref_market_titles">
<item>United States</item>
<item>Canada</item>
<item>United Kingdom</item>
<item>India</item>
<item>Japan</item>
<item>Other</item>
</string-array>
<string-array name="pref_market_values">
<item>US</item>
<item>CA</item>
<item>UK</item>
<item>IN</item>
<item>JA0</item>
<item>-1</item>
</string-array>
first time running app:
Expectation: -1
I realize the default value is US, but their codelab default is also US, yet the codelab says it should display first time -1.

Categories

Resources