I am developing app for displaying a channel's live stream and it starts on landscape mode by default and I can change it to portrait and vice versa from my options menu
Now I am using this code in manifest and put it in that activity
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
When I start app, it is working fine but when I change orientation to portrait, the app is hanging and options menu doesn't disappear as usual.
if I deleted this part |screenSize from manifest, it is working fine but the layout-land doesn't work and portrait layout is used at both orientation.
This is LiveActivity.java
package com.shadatv.shada;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.VideoView;
public class LiveActivity extends Activity {
VideoView videoView;
private AlertDialog.Builder errorDialog;
String httpLiveUrl = "http://38.96.148.147:1935/live/livestream/playlist.m3u8";
// =============================================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setContentView(R.layout.live);
try {
videoView = (VideoView) findViewById(R.id.myVideoView);
videoView.setVideoURI(Uri.parse(httpLiveUrl));
videoView.requestFocus();
videoView
.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
videoView.seekTo(1000);
videoView.start();
}
});
} catch (Exception e) {
errorDialog = new AlertDialog.Builder(this);
errorDialog.setMessage("مشكلة في البث");
errorDialog.setCancelable(true);
errorDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog errorStream = errorDialog.create();
errorStream.show();
}
}
// =============================================================================
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_shada, menu);
MenuItem fullItem = menu.findItem(R.id.fullScreen);
MenuItem smallItem = menu.findItem(R.id.smallScreen);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
fullItem.setVisible(false);
smallItem.setVisible(true);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
smallItem.setVisible(false);
fullItem.setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
// =============================================================================
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// setContentView(R.layout.activity_shada);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// setContentView(R.layout.activity_shada1);
}
}
// =============================================================================
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about: {
// TODO Auto-generated method stub
startActivity(new Intent("com.shadatv.MainActivity"));
}
break;
case R.id.smallScreen: {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
break;
case R.id.fullScreen: {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
break;
}
return true;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shadatv.shada"
android:versionCode="3"
android:versionName="1.0.2" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/shada"
android:label="#string/app_name"
>
<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>
<activity
android:name=".LiveActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:exported="false"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="com.shadatv.LiveActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</manifest>
I solved it by pull out the setContentView and try/catch block from onCreate and put it onConfigChanged
package com.shadatv.shada;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.VideoView;
public class LiveActivity extends Activity {
VideoView videoView;
private AlertDialog.Builder errorDialog;
String httpLiveUrl = "http://38.96.148.147:1935/live/livestream/playlist.m3u8";
// =============================================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// if (getResources().getConfiguration().orientation ==
// Configuration.ORIENTATION_LANDSCAPE) {
// getWindow().clearFlags(
// WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
// }
// setContentView(R.layout.live);
}
// =============================================================================
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_shada, menu);
MenuItem fullItem = menu.findItem(R.id.fullScreen);
MenuItem smallItem = menu.findItem(R.id.smallScreen);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
fullItem.setVisible(false);
smallItem.setVisible(true);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
smallItem.setVisible(false);
fullItem.setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
// =============================================================================
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.live);
try {
videoView = (VideoView) findViewById(R.id.myVideoView);
videoView.setVideoURI(Uri.parse(httpLiveUrl));
videoView.requestFocus();
videoView
.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
videoView.seekTo(1000);
videoView.start();
}
});
} catch (Exception e) {
errorDialog = new AlertDialog.Builder(this);
errorDialog.setMessage("مشكلة في البث");
errorDialog.setCancelable(true);
errorDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog errorStream = errorDialog.create();
errorStream.show();
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
// =============================================================================
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
// TODO Auto-generated method stub
startActivity(new Intent("com.shadatv.MainActivity"));
break;
case R.id.smallScreen:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case R.id.fullScreen:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
return true;
}
}
But I find out another problem at optionsMenu. When I press about button to get out from this activity and run MainActivity, the app stops. What is wrong?
When you write android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself.
so the portrait layout will not set on your activity when the screen orientation changed.
why you are using android:configChanges="keyboardHidden|orientation ?
Related
I want after a click on the OK button the MenuActivity to be shown. I have already searched on the Internet to find an answer and tried everything. I haave the activity declared in the AndroidManifest and I also tried to use Intent(this, MenuActivity.class) and also the one with the action inside but it doesn't work.
MainActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.jamesjohnson.chronos.R;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Willkommen");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.action_mainmenu:
startActivity(new Intent("com.jamesjohnson.chronos.MenuActivity"));
return true;
case R.id.action_settings:
showMessageBox("Es gibt leider noch keine Einstellungen. Wir arbeiten daran!", true, true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
Context ctx = this;
intent.setClassName(ctx, "com.jamesjohnson.chronos.MenuActivity");
intent.setAction("com.jamesjohnson.chronos.MenuActivity");
if ((intent.getAction() == "com.jamesjohnson.chronos.MenuActivity") || (intent.getClass() != null)) {
MainActivity.this.startActivity(intent);
showMessageBox("Button has been pressed " + intent.toString(), true, true);
}
else {
showMessageBox("Error : Hauptmenü ist nicht erreichbar", true, true);
}
}
catch (ActivityNotFoundException an) {
showMessageBox("Error :" + an.getMessage(), true, true);
}
catch (Exception e) {
showMessageBox("Error :" + e.getMessage(), true, true);
}
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Here's my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamesjohnson.chronos"
android:versionCode="1"
android:versionName="1.0.1
" >
<application
android:allowBackup="true"
android:debuggable="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>
<activity
android:name=".MenuActivity"
android:label="#string/title_activity_menu"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="com.jamesjohnson.chronos.MenuActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jamesjohnson.chronos.MainActivity" />
</activity>
</application>
</manifest>
And finally here's the MenuActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
private static final String TAG = "MenuActivity";
static final String[] ENTRIES = new String[] {"Kunden", "Projekte", "Leistungen", "Zeiten"};
ListView listView = getListView();
#Override
protected void onCreate(Bundle savedInstanceState) {
showMessageBox("Activity is beeing created", true, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setTitle("Hauptmenü");
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ENTRIES));
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessageBox("Kunden", true, true);
break;
case 1:
showMessageBox("Projekte", true, true);
break;
case 2:
showMessageBox("Leistungen", true, true);
break;
case 3:
showMessageBox("Zeiten", true, true);
break;
default:
showMessageBox("Error: Undefined index", true, true);
}
}
});
}
#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_menu, 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);
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MenuActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Unfortunately I can't show you my Logcat because it doesn't work on my computer. (I always have to export the APK to test the App).
P.S. I am working with Android Studio 1.0.1
...Please HELP ME !
To open a new activity you simply have to call it like this inside the onClick method.
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
So your onClick method will look like this.
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
}
Hope this helps.
Is because you say MainActivity.this, but you aren't in the MainActivity context.
You could make a reference of your current context in onCreate() and save it in a field:
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
context = this;
//rest of your code here
}
and use it as:
Intent intent = new Intent(context, MenuActivity.class);
//Something else
context.startActivity(intent);
Go to your manifest file, you will for your MainActivity manifest:
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
Just copy them and paste them for your MenuActivity.
I had the same same problem than you and it worked for me, but I don't know why.
Good luck!
first make sure your AndroidManifest.xml file contain declaration of all Activities in your app, like
<activity android:name=".MenuActivity"/>
then you create new intent and start it where you need to start the second Activity
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
I'm new to Android. I read similar posts but I cannot solve my problem.
I added all my activities in androidManifest file, but I cannot move from Second Activity to ThirdActivity using Intent.
Here is MainActivity.java
package com.mobi.crazycalc;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent in= new Intent(MainActivity.this,SecondActivity.class);
MainActivity.this.startActivity(in);
MainActivity.this.finish();
}
}, 1000);
}
#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;
}
}
here is SecondActivity.java
package com.mobi.crazycalc;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SecondActivity extends Activity {
EditText name1;
EditText name2;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name1= (EditText) findViewById(R.id.name1);
name2=(EditText) findViewById(R.id.name2);
goButton= (Button) findViewById(R.id.gobutton);
final String hisName=name1.getText().toString().trim();
final String herName=name2.getText().toString().trim();
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Love lv=new Love();
int result=lv.getLovePer(hisName, herName);
Intent in=new Intent(SecondActivity.this,ThirdActivity.class);
in.putExtra("Result", result);
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
Here is ThirdActivity.java
package com.mobi.crazycalc;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ThirdActivity extends Activity {
TextView meter;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
meter = (TextView) findViewById(R.id.meter);
goBackButton = (Button) findViewById(R.id.gobackbutton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in=new Intent(ThirdActivity.this,SecondActivity.class);
startActivity(in);
}
});
Random ran= new Random();
for(int i=0;i<100;++i)
{
int ranNo=ran.nextInt(100);
meter.setText(ran.toString());
}
Bundle bund=getIntent().getExtras();
int res=bund.getInt("Result");
meter.setText(res);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.third, menu);
return true;
}
}
this is the manifest file-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobi.crazycalc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
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.mobi.crazycalc.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>
<activity
android:name="com.mobi.crazycalc.SecondActivity"
android:label="#string/title_activity_second" >
</activity>
<activity
android:name="com.mobi.crazycalc.ThirdActivity"
>
</activity>
</application>
</manifest>
activity-second.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:background="#e52850"
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=".SecondActivity" >
<EditText
android:id="#+id/name1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:ems="10"
android:hint="#string/name1Edittext"
android:textColor="#color/almond" >
<requestFocus />
</EditText>
<Button
android:id="#+id/gobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:background="#android:color/transparent"
android:text="#string/buttontext"
android:textColor="#color/aeroBlue" />
<EditText
android:id="#+id/name2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name1"
android:layout_below="#+id/name1"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="#string/name2Edittext"
android:textColor="#color/almond" />
</RelativeLayout>
Try This one
And you can check this here
In MainActiviy
package com.mobi.crazycalc;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent in = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(in);
MainActivity.this.finish();
}
}, 1000);
}
#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;
}
}
In SecondAcivity
package com.mobi.crazycalc;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
EditText name1;
EditText name2;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name1 = (EditText) findViewById(R.id.name1);
name2 = (EditText) findViewById(R.id.name2);
goButton = (Button) findViewById(R.id.gobutton);
final String hisName = name1.getText().toString().trim();
final String herName = name2.getText().toString().trim();
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(SecondActivity.this, ThirdActivity.class);
in.putExtra("Result", "value");
startActivity(in);
}
});
}
#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_second, 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);
}
}
In Third activity
package com.mobi.crazycalc;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class ThirdActivity extends ActionBarActivity {
TextView meter;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
meter = (TextView) findViewById(R.id.meter);
goBackButton = (Button) findViewById(R.id.gobackbutton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(ThirdActivity.this, SecondActivity.class);
startActivity(in);
}
});
Random ran = new Random();
for (int i = 0; i < 100; ++i) {
int ranNo = ran.nextInt(100);
meter.setText(ran.toString());
}
Bundle bund = getIntent().getExtras();
String res = bund.get("Result").toString();
meter.setText(res);
}
#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_third, 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);
}
}
and In menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobi.crazycalc" >
<application
android:allowBackup="true"
android:icon="#mipmap/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>
<activity
android:name=".SecondActivity"
android:label="#string/title_activity_second" >
</activity>
<activity
android:name=".ThirdActivity"
android:label="#string/title_activity_third" >
</activity>
</application>
</manifest>
Hope it will help you.
Hi I want to play a media(video) file on surfaceview, so I am trying in follwing way.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myProject" >
<permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<SurfaceView
android:id="#+id/surfView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Then I have created a /raw folder under /res folder and added a video(newmovie.mp4) in it.
Now In MainActivity I am trying to play that video in this way.
package com.example.myProject;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.Fragment;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity implements SurfaceHolder.Callback,OnPreparedListener{
private MediaPlayer mediaPlayer;
private SurfaceHolder vidHolder;
private SurfaceView vidSurface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vidSurface = (SurfaceView) findViewById(R.id.surfView);
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(this);
vidHolder.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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container,
false);
return rootView;
}
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
String fileName = "android.resource://" + getPackageName() + "/" + R.raw.newmovie;
mediaPlayer.setDataSource(this, Uri.parse(fileName));
mediaPlayer.setDisplay(vidHolder);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepare();
}
catch(Exception e){
e.printStackTrace();
}
}
#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
}
}
But I am getting error as 'E/MediaPlayer﹕ Error (1,-38)' after running this application as a result getting blank screen.
Also getting error as 'E/MediaPlayer﹕ Should have subtitle controller already set' which can be neglected as it will not stop to play video file.
When I tried to debug and see the file-name at run-time is like "android.resource://com.example.myProject/21348349", but my video resides in res/raw/ folder. How android gets my video at run-time ?
Can anyone guide me for this what is the meaning of this error and how can I resolve it.
I have implemented a search system in my app, and the search bar appears, but when enter is pressed the search activity doesn't load.
As well as this, the text typed into the search box is black. The action bar is also black, so is there a way to make it white on API 14+?
My MainActivity:
package com.liamwli.spotify.spotifycommunity;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.Toast;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
ProgressBar progress;
WebView wv;
WebSettings wvs;
String url, prefix;
SharedPreferences prefs;
SharedPreferences.Editor editor;
ActionBar ab;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
ab = getActionBar();
ab.setHomeButtonEnabled(true);
progress = (ProgressBar) findViewById(R.id.pBProgress);
wv = (WebView) findViewById(R.id.wVPage);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if (!url.contains("community.spotify.com")
&& !url.contains("facebook.com")
&& !url.contains("spotify.com")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
i.addCategory(Intent.CATEGORY_BROWSABLE);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else {
view.loadUrl(url);
}
return super.shouldOverrideUrlLoading(view, url);
}
});
wv.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
// TODO Auto-generated method stub
if (newProgress < 100
&& progress.getVisibility() == ProgressBar.GONE) {
progress.setVisibility(ProgressBar.VISIBLE);
}
progress.setProgress(newProgress);
if (newProgress == 100) {
progress.setVisibility(ProgressBar.GONE);
}
super.onProgressChanged(view, newProgress);
}
});
wvs = wv.getSettings();
if (prefs.getBoolean("javascript_enabled", true)) {
wvs.setJavaScriptEnabled(true);
wvs.setJavaScriptCanOpenWindowsAutomatically(true);
}
if (Build.VERSION.SDK_INT >= 11)
wvs.setDisplayZoomControls(true);
wvs.setSupportZoom(true);
wvs.setSupportMultipleWindows(true);
if (prefs.getBoolean("desktop_mode", false)) {
prefix = "/?device-view=desktop";
} else {
prefix = "/?device-view=mobile";
}
url = "http://community.spotify.com" + prefix;
Intent liam = getIntent();
if (liam.getAction() == Intent.ACTION_VIEW) {
Uri data = liam.getData();
URL urlurl = null;
try {
urlurl = new URL(data.getScheme(), data.getHost(),
data.getPath());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("Malformed URL Given");
}
url = urlurl.toString() + prefix;
}
if (url == null)
throw new RuntimeException("URL Null");
wv.loadUrl(url);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.activity_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the
// widget;
// expand it by default
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_back:
if (wv.canGoBack()) {
wv.goBack();
} else {
Toast.makeText(this, "Can't Go Back!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_forward:
if (wv.canGoForward()) {
wv.goForward();
} else {
Toast.makeText(this, "Can't Go Forward!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_refresh:
wv.reload();
break;
case R.id.menu_settings:
Intent i = new Intent(this, PrefActivity.class);
startActivity(i);
break;
case R.id.menu_search:
onSearchRequested();
break;
case android.R.id.home:
wv.loadUrl("http://community.spotify.com" + prefix);
break;
}
return super.onOptionsItemSelected(item);
}
}
My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.liamwli.spotify.spotifycommunity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.liamwli.spotify.spotifycommunity.StartActivity"
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.liamwli.spotify.spotifycommunity.MainActivity"
android:excludeFromRecents="true"
android:exported="true"
android:label="#string/app_name"
tools:ignore="ExportedActivity" >
<intent-filter>
<action android:name="com.liamwli.spotify.spotifycommunity.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.PostUrl"
android:excludeFromRecents="true"
android:exported="false"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.liamwli.spotify.spotifycommunity.POSTURL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.PrefActivity"
android:exported="false"
android:label="#string/app_name" >
<intent-filer>
<action android:name="com.liamwli.spotify.spotifycommunity.PREFACTIVITY" />
<category android:name="android.intent.cetagory.PREFERENCE" />
</intent-filer>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.ClearData"
android:excludeFromRecents="true"
android:exported="false"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.liamwli.spotify.spotifycommunity.CLEARDATA" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.liamwli.spotify.spotifycommunity.SearchActivity"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<provider
android:name="com.liamwli.spotify.spotifycommunity.MySuggestionProvider"
android:authorities="com.liamwli.spotify.spotifycommunity.MySuggestionProvider"
android:exported="true" />
</application>
</manifest>
My SearchActivity:
package com.liamwli.spotify.spotifycommunity;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.SearchRecentSuggestions;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Toast;
public class SearchActivity extends Activity {
WebView wv;
SharedPreferences prefs;
SharedPreferences.Editor editor;
String prefix;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
wv = (WebView) findViewById(R.id.wVPage);
if (prefs.getBoolean("desktop_site", false)) {
prefix = "/?device-view=desktop";
} else {
prefix = "/?device-view=mobile";
}
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
this, MySuggestionProvider.AUTHORITY,
MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
doMySearch(query);
}
}
private void doMySearch(String query) {
// TODO Auto-generated method stub
wv.loadUrl("http://community.spotify.com/t5/forums/searchpage/tab/message?q="
+ query + prefix);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.activity_main_nosearch, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_back:
if (wv.canGoBack()) {
wv.goBack();
} else {
Toast.makeText(this, "Can't Go Back!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_forward:
if (wv.canGoForward()) {
wv.goForward();
} else {
Toast.makeText(this, "Can't Go Forward!", Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.menu_refresh:
wv.reload();
break;
case R.id.menu_settings:
Intent i = new Intent(this, PrefActivity.class);
startActivity(i);
break;
case android.R.id.home:
wv.loadUrl("http://community.spotify.com" + prefix);
break;
}
return super.onOptionsItemSelected(item);
}
}
I don't receive a force close - it just doesn't launch the search activity.
Also, what permission should I set for the final provider? The android system must be able to execute it,
I have 7 Activities in my application. I wants to display admob in every activity
Whether i have to create each AdView in every activity?
or
is there any alternative to reuse previous activity container OR prevent it from destroy so can i use in next activity....
Any code or hint we'll b appreciate.
Thankx
I DID this. Thankx to yorkw comment. This is not an efficient code. But you can modify accordingly. That reduces your code for each activity.
Just Extends "TestingAdmobActivity" & call SetupAds() to call your advs.
My SuperClass "TestingAdmobActivity.java"
package com.test.myadmob;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
public class TestingAdmobActivity extends Activity implements AdListener{
public AdView adView;
public String ADV_PUB_ID = "a14e2fb60918999";
private boolean adVisible = true;
LinearLayout layout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Admob", "Calling External");
}
public void SetupAds(){
Log.i("AdMob", "Start Setup");
layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.CENTER_HORIZONTAL); //To put AdMob Adv to Bottom of Screen
Log.i("AdMob", "End Layout Setup");
addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
adView = new AdView(this, AdSize.BANNER, ADV_PUB_ID);
adView.setAdListener(this);
Log.i("AdMob", "Init complete Adview");
layout.addView(adView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.i("AdMob", "Done AddView Layout");
AdRequest request = new AdRequest();
request.addTestDevice(AdRequest.TEST_EMULATOR);
request.addKeyword("LifeOK");
adView.loadAd(request);
Log.i("AdMob", "End Setup");
}
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 0: //Disable Adv
if (adVisible)
adVisible = false;
break;
case 1: //Enable Adv
if (!adVisible)
{
Log.i("AdMob", "Case 1");
adVisible = true;
}
break;
case 2: //Enable but Hide Adv
adView.setVisibility(View.GONE);
break;
case 3: //Enable but Show Adv
adView.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
};
public void DisableAds()
{
Log.i("AdMob", "Request Disable Adv");
handler.sendEmptyMessage(0);
}
public void EnableAds()
{
Log.i("AdMob", "Request Enable Adv");
handler.sendEmptyMessage(1);
}
public void HideAdv() //Enable Adv but Hide
{
Log.i("AdMob", "Request Hide Adv");
handler.sendEmptyMessage(2);
}
public void ShowAdv() //Show Adv
{
Log.i("AdMob", "Request Show Adv");
handler.sendEmptyMessage(3);
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Dismiss Screen");
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
Log.d("AdMob", "failed to receive ad (" + arg1 + ")");
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Leaving Application");
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Present Screen");
}
#Override
public void onReceiveAd(Ad arg0) {
// TODO Auto-generated method stub
Log.d("AdMob", "Adv Received");
}
}
My FirstActivityClass "NewActivity_1.java"
package com.test.myadmob;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class NewActivity_1 extends TestingAdmobActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Admob", "OnCreate");
SetupAds();
Log.i("Admob", "Done");
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Admob", "Going to Activity 2");
Intent mainIntent = new Intent().setClass(NewActivity_1.this, NewActivity_2.class);
startActivity(mainIntent);
}
});
}
}
My SecondActivityClass "NewActivity_2.java"
package com.test.myadmob;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class NewActivity_2 extends TestingAdmobActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Admob", "OnCreate");
SetupAds();
Log.i("Admob", "Done");
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Admob", "Going Back to Activity 1");
finish();
}
});
}
}
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.myadmob"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".NewActivity_1" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".TestingAdmobActivity" ></activity>
<activity android:name=".NewActivity_2" ></activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
>
</activity>
</application>
<!-- AdMob SDK requires Internet permission -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- to get Android Device ID -->
</manifest>
Note: for the sake of permissions used by google admob sdk, i have to build this on android 4.0 sdk with min-sdk version 7
In my app I have a cache of 0..12 ads at any given time. I'm reusing them accross different Fragments in an endless ViewPager. The caching class is in charge of loading the providing the ads to the Fragments.
The trick is to:
Call the AdView's onDestory only when you're sure you're done with that AdView instance for good. This means that the Fragments themselves are not in charge of this.
Passing the AdView's themselves between the Fragments, we need to remember to detach each AdView from its hierarchy:
(only on the UI thread of course):
public void detachFromHirerchy()
{
View adView = getAdView();
if ( adView != null )
{
ViewGroup parent = (ViewGroup) adView.getParent();
if (parent != null)
{
parent.removeView( adView );
}
}
}