Adding TextureView to main.xml: Android - java

I'm trying to capture an image using TextureView, but the main.xml file is overridden by TextureView, and hence I cannot see the contents of the main.xml file. I'm trying to add TextureView into main.xml. Please give suggestions about how to improve my code.
Java:
public class MainActivity extends Activity implements TextureView.SurfaceTextureListener {
private Camera mCamera;
private TextureView mTextureView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextureView = (TextureView) findViewById(R.id.textureView1);
mTextureView = new TextureView(this);
mTextureView.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mCamera = Camera.open(0);
try {
mCamera.setPreviewTexture(surface);
}
catch(IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
mCamera.stopPreview();
mCamera.release();
return true;
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
}
}
Layout resource XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<TextureView
android:id="#+id/textureView1"
android:layout_width="350dp"
android:layout_height="350dp"
android:layout_below="#+id/textView1" />

I dont understand you question.
You say you want to add a TextureView to your activity_main.xml layout. but it is already there.
Obviously if you use setContentView(mTextureView); after setContentView(R.layout.activity_main); the entire layout will be gone. You are setting the activity content to a single view instead of the entire layout.
You are also creating a new TextureView and not using the one on the activity_main layout.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextureView = (TextureView)findViewById(R.id.textureView1);
mTextureView.setSurfaceTextureListener(this);
}
I think you should be doing something like this. I never tested this though.
It seems that you are trying to make a camera preview with the TextureView, there is a good example here, and a more advanced version here.

