I bought myself a android car unit and came at the conclusion that the minimum brightness is still to bright when driving in the night. There is a clever app called screen filter that (i think it works like this) uses a overlay over the screen to fake a screen dimming. I wanted to make this by myself because i want to enable it when it's sunset and disable it after sunrise.
After some searching in the web i found a usable code.
Create a Main activity with a service called Overlayservice. The service runs when i start the app and the overlay also works fine.
The next thing i want to make is a code so i can change the overlay transparency. I want that the program starts fading when sunset starts and for example after an half hour the transparency is 50%.
The problem i am facing at is i am not able to set a new colour and transparency while the overlay is active in a service.
What i tired was creating a timer in the service that sets the colour after 5 seconds but i got a crash with the error:
Only the original thread that created a view hierarchy can touch its views.
The code i now have is as following:
package erik.autostart;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.LinearLayout;
import java.util.Timer;
import java.util.TimerTask;
public class OverlayService extends Service {
String color;
LinearLayout oView;
WindowManager.LayoutParams localLayoutParams;
private static Timer timer = new Timer();
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.color = intent.getExtras().getString("color");
Log.v("Message","Intent: " + Color.parseColor(this.color));
oView = new LinearLayout(getBaseContext());
localLayoutParams = new WindowManager.LayoutParams();
oView.setBackgroundColor(Color.parseColor(this.color)); //De eerste 2 waardes zijn de density ff is volledig en 00 is weg de laatste 6 waardes zijn hex color waardes, kan dus zwart zijn.
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
localLayoutParams.gravity = Gravity.TOP;
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
// this is to enable the notification to recieve touch events
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
// Draws over status bar
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.format = PixelFormat.TRANSLUCENT;
manager.addView(oView, localLayoutParams);
timer.scheduleAtFixedRate(new Task(), 0, 500);
return START_STICKY;
}
private class Task extends TimerTask
{
public void run()
{
Log.v("Message", "Tasker");
runtask();
}
}
void runtask()
{
if(oView!=null){
oView.setBackgroundColor(Color.parseColor("#ff000000"));
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.updateViewLayout(oView, oView.getLayoutParams());
}
}
#Override
public void onCreate() {
super.onCreate();
Log.v("Message", "OverlayService started");
}
#Override
public void onDestroy() {
if(oView!=null){
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.removeView(oView);
}
Log.v("Message", "Destroying OverlayService");
super.onDestroy();
}
}
I want to run a tasker somewhere so i can set the new colour and update the overlay.
To fix this i thought perhaps stopping the service and starting it again with a new colour would help so i made a taker in the Mainactivity and stopped the service and start a new one with a different colour. The problem there is that the screen flickers.
I was hoping someone can help me with this problem. Is it even possible to do what i want?
The complete answer I promised earlier. I'm sorry for the untested code, I haven't done anything with Android development in about half a year and don't have the setup ready to test code.
That said, probably the best way is to use Handler. The Handler is initialized to be run on the main (UI) thread, so that it can modify UI. The Dimmer executes on the UI thread, thus preventing the problem you had.
...
public class OverlayService extends Service {
Handler handler;
...
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
manager.addView(oView, localLayoutParams);
handler.postDelayed(new Dimmer("#ff000000"), 500);
return START_STICKY;
}
private class Dimmer implements Runnable {
private String color;
public Dimmer (String color) {
this.color = color;
}
public void run() {
if(oView!=null){
oView.setBackgroundColor(Color.parseColor(color));
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.updateViewLayout(oView, oView.getLayoutParams());
}
}
}
#Override
public void onCreate() {
super.onCreate();
Log.v("Message", "OverlayService started");
handler = new Handler(Looper.getMainLooper());
}
...
}
Related
When I run my code below everything works fine. When I want to go back to the previous activity (using the emulator) I get a black screen and then the app shuts down. I also get a black screen when I exit the application and try to resume it.
The code:
package com.example.bono.as3;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class Main extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
#Override public void onResume(){
super.onResume();
drawView.resume();
}
#Override public void onPause(){
super.onPause();
drawView.pause();
}
public class DrawView extends SurfaceView implements Runnable{
Thread gameloop = new Thread();
SurfaceHolder surface;
volatile boolean running = false;
AssetManager assets = null;
BitmapFactory.Options options = null;
Bitmap incect[];
int frame = 0;
public DrawView(Context context){
super(context);
surface = getHolder();
assets = context.getAssets();
options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
incect = new Bitmap[2];
try {
for (int n = 0; n < incect.length; n++){
String filename = "incect"+Integer.toString(n+1)+".png";
InputStream istream = assets.open(filename);
incect[n] = BitmapFactory.decodeStream(istream,null,options);
istream.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
public void resume(){
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void pause(){
running = false;
while (true){
try {
gameloop.join();
}
catch (InterruptedException e){}
}
}
#Override public void run (){
while (running){
if (!surface.getSurface().isValid())
continue;
Canvas canvas = surface.lockCanvas();
canvas.drawColor(Color.rgb(85, 107, 47));
canvas.drawBitmap(incect[frame], 0, 0, null);
surface.unlockCanvasAndPost(canvas);
frame++;
if (frame > 1) frame = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
I dont get any error message in the log, what I do get is about 13 messages saying "suspending all threads took: X ms" so it has something to do with my gameloop Thread I think. Unfortunately I don't see what the problem is in my code...
If you need a context, use getApplicationContext() or Activity.this. (seems less buggy with my code)
While going back to a previously used activity, onCreate() is not called, only onResume(), so it might help if you move the following lines to there.
drawView = new DrawView(this);
setContentView(drawView);
Why use inner class at all? Activity is a class already. If you want to use the code multiple times, make it a class on its own.
This is what i use to navigate back. Maybe this is usefull for you 2!
Button backpressed = (Button) findViewById(R.id.btBack);
backpressed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onBackPressed();
}
});
The onBackPressed() is just a method that you can call if you want to return to the last page.
What it looks like for me:
I want to create a notification for my android app. I have it working fine when I run it with the rest of my code inside a class, everything executes when I click a button and the notification works fine. However, because there is a lot of work to be done, the application is running slowly when I click the button. To help this, I have separated the notification part into a class of it's own and I am running it on a different thread.
I do not have a lot of experience with threads, or notifications for that matter and I would appreciate some help with this problem. Should I be separating the notification part into a class of it's own?
HomeActivity class is where the thread gets called to start, using the start() method when the button is clicked:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import Model.Data;
public class HomeActivity extends FragmentActivity {
private com.atmlocator.hooper.kenneth.atmlocator.Notification n;
public void addListenerOnButton() {
locationSpinner = (Spinner) findViewById(R.id.spinner1);
options1Spinner = (Spinner) findViewById(R.id.spinner2);
options2Spinner = (Spinner) findViewById(R.id.spinner3);
Button locate = (Button) findViewById(R.id.locateBtn);
locate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = getApplicationContext();
String text = "Loading...";
//call notification thread here
n.start();
//rest of code here...
}
}
}
}
and then the Notification class is:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
public class Notification extends FragmentActivity implements Runnable {
private Thread t;
private String name;
Context context;
Notification(String name, Context c)
{
this.name = name;
this.context = c;
}
public void run()
{
// Intent is triggered if the notification is selected
Intent intent = new Intent(context, HomeActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, 0);
// Build notification
android.app.Notification not = new android.app.Notification.Builder(context)
.setContentTitle("Notification")
.setContentText("New email").setSmallIcon(R.drawable.atm)
.setContentIntent(pIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
not.flags |= android.app.Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, not);
}
public void start()
{
t = new Thread (this, name);
t.start ();
}
}
Should I be separating the notification part into a class of it's own?
There should not be any problem with this!
Also you should show your notification outside a thread.
You can use a handler instead to show notification instead of thread
like this :
}
....
// write this outside your code block
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
showNotification();
}
};
// call it like this instead of thread start
mHandler.sendEmptyMessage(0);
check this link for more info : https://developer.android.com/training/multiple-threads/communicate-ui.html
This will virtually always work:
public static void toast(final String text, final int length, final Context context) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, text, length).show();
}
});
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html
So I'm following the book Open GL ES 2 for Android by Kevin Brothaler and I'm trying out the first chapter's project, which is basically coloring the screen red. I set up by Samsung Galaxy Note 3 so I can debug my app on there, and also set up an emulator that uses the host GPU for rendering. Also, I forced GPU rendering on my phone. I copied the code he had exactly into my eclipse project. Here's the code for reference:
package com.firstopenglproject.android;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
//import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class FirstOpenGLProjectActivity extends Activity {
private static final String TAG = FirstOpenGLProjectActivity.class.getSimpleName();
private GLSurfaceView glSurfaceView;
private boolean rendererSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "Before calling super.onCreate()");
super.onCreate(savedInstanceState);
Log.d(TAG, "Before creating a new GLSurfaceView");
glSurfaceView = new GLSurfaceView(this);
Log.d(TAG, "Creating activity manager");
final ActivityManager activityManager =
(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
Log.d(TAG, "Creating configuration info");
final ConfigurationInfo configurationInfo =
activityManager.getDeviceConfigurationInfo();
Log.d(TAG, "Getting supportsEs2 boolean");
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
// || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
// && (Build.FINGERPRINT.startsWith("generic")
// || Build.FINGERPRINT.startsWith("unknown")
// || Build.MODEL.contains("google_sdk")
// || Build.MODEL.contains("Emulator")
// || Build.MODEL.contains("Android SDK built for x86")));
Log.d(TAG, "supportsEs2 = " + supportsEs2);
if (supportsEs2) {
// Request an OpenGLES2 compatible context
glSurfaceView.setEGLContextClientVersion(2);
glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
// Assign our renderer
glSurfaceView.setRenderer(new FirstOpenGLProjectRenderer());
rendererSet = true;
Toast.makeText(this, "Device supports OpenGL ES 2.0", Toast.LENGTH_LONG).show();
Log.d(TAG, "rendererSet is true");
} else {
Log.d(TAG, "OGLES2.0 not supported");
Toast.makeText(this, "This device does not support OpenGL ES 2.0", Toast.LENGTH_LONG).show();
return;
}
}
#Override
protected void onPause() {
super.onPause();
if (rendererSet) {
glSurfaceView.onPause();
}
}
#Override
protected void onResume() {
super.onResume();
if (rendererSet) {
glSurfaceView.onResume();
}
}
}
The logging tasks were ones that I added so that I can see whether the code is executing properly, and it is: I see all these log messages in LogCat. Here's the code for the renderer:
package com.firstopenglproject.android;
import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glViewport;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
public class FirstOpenGLProjectRenderer implements Renderer {
private static final String TAG = FirstOpenGLProjectRenderer.class.getSimpleName();
/*
* GLSurfaceView calls this when its time to draw a frame. We must
* draw something, even if its only to clear the screen. The rendering buffer
* will be swapped and displayed on the screen after this method returns,
* so if we don't draw anything, we'll probably get a bad flickering effect.
* */
#Override
public void onDrawFrame(GL10 arg0) {
// clear the rendering surface
glClear(GL_COLOR_BUFFER_BIT);
}
/*
* GLSurfaceView calls this after the surface is created and whenever the size has
* changed. A size change can occur when switcheing from portrait to landscape
* and vice versa.
*/
#Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
// set the openGL viewport to fill the entire surface
glViewport(0, 0, width, height);
}
/*
* GLSurfaceView calls this when the surface is created. This happens the first
* time our application is run, and it may also be called when the device wakes
* up or when the user switches back to our activity. In practice, this means that
* this method may be called multiple times while our application is still running.
*/
#Override
public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
}
}
As you can see, I only use 3 calls to static methods in the GLES20 package. When I run this app on my phone and on my emulator I get a blank screen: what is going on? I've been banging my head on the table for the last 2 hours about this, and this is as simple as it could possibly get. It's supposed to display a red screen. Thanks a bunch!
you are not setting the view in your OnCreate() method at the end of that method add:
setContentView(glSurfaceView);
alright so I'm new to programming for android, and I think I did something wrong, but I don't know what. I've looked at 3 different tutorials and my code seems to look like theirs. Can anyone tell me what I'm doing wrong? here is my src (altered from a android nehe tutorial).
package cypri.games;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
/**
* The initial Android Activity, setting and initiating
* the OpenGL ES Renderer Class #see Lesson02.java
*
* #author Savas Ziplies (nea/INsanityDesign)
*/
public class DGearActivity extends Activity {
/** The OpenGL View */
private GLSurfaceView glSurface;
DGear dGear = new DGear();
private static final String TAG = "DEBUG";
SensorManager sensorManager;
private final SensorEventListener sensorListener = new SensorEventListener(){
public void onSensorChanged(SensorEvent se) {
if (se.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
dGear.playerX = se.values[0];
Log.v(TAG, "se.values[0] =" + se.values[0]);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
/**
* Initiate the OpenGL View and set our own
* Renderer (#see Lesson02.java)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
//Create an Instance with this Activity
glSurface = new GLSurfaceView(this);
//Set our own Renderer
glSurface.setRenderer(dGear);
//Set the GLSurface as View to this Activity
setContentView(glSurface);
}
/**
* Remember to resume the glSurface
*/
#Override
protected void onResume() {
Log.v(TAG, "or");
super.onResume();
glSurface.onResume();
sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
}
/**
* Also pause the glSurface
*/
#Override
protected void onPause() {
super.onPause();
glSurface.onPause();
Log.v(TAG, "op");
sensorManager.unregisterListener(sensorListener);
}
}
Are you running this in the emulator or on an actual device?
If you're running it on an actual device are you sure it has a gyroscope? There are lots of different sensor types and the gyroscope is only one of them. It could very well be one of the others.
Instead of only writing to the log if it's a gyroscope type, try writing the name of the se.sensor when that event fires. That way you'll at least know the event is firing.