I keep getting this black screen when ever I open my app, the only way to get rid of it is to press the back button, then again go to the app. I was told by my friend that it is going into deadlock! but I do not think because when I checked the logcat it shows the below log messages.
View
private boolean mGameIsRunning;
public void surfaceCreated(SurfaceHolder holder) {
// Your own start method.
start();
}
public void start() {
if (!mGameIsRunning) {
thread.initLevel();
thread.setRunning(true);
thread.start();
mGameIsRunning = true;
} else {
thread.onResume();
thread.initLevel();
thread.setRunning(true);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "Surface is being destroyed");
// tell the thread to shut down and wait for it to finish
// this is a clean shutdown
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d(TAG, "Thread was shut down cleanly");
}
Thread
private Object mPauseLock = new Object();
private boolean mPaused;
#Override
public void run() {
Canvas canvas;
Log.d(TAG, "Starting game loop");
while (running) {
canvas = null;
// try locking the canvas for exclusive pixel editing
// in the surface
try {
canvas = this.mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder) {
mStartTime = System.currentTimeMillis();
mElapsedTime = System.currentTimeMillis() - mStartTime;
this.updateGame();
this.onDraw(canvas);
}
synchronized(mPauseLock){
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
}
}
}
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null) {
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
} // end finally
}
}
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
Log
07-08 17:24:41.735: DEBUG/Hitman(3221): View added
07-08 17:24:41.895: DEBUG/(3221): Enemies Spawed
07-08 17:24:41.934: DEBUG/(3221): Starting game loop
07-08 17:24:42.165: INFO/ActivityManager(66): Displayed activity com.android.hitmanassault/.Hitman: 1384 ms (total 1384 ms)
07-08 17:24:46.164: DEBUG/(3221): Enemies Spawed
07-08 17:24:48.914: INFO/ActivityManager(66): Start proc com.android.settings for broadcast com.android.settings/.widget.SettingsAppWidgetProvider: pid=3228 uid=1000 gids={3002, 3001, 3003}
07-08 17:24:48.914: INFO/ActivityManager(66): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher/.Launcher }
07-08 17:24:48.924: DEBUG/PhoneWindow(3221): couldn't save which view has focus because the focused view com.android.hitmanassault.HitmanView#44d99528 has no id.
07-08 17:24:48.954: INFO/WindowManager(66): Setting rotation to 0, animFlags=0
07-08 17:24:49.014: INFO/ActivityManager(66): Config changed: { scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=34}
07-08 17:24:49.275: DEBUG/(3221): Surface is being destroyed
07-08 17:24:49.285: DEBUG/(3221): Thread was shut down cleanly
07-08 17:24:49.694: DEBUG/ddm-heap(3228): Got feature list request
07-08 17:24:49.754: WARN/IInputConnectionWrapper(3221): showStatusIcon on inactive InputConnection
07-08 17:24:51.315: DEBUG/dalvikvm(66): GC freed 2325 objects / 114696 bytes in 122ms
07-08 17:24:58.234: INFO/ActivityManager(66): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.hitmanassault/.HitmanTitle }
07-08 17:24:58.284: INFO/WindowManager(66): Setting rotation to 1, animFlags=0
07-08 17:24:58.354: INFO/ActivityManager(66): Config changed: { scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=2 layout=34}
07-08 17:24:58.554: DEBUG/(3221): Enemies Spawed
07-08 17:24:58.945: WARN/IInputConnectionWrapper(144): showStatusIcon on inactive InputConnection
07-08 17:25:00.604: DEBUG/dalvikvm(66): GC freed 1403 objects / 71832 bytes in 103ms
Activity Class:
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu_restart:
startActivity(new Intent(this, Hitman.class));
return true;
case R.id.menu_scores:
startActivity(new Intent(this, HitmanScores.class));
return true;
case R.id.menu_help:
startActivity(new Intent(this, HitmanHelp.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CanvasSurfaceView(this));
Log.d(TAG, "View added");
}
Does rotating the display cause it to refresh (in emulator: CTRL+F12)? If so then you have to override onResume() in your activity and have it restart whatever it is you set up that might not be being called. It could be that you just need to call view.invalidate() from the activity onResume()? You don't show code from your activity so I'm unsure.
In the code I saw, you should use this.postInvalidate() (same as invalidate() but for from a different thread) instead of this.onDraw(canvas) and have it call this.onDraw() on its own in the UI thread, as opposed to in your thread.
Where do you initialize your thread? Try doing so in surfaceCreated( ) instead of the surfaceView consturctor (which is where I think you did it..)
public void surfaceCreated(SurfaceHolder holder) {
// Restart draw thread
Thread.State state = thread.getState();
if(state == Thread.State.TERMINATED)
thread = new MyThread(getHolder(), getContext());
thread.setRunning(true);
thread.start();
}
Related
I've an streaming audio (from a server) with Media Player. It works when I turn off the screen and the system goes to sleep mode but after some minutes the phone stop music. This doesn't happen when the cellphone is connected to power (USB cable). So, the system must crash the app due to a power management or a memory management.
Service class:
public class MyService extends Service {
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
WifiManager.WifiLock wifiLock;
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Lock");
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wakeLock.acquire();
wifiLock.acquire();
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource("http://mediacontrol.jargon.com.ar:8168/;");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
wakeLock.release();
wifiLock.release();
}
}
And this is the class that implements the service:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setRetainInstance(true); // con esto retenemos los valores pero se elimina el view
View view = inflater.inflate(R.layout.fragment_blank_fragment4, container, false);
play = (ImageButton) view.findViewById(R.id.imageButton);
imagen=(ImageView) view.findViewById((R.id.imageView));
if(comenzar) {
play.setImageResource(R.drawable.play);
}
else {
play.setImageResource(R.drawable.stop);
}
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (comenzar) {
if(isConnectedMobile(getActivity())||
isConnectedWifi(getActivity())) {
play.setImageResource(R.drawable.stop);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getActivity().startService(new Intent(getActivity(), MyService.class));
showNotification();
comenzar = false;
release=true;
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No hay conexión a internet");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
} else {
play.setImageResource(R.drawable.play);
getActivity().stopService(new Intent(getActivity(), MyService.class));
comenzar = true;
NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
release=false;
}
}
});
return view;
}
I also set this permission in the manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
I can't debug it so well because the problem happens when the mobile is not connected but when the audio crash, then I connect it and it runs a one second more when I turn on the screen and after it stops.
I get this:
09-24 18:14:21.480 8539-8539/jaodev.utnfrp W/MediaPlayer: mediaplayer went away with unhandled events
09-24 18:14:24.070 8539-8551/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:14:24.970 8539-8539/jaodev.utnfrp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
09-24 18:17:57.413 8539-8552/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:18:30.437 8539-8551/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:18:34.187 8539-9040/jaodev.utnfrp W/MediaPlayer: info/warning (703, 0)
09-24 18:18:34.188 8539-9040/jaodev.utnfrp W/MediaPlayer: info/warning (701, 0)
09-24 18:19:03.462 8539-9040/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:19:03.941 8539-9040/jaodev.utnfrp W/MediaHTTPConnection: readAt 1507328 / 32768 => java.net.ProtocolException
09-24 18:19:04.202 8539-8551/jaodev.utnfrp W/MediaPlayer: info/warning (703, 0)
09-24 18:21:51.201 8539-8544/jaodev.utnfrp I/art: Do partial code cache collection, code=40KB, data=62KB
09-24 18:21:51.203 8539-8544/jaodev.utnfrp I/art: After code cache collection, code=40KB, data=62KB
Increasing code cache capacity to 256KB
I'm using two activities, the main one, and the camera one. In the mainActivity i call startActivity(new Intent(this, CameraActivity));
Now, when camera activity starts, the onCreate() is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
View myView= (View) findViewById(R.id.camera_previeww);
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
cameraID= Camera.CameraInfo.CAMERA_FACING_FRONT;
mCamera=openCamera(cameraID);
mCamera.startPreview();
IntentFilter filter = new IntentFilter();
filter.addAction(Tabbed.BROADCAST_ACTION_TABBED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(this);
bm.registerReceiver(mBroadcastReceiver, filter);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) this.findViewById(R.id.camera_previeww);
preview.addView(mPreview);
}
The openCamera(int cameraID) method is:
public Camera openCamera(int cameraIDD){
Camera c=null;
try{
c=Camera.open(cameraIDD);
}catch (Exception e){
Log.d("Camera Activity", e.getMessage());
}
return c;
}
Also I'm using a BroadcastReceiver like:
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte [] data=new byte[3];
if (intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
}
if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==SINGLE_TAP){
//switchCamera();
//releaseCamera();
//mCamera=Camera.open();
}
else if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==DOUBLE_TAP){
// HAVE TO GO BACK
kill_activity();
}
else if (data[FINGER]==INDEX_FINGER && data[TYPE]==SINGLE_TAP){
mCamera.takePicture(null, null, mPicture);
}
// kill activity
}
};
And some other methods:
#Override
protected void onPause() {
super.onPause();
//releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
void kill_activity()
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
releaseCamera();
finish();
}
Here is the crash:
FATAL EXCEPTION: main
Process: com.etu.goglove, PID: 6008
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.takePicture(android.hardware.Camera$ShutterCallback, android.hardware.Camera$PictureCallback, android.hardware.Camera$PictureCallback)' on a null object reference
at com.etu.goglove.CameraActivity$2.onReceive(CameraActivity.java:155)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
With all this, I'm trying to take a photo when I receive broadcast intents. So, after my activity has started, I open mCamera and when I receive an intent I make the photo or I get back. At the first time, i can take the photo and then I finish my activity. If i try to restart cameraActivity from the mainActivity, calling startActivity(intent),in the onCreate() camera is open and it is not null (checked with the debugger), but this time, when I get in the onReceive() method, mCamera is always null, so I get a null object reference on mCamera!(when I'm trying to do mCamera.takePicture()) don't know how ...
Thanks!
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte [] data=new byte[3];
if (intent!=null && intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==SINGLE_TAP){
//switchCamera();
//releaseCamera();
//mCamera=Camera.open();
}
else if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==DOUBLE_TAP){
// HAVE TO GO BACK
kill_activity();
}
else if (data[FINGER]==INDEX_FINGER && data[TYPE]==SINGLE_TAP){
mCamera.takePicture(null, null, mPicture);
}
}
// kill activity
}
};
I want to make an app that takes a picture with the device's camera, saves the image in the internal memory, and then displays that image in the next Activity. The preview works perfectly, but when I hit the Capture button the app goes to the next activity and only shows a blank white screen. Maybe I'm not writing or reading the file correctly?
Here is the Main Activity:
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "File_name";
private Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
//////////////////////
public void sendInfo(String pathway) {
Intent intent = new Intent(this, show_image.class);
intent.putExtra(EXTRA_MESSAGE,pathway);
startActivity(intent);
}
/////////////////
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data , Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"pic.jpg");
FileOutputStream fos = null;
if (directory == null){
Log.d("Logtag", "Error creating media file, check storage permissions: ");
return;
}
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
String path = directory.getAbsolutePath();
sendInfo(path);
} catch (FileNotFoundException e) {
Log.d("Logtag", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Logtag", "Error accessing file: " + e.getMessage());
}
}
};
#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);
}
/**
* A safe way to get an instance of the Camera object.
*/
public Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
Toast.makeText(getApplicationContext(), "Camera is not available (in use or does not exist)",
Toast.LENGTH_LONG).show();
}
return c; // returns null if camera is unavailable
}
}
Here is the Second activity that is supposed to display the image that was just taken:
public class show_image extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String path = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
try {
File f = new File(path, "pic.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img= new ImageView(this);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static Bitmap decodeFile(File f, final int maxSize) {
Bitmap b = null;
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > maxSize || o.outWidth > maxSize) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(maxSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
} catch (Exception e) {
Log.e("Logtag", "Error processing bitmap", e);
} finally {
//FileUtil.closeQuietly(fis);
}
return b;
}
#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);
}
}
The LogCat from Android Studio:
02-25 12:32:49.389 17041-17041/edu.ramapo.camer I/System.out﹕ debugger has settled (1496)
02-25 12:32:49.620 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
02-25 12:32:49.620 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 11360: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
02-25 12:32:49.620 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
02-25 12:32:49.620 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
02-25 12:32:49.620 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 11366: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
02-25 12:32:49.620 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
02-25 12:32:49.630 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
02-25 12:32:49.630 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 9050: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
02-25 12:32:49.630 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
02-25 12:32:49.660 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method
android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
02-25 12:32:49.660 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 367: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
02-25 12:32:49.660 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
02-25 12:32:49.670 17041-17041/edu.ramapo.camer I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
02-25 12:32:49.670 17041-17041/edu.ramapo.camer W/dalvikvm﹕ VFY: unable to resolve virtual method 389: Landroid/content/res/TypedArray;.getType (I)I
02-25 12:32:49.670 17041-17041/edu.ramapo.camer D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
02-25 12:32:50.611 17041-17041/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libEGL_adreno200.so
02-25 12:32:50.621 17041-17041/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-25 12:32:50.621 17041-17041/edu.ramapo.camer D/libEGL﹕ loaded /system/lib/egl/libGLESv2_adreno200.so
02-25 12:32:50.631 17041-17041/edu.ramapo.camer I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM build: HAREESHG_Nondeterministic_AU+PATCH[ES]_msm8960_JB_1.9.6_MR2_CL3219408_release_ENGG (CL3219408)
Build Date: 09/28/13 Sat
Local Branch: hhh
Remote Branch: quic/jb_1.9.6_1
Local Patches: 8d50ec23e42ef52b570aa6ff1650afac0b503d78 CL3219408: Fix in the Glreadpixels for negative offsets and larger dimensions.
801859126f6ca69482b39a34ca61447e3f7cded8 rb: fix panel settings to clear undrawn/undefined buffers
Reconstruct Branch: LOCAL_PATCH[ES]
02-25 12:32:50.991 17041-17041/edu.ramapo.camer D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 12:32:51.552 17041-17041/edu.ramapo.camer I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-25 12:32:56.037 17041-17047/edu.ramapo.camer D/dalvikvm﹕ Debugger has detached; object registry had 4113 entries
02-25 12:33:18.651 17041-17041/edu.ramapo.camer D/dalvikvm﹕ GC_FOR_ALLOC freed 694K, 38% free 12155K/19420K, paused 29ms, total 32ms
02-25 12:33:18.771 17041-17041/edu.ramapo.camer I/dalvikvm-heap﹕ Grow heap (frag case) to 45.705MB for 31961104-byte allocation
02-25 12:33:24.507 17041-17041/edu.ramapo.camer D/dalvikvm﹕ GC_FOR_ALLOC freed 31627K, 40% free 11825K/19424K, paused 30ms, total 30ms
02-25 12:33:24.587 17041-17041/edu.ramapo.camer I/dalvikvm-heap﹕ Grow heap (frag case) to 45.382MB for 31961104-byte allocation
Well right now I made a copy of the app I sent you the link already here is the code:
public class GlassARTest extends FragmentActivity {
private static final String TAG = "CameraActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
private Camera mCamera;
private CameraPreview mPreview;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mContext = this;
if(checkCameraHardware(mContext)){
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
return pictureFile.getPath();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
return null;
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
Intent intent = new Intent(mContext, ImageDisplayActivity.class);
intent.putExtra(ImageDisplayActivity.KEY_PATH, result);
startActivity(intent);
}
}
}.execute();
}
};
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
} private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
and the other Activity:
public class ImageDisplayActivity extends FragmentActivity{
public static final String KEY_PATH = "path";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
final ImageView imageDisplay = (ImageView)findViewById(R.id.image_displayer);
final Bundle extras = getIntent().getExtras();
if(extras != null){
final String path = extras.getString(KEY_PATH);
File imgFile = new File(path);
Bitmap bitmap = decodeFile(imgFile);
imageDisplay.setImageBitmap(bitmap);
}
}
private Bitmap decodeFile(File f){
Bitmap b = null;
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > 50 || o.outWidth > 50) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(50 / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (IOException e) {
}
return b;
}
}
this code worked showing a pixelated image of what I took picture of (as I'm just decoding it in low quality for testing purposes).
I hope this help you.
Please scroll down to the "EDIT" :)
I'm trying to understand some basic android animation programming using Android Studio, and I have followed some tutorials on the internet.
I already know some basic java programming, but I have a problem with my "copy/paste app" I made.
This is my MainActivity:
public class MainActivity extends ActionBarActivity {
private Button play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button) findViewById(R.id.play_button);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent startGame = new Intent("com.abc.test.DRAWGAME2");
startActivity(startGame);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
This is DrawGame2.java:
public class DrawGame2 extends Activity implements View.OnTouchListener {
private MyView surfaceView;
private float y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
surfaceView = new MyView(this);
surfaceView.setOnTouchListener(this);
setContentView(surfaceView);
}
#Override
protected void onPause() {
super.onPause();
surfaceView.pause();
}
#Override
protected void onResume() {
super.onResume();
surfaceView.resume();
}
#Override
public boolean onTouch(View v, MotionEvent me) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (me.getAction()){
case MotionEvent.ACTION_DOWN:
y = me.getY();
break;
case MotionEvent.ACTION_UP:
y = me.getY();
break;
case MotionEvent.ACTION_MOVE:
y = me.getY();
break;
}
return true;
}
public class MyView extends SurfaceView implements Runnable {
private Thread thread = null;
private SurfaceHolder holder;
private boolean isRunning = false;
public MyView(Context context) {
super(context);
holder = getHolder();
y = 0;
}
public void run() {
while (isRunning) {
if (!holder.getSurface().isValid()) {
continue;
}
Canvas canvas = holder.lockCanvas();
canvas.drawRGB(02,02,150);
if (y != 0){
Bitmap test = BitmapFactory.decodeResource(getResources(),R.drawable.greenball);
canvas.drawBitmap(test, canvas.getWidth()/2 - test.getWidth()/2, y, null);
}
holder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
isRunning = false;
while (true) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
thread = null;
}
public void resume() {
isRunning = true;
thread = new Thread(this);
thread.start();
}
}}
Logcat:
02-12 11:01:06.676 1972-1972/com.abc.test I/art﹕ Not late-enabling -Xcheck:jni (already on)
02-12 11:01:06.881 1972-1990/com.abc.test D/OpenGLRenderer﹕ Render dirty regions requested: true
02-12 11:01:06.882 1972-1972/com.abc.test D/﹕ HostConnection::get() New Host Connection established 0xa686fb60, tid 1972
02-12 11:01:06.917 1972-1972/com.abc.test D/Atlas﹕ Validating map...
02-12 11:01:07.007 1972-1990/com.abc.test D/﹕ HostConnection::get() New Host Connection established 0xa686fd90, tid 1990
02-12 11:01:07.037 1972-1990/com.abc.test I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-12 11:01:07.102 1972-1990/com.abc.test D/OpenGLRenderer﹕ Enabling debug mode 0
02-12 11:01:07.126 1972-1990/com.abc.test W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-12 11:01:07.126 1972-1990/com.abc.test W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6814940, error=EGL_SUCCESS
02-12 11:01:07.705 1972-1990/com.abc.test W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-12 11:01:07.705 1972-1990/com.abc.test W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6814940, error=EGL_SUCCESS
02-12 11:01:12.571 1972-1990/com.abc.test W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-12 11:01:12.571 1972-1990/com.abc.test W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5a69ba0, error=EGL_SUCCESS
02-12 11:01:16.892 1972-1972/com.abc.test I/Choreographer﹕ Skipped 263 frames! The application may be doing too much work on its main thread.
02-12 11:01:16.899 1972-2270/com.abc.test D/﹕ HostConnection::get() New Host Connection established 0xa5dfcc10, tid 2270
The problem with this app is that the animation is really laggy, and I can't figure out why!
I have tried to make the same animation with a simple rectangle, but the lag is still there.
The problem isn't the OnTouchListener, because I've tried to just increase the y value by 1 with each loop in the run method (while disabling the OnTouchListener), but it is still lagging.
I have tried with different emulators (Lollipop, Kitkat) and on my Samsung Galaxy S3 (Jelly Bean).
Are there any wise people out there that can help me with this problem? :)
Have a great day!
EDIT:
Okay, so I applied the answers I got, and now it runs smoothly, ON MY Samung Galaxy S3!
The lagging is still there on my emulator though. I've installed HAXM and the emulator runs smoothly out of the app I've created, but as soon as I launch the app and press the "PLAY" button, the animation lags when I interact with the app.
This is the properties for my emulator:
Name: Nexus_5_API_21
CPU/ABI: Intel Atom (x86)
hw.gpu.enabled: yes
Path: C:\Users\User\.android\avd\Nexus_5_API_21.avd
Target: Android 5.0.1 (API level 21)
Skin: nexus_5
SD Card: 100M
Snapshot: no
hw.lcd.density: 480
hw.dPad: no
avd.ini.encoding: UTF-8
hw.camera.back: none
disk.dataPartition.size: 200M
runtime.network.latency: none
skin.dynamic: no
hw.keyboard: yes
runtime.network.speed: full
hw.device.hash2: MD5:2fa0e16c8cceb7d385183284107c0c88
hw.ramSize: 1536
tag.id: default
tag.display: Default
hw.sdCard: yes
hw.device.manufacturer: Google
hw.mainKeys: no
hw.accelerometer: yes
hw.trackBall: no
hw.device.name: Nexus 5
hw.sensors.proximity: yes
hw.battery: yes
AvdId: Nexus_5_API_21
hw.sensors.orientation: yes
hw.audioInput: yes
hw.camera.front: none
hw.gps: yes
avd.ini.displayname: Nexus 5 API 21
snapshot.present: no
vm.heapSize: 64
runtime.scalefactor: auto
As far as I can see, your problem is in the onTouch() method, in which you have this code:
try{
Thread.sleep(50);
}catch (InterruptedException e){
e.printStackTrace();
}
Which will sleep the MAIN thread, meaning that everything will make the entire application hold up for 50 milliseconds.
So try to remove that.
Decoding resources are also not performance friendly. You should decode bitmap earlier and reuse it while drawing. Why you do not use onDraw method ?
I've been struggling with this exception and I've looked around but there's nothing to help me.
Here's the code
package com.example.surfacetest;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface.OutOfResourcesException;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class BoardSurfaceActivity extends Activity {
/** Called when the activity is first created. */
private static final String TAG = BoardSurfaceActivity.class.getSimpleName();
private BoardSurface bS;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bS = new BoardSurface(this);
setContentView(bS);
Log.d(TAG, "View added");
}
#Override
protected void onDestroy() {
Log.d(TAG, "Destroying...");
super.onDestroy();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopping...");
super.onStop();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
#Override
protected void onPause() {
Log.d(TAG, "Pausing...");
super.onPause();
}
#Override
protected void onResume() {
Log.d(TAG, "Resuming...");
super.onResume();
}
public class BoardSurface extends SurfaceView implements SurfaceHolder.Callback, Runnable {
final String TAG = BoardSurface.class.getSimpleName();
private Stuff stuff;
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false;
public BoardSurface(Context context) {
super(context);
holder = getHolder();
getHolder().addCallback(this);
stuff = new Stuff(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher), 50, 50);
t = new Thread(this);
setFocusable(true);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "Surface created");
resume();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "Surface Destroyed");
pause();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// delegating event handling to the droid
stuff.handleActionDown((int) event.getX(), (int) event.getY());
// check if in the lower part of the screen we exit
if (event.getY() > getHeight() - 50) {
((Activity) getContext()).finish();
} else {
Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
}
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
// the gestures
if (stuff.isTouched()) {
// the droid was picked up and is being dragged
stuff.setX((int) event.getX());
stuff.setY((int) event.getY());
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
// touch was released
if (stuff.isTouched()) {
stuff.setTouched(false);
}
}
return true;
}
public void draw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
stuff.draw(canvas);
}
#Override
public void run() {
while (isItOk) {
holder = getHolder();
if (holder.getSurface().isValid()) {
Canvas c = null;
try {
// make sure holder is updated
c = holder.lockCanvas(null);
if (c != null) {
synchronized (holder) {
draw(c);
}
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
}
}
}
public void pause() {
isItOk = false;
while (true) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
t = null;
}
public void resume() {
if (t.getState() == Thread.State.TERMINATED) {
t = new Thread(this);
isItOk = true;
t.start();
} else {
isItOk = true;
t.start();
}
}
}
}
What is super strange is that I have this trace :
10-22 08:54:41.153: D/BoardSurface(17298): Surface created
10-22 08:54:41.394: E/memalloc(17298): /dev/pmem: Failed to map buffer size:24641536 offset:23699456 fd:56 Error: Invalid argument
10-22 08:54:41.394: E/gralloc(17298): Could not mmap handle 0x89e2b8, fd=56 (Invalid argument)
10-22 08:54:41.394: E/gralloc(17298): gralloc_register_buffer: gralloc_map failed
10-22 08:54:41.394: W/GraphicBufferMapper(17298): registerBuffer(0x89e2b8) failed -22 (Invalid argument)
10-22 08:54:41.394: E/GraphicBuffer(17298): unflatten: registerBuffer failed: Invalid argument (-22)
10-22 08:54:41.394: E/memalloc(17298): /dev/pmem: Failed to map buffer size:24641536 offset:23699456 fd:56 Error: Invalid argument
10-22 08:54:41.394: E/gralloc(17298): Could not mmap handle 0x89e2b8, fd=56 (Invalid argument)
10-22 08:54:41.394: E/libgenlock(17298): perform_lock_unlock_operation: GENLOCK_IOC_DREADLOCK failed (lockType0x1,err=Bad file number fd=56)
10-22 08:54:41.394: E/gralloc(17298): gralloc_lock: genlock_lock_buffer (lockType=0x2) failed
10-22 08:54:41.394: W/GraphicBufferMapper(17298): lock(...) failed -22 (Invalid argument)
10-22 08:54:41.394: W/Surface(17298): failed locking buffer (handle = 0x89e2b8)
10-22 08:54:41.424: E/SurfaceHolder(17298): Exception locking surface
10-22 08:54:41.424: E/SurfaceHolder(17298): java.lang.IllegalArgumentException
10-22 08:54:41.424: E/SurfaceHolder(17298): at android.view.Surface.nativeLockCanvas(Native Method)
10-22 08:54:41.424: E/SurfaceHolder(17298): at android.view.Surface.lockCanvas(Surface.java:236)
10-22 08:54:41.424: E/SurfaceHolder(17298): at android.view.SurfaceView$4.internalLockCanvas(SurfaceView.java:807)
10-22 08:54:41.424: E/SurfaceHolder(17298): at android.view.SurfaceView$4.lockCanvas(SurfaceView.java:787)
10-22 08:54:41.424: E/SurfaceHolder(17298): at com.example.surfacetest.BoardSurfaceActivity$BoardSurface.run(BoardSurfaceActivity.java:137)
10-22 08:54:41.424: E/SurfaceHolder(17298): at java.lang.Thread.run(Thread.java:841)
in my running loop.
But here's the tricky part ! When I press back (not HOME) then start the app from the menu again. It just simply works.
So I really don't know what I'm missing.
Additional info : I'm running on a HTC Sensation XE, CM 10.2 (Android 4.3.1)
EDIT:
The device is not the issue here. Tried with another HTC on stock ROM.
EDIT 2 :
Even though I check :
if (holder.getSurface().isValid())
Which is specifically saying that lockcanvas() will succeed if it is true, I get this exception
10-22 10:11:27.688: E/SurfaceHolder(22195): Exception locking surface
10-22 10:11:27.688: E/SurfaceHolder(22195): java.lang.IllegalArgumentException
10-22 10:11:27.688: E/SurfaceHolder(22195): at android.view.Surface.nativeLockCanvas(Native Method)
10-22 10:11:27.688: E/SurfaceHolder(22195): at android.view.Surface.lockCanvas(Surface.java:236)
10-22 10:11:27.688: E/SurfaceHolder(22195): at android.view.SurfaceView$4.internalLockCanvas(SurfaceView.java:807)
10-22 10:11:27.688: E/SurfaceHolder(22195): at android.view.SurfaceView$4.lockCanvas(SurfaceView.java:787)
10-22 10:11:27.688: E/SurfaceHolder(22195): at com.example.surfacetest.BoardSurfaceActivity$BoardSurface.run(BoardSurfaceActivity.java:144)
10-22 10:11:27.688: E/SurfaceHolder(22195): at java.lang.Thread.run(Thread.java:841)
EDIT 3 :
Works on Galaxy S4 Stock ROM and Emulator Intelx86 4.2.2
#CinetiK: Post the rest of your stacktrace.
HTC devices are notorious when it comes to rotation and surface tests. Have you tried this:
Restart your phone.
Go to Safe mode (i.e. restart the phone and when you see the HTC logo, long press Volume down button). The phone will restart again and go into Safe mode.
Once phone is in Safe mode, go to Settings | Display & Gestures | G-Sensor Calibration. Then, calibrate your phone while ensuring your phone rests on a flat surface. Once calibration is successfully completed, restart the phone in normal mode.
If the above steps still do not fix the error, and since you're using CM 10.2, I would recommend testing your Android app on stock ROMs first. While I have nothing against custom Android ROMs (I used them myself), from experience I have had more unexplained errors on custom ROMs than stock ROMs. Try a stock ROM first and see if you still get the same error.