Check this code this is working for me.
MainActivity.java.
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.View;
import android.widget.FrameLayout;
public class MainActivity extends Activity implements SurfaceTextureListener {
private TextureView myTexture;
private Camera mCamera;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTexture = new TextureView(this);
myTexture.setSurfaceTextureListener(this);
setContentView(myTexture);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi")
#Override
public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1,
int arg2) {
mCamera = Camera.open();
Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
myTexture.setLayoutParams(new FrameLayout.LayoutParams(
previewSize.width, previewSize.height, Gravity.CENTER));
try {
mCamera.setPreviewTexture(arg0);
} catch (IOException t) {
}
mCamera.startPreview();
myTexture.setAlpha(1.0f);
myTexture.setRotation(90.0f);
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
mCamera.stopPreview();
mCamera.release();
return true;
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,
int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextureView
android:id="#+id/textureView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.textureview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.textureview.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Related

the following code should turn on the camera and record video on my android phone. However, nothing happens. Anybody spot any errors in my code?

I have used this code to create (trying) an app that opens its camera and starts recording videos, whether front or back, doesn't matter. But what ever i have tried i cannot seem to get it to work. When i press the button, nothing happens, no crash, no new view. I am not sure what the problem is.
package com.example.mediaworld;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
//private button stopRecording;
File video;
private Camera mCamera;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(null, "Video starting");
startRecording = (Button)findViewById(R.id.buttonstart);
mCamera = Camera.open();
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
menu.add(0,0,0, "StartRecording");
menu.add(0,1,0, "StopRecording");
return super.onCreateOptionsMenu(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();
//if (id == R.id.action_settings) {
// return true;
//}
switch(item.getItemId()){
case 0: try{
startRecording();
}catch(Exception e){
String message = e.getMessage();
Log.i(null, "problem Start" + message);
mrec.release();
}
break;
case 1:
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException{
mrec = new MediaRecorder();
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz/3gp");
mrec.prepare();
mrec.start();
}
protected void stopRecording(){
mrec.stop();
mrec.release();
mCamera.release();
}
private void releaseMediaRecorder(){
if(mrec != null){
mrec.reset();
mrec.release();
mrec = null;
mCamera.lock();
}
}
private void releaseCamera(){
if(mCamera != null){
mCamera.release();
mCamera = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
if(mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}else{
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCamera.stopPreview();
mCamera.release();
}
}
And here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mediaworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name= "android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
AND here is the xml file for main activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mediaworld.MainActivity" >
<SurfaceView
android:id="#+id/surfaceView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="#+id/buttonstart"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:text="Start Rec" />
</LinearLayout>
I think you forgot to register an "onClickListener" with your button:
startRecording.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startRecording();
}
});

Why is the set of listeners empty when I need them to be notified? (in an Android app)

In my Android app I have three classes, one is the MainActivity another one is called CustomerTransaction, which is just a Java class. There is also another activity called DataActivity which starts when the button Enter Data on the MainActivity screen is clicked. The activity DataActivity allows the user to enter a number in an EditText and then click the Send button to trigger a method in CustomerTransaction. I shall add the complete code below. But first let me explain my problem. In CustomerTransaction I have a method that provides values for two variables: totalAmount and transactionType (both are int). This values are needed in the MainActivity to be displayed on the main screen, when they are available. The MainActivity implements an interface called CustomListeners containing the header of the function that displays the two values (in TextViews). The values are communicated from CustomerTransaction to the method in MainActivity by notifying the listener when the values are available. The problem is that when I have the values, the set of listeners is empty. I would like to understand why this happens and then to correct the code.
Here's the code:
package com.example.customlistenertest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements CustomListeners {
TextView tv_amount;
TextView tv_transactionType;
Button btn_enterData;
CustomerTransaction control= new CustomerTransaction();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
control.registerListener(this);
tv_amount = (TextView) findViewById(R.id.textView_amount);
tv_transactionType = (TextView) findViewById(R.id.textView_transactionType);
btn_enterData = (Button) findViewById(R.id.button_enterData);
addListenerOnButtonEnterData();
}
public void addListenerOnButtonEnterData() {
btn_enterData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent =
new Intent(MainActivity.this,com.example.customlistenertest.DataActivity.class);
startActivity(intent);
}
});
}
public void updateTotal(final int transactionType, final int totalAmount) {
runOnUiThread(new Runnable() {
public void run() {
tv_amount.setText(Integer.toString(totalAmount));
tv_transactionType.setText(Integer.toString(transactionType));
}});
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume(){
super.onResume();
control.registerListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
control.unregisterListener(this);
}
} // End MainActivity
Following is the code for the DataActivity class:
package com.example.customlistenertest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DataActivity extends Activity {
TextView tv_enterNumber;
EditText et_number;
Button btn_send;
CustomerTransaction transaction;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_data);
btn_send = (Button) findViewById(R.id.button_send);
et_number = (EditText) findViewById(R.id.editText_number);
}
public void send(View view) {
transaction = new CustomerTransaction();
transComplete();
}
private void transComplete() {
new Thread("TransComplete") {
public void run() {
String s_number = et_number.getText().toString();
int value = Integer.parseInt(s_number);
transaction.setState(5, value);
finish();
}
}.start();
}
} // end DataActivity
Following is the code for the CustomerTransaction class:
package com.example.customlistenertest;
import java.util.HashSet;
import java.util.Set;
public class CustomerTransaction {
public static final int DATA_ENTERED = 1;
public static final int TRANSACTION_COMPLETE = 5;
private int state;
private int totalAmount;
private int transactionType;
public Set<CustomListeners> listeners = new HashSet<CustomListeners>();
public synchronized void registerListener(CustomListeners listener) {
listeners.add(listener);
}
public synchronized void unregisterListener(CustomListeners listener) {
listeners.remove(listener);
}
public synchronized void notifyListeners() {
for(CustomListeners listener : listeners) {
if (totalAmount != 0)
listener.updateTotal(transactionType,totalAmount);
else
listener.updateTotal(transactionType,0);
}
}
public void performOperation() {
new Thread("MyThread") {
public void run() {
notifyListeners();
}
}.start();
}
public void setState(final int state, final int value) {
this.state = state;
this.totalAmount = value;
this.transactionType = 999;
if (state == DATA_ENTERED) {
}
if (state == TRANSACTION_COMPLETE) {
performOperation();
}
}
} // end CustomerTransactionjava
I shall add the two layout files as well. The first is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView_transactionType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button_enterData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Data" />
</LinearLayout>
The next one is the file enter_data.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_enterNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter a number:" />
<EditText
android:id="#+id/editText_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="send"
android:text="Send" />
</LinearLayout>
Finally, here's the Manifest file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.customlistenertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:theme="#style/AppTheme"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<activity android:label="#string/app_name" android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.customlistenertest.DataActivity" >
</activity>
</application>
</manifest>
The "CustomerTransaction transaction" used in the MainActivity is not the same instance of the "CustomerTransaction transaction" of the one defined in the DataActivity. That explains why the DataActivity one is empty, because you did subscribe only with the one from the MainActivity. Two possible solutions for the problem:
Make the 'control' a singleton, so that you will be sure that there is only one instance of it at a time.
Make the 'listeners' variables and the 'register/unregister/notitifylisteners' methods static.
I prefer the option 1, but you can choose what you think it's best.
Good luck!

My android app crashed on startup

I have followed this for making my app. When I run it on my android 2.1, the app gets stuck. Can you help me? What can I do to make my app working?
MainActivity.java
public class MainActivity extends Activity {
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://check.be?v=1";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<webView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="be.moviechecker.bioscoopprogramma"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<activity
android:name="be.moviechecker.bioscoopprogramma.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In your activity_main.xml file you've used 'webView' instead of using 'WebView' hence it is not getting recognized. Please change it to to WebView and check the result. It will work.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
#user3142817. Welcome. I've made below code make it work for you. Please check
public class MainActivity extends Activity {
private WebView view;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) this.findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("http://www.google.com");
view.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if (url != null && url.startsWith("http://"))
{
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
else
{
return false;
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK && view.canGoBack()){
view.canGoBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

Android Splash Screen

this is what i have in my package explorer so lets start from the top
and work our way around to the problem where i think it is located..
MainActivity.java -
package com.drg.idoser;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
now SplashActivity.java
package com.drg.idoser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
public class SplashActivity extends Activity {
private static String TAG = SplashActivity.class.getName();
private static long SLEEP_TIME = 5; // Sleep for some time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
setContentView(R.layout.splash);
// Start timer and launch main activity
IntentLauncher launcher = new IntentLauncher();
launcher.start();
}
private class IntentLauncher extends Thread {
#Override
/**
* Sleep for some time and than start new activity.
*/
public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME*1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Start main activity
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
SplashActivity.this.startActivity(intent);
SplashActivity.this.finish();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/splash_bg"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
AndroidManafest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drg.idoser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.drg.idoser.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
now i think my problem is in AndroidManafest.xml i dont think i have the splach screen set up right in the AndroidManafest.xml when i launch my application from my phone it jumps to activity_main.xml and not splash.xml im new to android applications so i cant seem to find my problem but i need my splash screen to show for 5 seconds if anyone has TeamViwer and would like to help me ill post my session info if it will be faster.
Change your <application> tag to the following. You didn't have SplashActivity declared, and had your MainActivity setup as the launcher Activity.
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.drg.idoser.SplashActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.drg.idoser.MainActivity"
android:label="#string/app_name" />
</application>
The Best way implement a splash screen, to be displayed every time your application is launched will be to create a new activity.
public class SplashScreen extends Activity {
private Handler mHandler;
private Runnable myRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Just create simple XML layout with i.e a single ImageView or a custom layout
setContentView(R.layout.splash_screen_layout);
mHandler = new Handler();
myRunnable = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
};
}
#Override
public void onBackPressed() {
// Remove callback on back press
if (mHandler != null && myRunnable != null) {
mHandler.removeCallbacks(myRunnable);
}
super.onBackPressed();
}
#Override
protected void onPause() {
// Remove callback on pause
if (mHandler != null && myRunnable != null) {
mHandler.removeCallbacks(myRunnable);
}
super.onPause();
}
#Override
protected void onResume() {
// Attach and start callback with delay on resume
if (mHandler != null && myRunnable != null) {
mHandler.postDelayed(myRunnable, ConstantValues.SPLASH_TIME_OUT);
}
super.onResume();
}
}
You can easily access splash screen like this. such as
public class MainActivity extends Activity {
private ImageView splashImageView;
private boolean splashloading = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splashImageView = new ImageView(this);
splashImageView.setScaleType(ScaleType.FIT_XY);
splashImageView.setImageResource(R.drawable.ic_launcher);
setContentView(splashImageView);
splashloading = true;
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
splashloading = false;
// set your layout file in below
setContentView(R.layout.activity_main);
}
}, 3000);
}
}
it will be works 100%.
Here is a simple one!
~Lunox
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
splashscreen.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class splashscreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
//Splash Screen duration
int secondsDelayed = 1;
new Handler().postDelayed(new Runnable() {
public void run() {
startActivity(new Intent(splashscreen.this, MainActivity.class));
finish();
}
}, secondsDelayed * 3000);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
splashscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splashlogo"
/>
splashlogo.png
splashlogo.png
GitHub
SplashScreen
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread th = new Thread(new Runnable() { /*create a new thread */
#Override
public void run() { /*
* The purpose of this thread is to
* navigate from one class to another
* after some time
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
/*
* We are creating this new thread because we don’t
* want our main thread to stop working for that
* time as our android stop working and some time
* application will crashes
*/
e.printStackTrace();
}
finally {
Intent i = new Intent(MainActivity.this,
Splash_Class.class);
startActivity(i);
finish();
}
}
});
th.start(); // start the thread
}
http://www.codehubb.com/android_splash_screen

Admob + surfaceview don't play well

I'm running Admob 6.0.1 and trying to add the advert over the top of the surface view, I can say that the code below works great with a Android 3.2 (a real device), and also works fine with a android 4 device in the emulator but, when I try to test on pre api13, eg 2.3.3 or below the advert doesn't show. Now here's the weird part, if I change the visibility of the surfaceview (in xml) to invisible the advert will show!!!! what's going on?? Is this just the emulator being buggy or do I have a real problem?
I've tried to keep the code as simple as possible to reproduce the error. I've added a button just to show the surfaceview does allow other views to update, just not the Admob view...
package com.google.example.ads.fundamentals;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.google.ads.AdView;
public class BannerSample extends Activity {
/** The view to show the ad. */
private AdView adView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
adView = (AdView) findViewById(R.id.adView);
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
class Panel extends SurfaceView implements SurfaceHolder.Callback {
private final TutorialThread _thread;
public Panel(Context context, AttributeSet att) {
super(context, att);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
Log.d("Hello", "drawing stuff");
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d("HELLO", "surface changed" + holder.getSurfaceFrame().width()
+ "Height: " + holder.getSurfaceFrame().height());
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
_thread.setRunning(true);
_thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// simply copied from sample application LunarLander:
// we have to tell thread to shut down & wait for it to finish, or
// else
// it might touch the Surface after we return and explode
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
class TutorialThread extends Thread {
private final SurfaceHolder _surfaceHolder;
private final Panel _panel;
private boolean _run = false;
public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
and the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent" android:layout_height="match_parent">
<com.google.example.ads.fundamentals.Panel
android:id="#+id/mainPanel" android:layout_width="match_parent"
android:layout_height="match_parent" android:visibility="invisible" />
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_gravity="top" ads:adSize="BANNER" ads:adUnitId="xxxxxxxxx"
ads:loadAdOnCreate="true" ads:testDevices="TEST_EMULATOR" />
<Button android:id="#+id/mybutton" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="#id/adView"
android:text="hello" />
</RelativeLayout>
And the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.example.ads.fundamentals"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="15" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".BannerSample"
android:screenOrientation="portrait"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Any ideas or help would be so great, I've tried to post on Google Groups for admob but I think it got lost in a void..
As it turns out it was a problem with the emulator, When the code was run on a real device it worked fine! crazy emulator...
Try placing the AdView outside of the SurfaceView instead of on top of it. You can do this by aligning the AdView ad the top, and setting the SurfaceView below it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent" android:layout_height="match_parent">
<com.google.example.ads.fundamentals.Panel
android:id="#+id/mainPanel" android:layout_width="match_parent"
android:layout_height="match_parent" android:visibility="invisible"
android:layout_below="#+id/adView" />
<com.google.ads.AdView android:id="#id/adView"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_gravity="top" ads:adSize="BANNER" ads:adUnitId="xxxxxxxxx"
ads:loadAdOnCreate="true" ads:testDevices="TEST_EMULATOR"
android:layout_alignParentTop="true" />
</RelativeLayout>

Categories