Use public boolean onKeyDown in all activities - java

I'm new in Android Studio and I have created a simple application with 10 activities.
Now, I want to intercept the KeyEvent.KEYCODE_BACK from the user in all of my activities.
I'm opening a dialog when KEYCODE_BACK. It's ok in my MainActivity but I don't want to copy this code in all of my activities.
Would anyone have an idea ?
public class MainActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}

I think that you should separate this code into a separate abstract class and make exdends of this class for all your activities
public abstract class BaseActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
And in all activities
public class ActivityA extends BaseActivity {
}

Related

Want to show interstitial ads on every button clicked but ad show on one button

This is my code for main_activity.i want to implement ads on every button visible on screen and when clicked interstital ad should show. But it only shows ad on btn_button.Kindly guide me how to resolve this issue.
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
private InterstitialAd mInterstitialAd2;
Button btn_button,btn_button2,btn_button3,btn_button4,btn_button5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}});
btn_button=(Button) findViewById(R.id.button);
btn_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i3=new Intent(MainActivity.this,Button.class);
startActivity(i3);
}
});
btn_button2=(Button) findViewById(R.id.button);
btn_button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2=new Intent(MainActivity.this,Button.class);
startActivity(i2);
}
});
btn_button3=(Button) findViewById(R.id.button);
btn_button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Button.class);
startActivity(i);
}
});
btn_button4=(Button) findViewById(R.id.button);
btn_button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i4=new Intent(MainActivity.this,Button.class);
startActivity(i4);
}
});
btn_button5=(Button) findViewById(R.id.button);
btn_button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i5=new Intent(MainActivity.this,Button.class);
startActivity(i5);
}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
btn_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
mInterstitialAd2 = new InterstitialAd(this);
mInterstitialAd2.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd2.loadAd(new AdRequest.Builder().build());
btn_button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd2.isLoaded()) {
mInterstitialAd2.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
btn_button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
btn_button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
btn_button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
}
}
You have same button id, that's why it is showing one only one button as #Anon mentioned.
But actually you don't need so many interstitial instances as you are only using one ad unit. Only one instance is sufficient to show ad on every button clicked.
BUT... your AdMob account will be disabled very soon if you try to show ad on every click.
Every button you are using refers to the same button id, so you have only one button working. =)
'btn_button5=(Button) findViewById(R.id.button);
btn_button4=(Button) findViewById(R.id.button);'

How to always check a condition in Android?

I want to develop an app to toggle the device's audio status. If the audio status is silent then my button's text should be "silent", if it's normal the text should be "normal"
Here is my only class:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1= (Button) findViewById(R.id.btn1);
final AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Normal");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Silent");
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});
How can I always check this condition in Android ?
If you need to get the mode of current ringer even if it was changed outside from you application context then you should register a BroadcastReceiver for AudioManager.RINGER_MODE_CHANGED_ACTION.
This receiver will be called everytime someone changes the ringer mode.
Do this inside onCreate.
BroadcastReceiver receiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Normal");
}
}
};
IntentFilter filter=new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(receiver,filter);
Just do this
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
what your are doing is
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});

How to Reference Buttons in the same Activity from a Custom View

I am trying to make a simple drawing application, but am running into problems switching the paint color.Here is the tutorial I used to get to the point I am at. Here is my code:
Drawing_View.java
public class Drawing_View extends View {
private Path path = new Path();
private Paint paint = new Paint();
public String paint_color = "#FFBB00";
public Drawing_View(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.parseColor(paint_color));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventY = event.getY();
float eventX = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
invalidate();
return true;
}
}
Here is the code for the activity the custom view sits inside.
Drawing_Main.java
public class Drawing_Main extends ActionBarActivity {
Button green_light,green_dark,blue_light,blue_dark,blue_verydark,purple,magenta,red,orange_dark,orange_light,orange_lightest,yellow,black;
String btn_color_hex;
SharedPreferences.Editor editor = getSharedPreferences("paint_color", MODE_PRIVATE).edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
green_light = (Button)findViewById(R.id.button1);
green_dark = (Button)findViewById(R.id.button2);
blue_light = (Button)findViewById(R.id.button3);
blue_dark = (Button)findViewById(R.id.button4);
blue_verydark = (Button)findViewById(R.id.button5);
purple = (Button)findViewById(R.id.button6);
magenta = (Button)findViewById(R.id.button7);
red = (Button)findViewById(R.id.button8);
orange_dark = (Button)findViewById(R.id.button9);
orange_light = (Button)findViewById(R.id.button10);
orange_lightest = (Button)findViewById(R.id.button11);
yellow = (Button)findViewById(R.id.button12);
black = (Button)findViewById(R.id.button13);
green_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_color_hex="#0fad00";
editor.putString("paint_color_hex", btn_color_hex);
editor.commit();
}
});
green_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_verydark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
magenta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_lightest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
yellow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
black.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#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_emojicreation, 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);
}
}
As you can see I started exploring the sharedPreferences option, after my attempt to create a service failed. If a Service is the best option, how can I make Drawing_View.java constantly listen for color changes? Thanks everyone!
You could add a setPaintColor method to your Drawing_View class. That way, you would not need to use SharedPreferences
and you could just change the paint color in your onClickListeners.
Something like this should work:
In your Drawing_View class, add:
public void setPaintColor (String color) {
paint.setColor(Color.parseColor(color));
}
In your onClickListener, call the setPaintColor method:
drawingView.setPaintColor(color);
I assume that your Drawing_View is already instantiated.
Update
You need to instantiate your Drawing_View the same way you instantiated the Buttons in your activity's onCreate method.
public class Drawing_Main extends ActionBarActivity {
...
Drawing_View drawingView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
drawingView = (Drawing_View)findViewById(R.id.drawing_view);
green_light = (Button)findViewById(R.id.button1);
...
I hope this helps.

android app crash after adding actionbar.setsubtitle

I tried to run my app (from bignerdranch) and could not run it after adding the following code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
I get a runtime exception . If i remove these lines the app runs ok .
ofcourse i added the line #TargetApi(11)
i tried changing my target sdk, i tried copying other people's code. nothing works!!
this is my code :
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater[mCurrentIndex]) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
mIsCheater[mCurrentIndex] = data.getBooleanExtra(
CheatActivity.EXTRA_ANSWER_SHOWN, false);
}
#TargetApi(11)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
}
);
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
// mIsCheater=false;
updateQuestion();
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater[mCurrentIndex] = savedInstanceState.getBoolean(CHEATED);
}
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex]
.isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATED, mIsCheater[mCurrentIndex]);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, 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);
}
}
`
what could be the problem?
please help me..
I had the same problem with bignerdranch.
It seems that because QuizActivity is a subclass of ActionBarActivity
instead of Activity I have to use getSupportActionBar() instead of
getActionBar()

how to resume my audio in Android?

I have to implemented application for creating audio with the status of pause and resume and when my app as an when start the audio is start and when I press the back button on the emulator the audio music is on pause state but When my activity comes back to the foreground from the stopped state my audio music is not resumed. Here is my code.
public class Audio_Activity extends Activity
{
private MediaPlayer mp;
Button btnStartStop ;
Button btnChapter ;
Button btnOne;
Button btnTwo;
Button btnThree;
Button btnFour;
Button btnFive;
int length;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
if(mp!=null)
{
mp.setLooping(false);
mp.start();
btnChapter.setEnabled(false);
System.out.println("B4 button Click!!!!");
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
btnStartStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
if(mp.isPlaying())
{
if(mp!=null)
{
mp.pause();
}
}
else
{
// Resume song
if(mp!=null)
{
mp.start();
}
}
}
});
btnOne.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
imgVw.setImageResource(R.raw.chocklate);
}
}
);
btnTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.creame);
}
});
btnThree.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.schocklate);
}
});
btnFour.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.pinapple);
}
});
btnFive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.strobery);
}
});
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
}
#Override
protected void onStart()
{
super.onStart();
System.out.println("Activity is Started !!!");
}
#Override
protected void onRestart() {
super.onRestart();
System.out.println("Activity is Re-Started !!!");
if(mp.isPlaying())
{
if(mp!=null)
{
length=mp.getCurrentPosition();
mp.seekTo(length);
mp.start();
}
}
}
#Override
protected void onPause() {
super.onPause();
System.out.println("Activity is Pause!!!");
}
#Override
protected void onStop() {
super.onStop();
System.out.println("Activity is Stop !!!");
}
#Override
protected void onDestroy() {
super.onDestroy();
System.out.println("Activity is Destroyed !!!");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{ //Back key pressed
//Things to Do
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
//mp=null;
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
You should use android MediaPlaybackService for background play,Pause, stop or just open the activity by clicking the Notification. when click on back button it will bind a PendingIntent to with the button click event or buttons on the notification bar for controlling audio playbacks.
Use this Gist Code for AudioPlayer, try o use MediaPlaybackService class or try to reverse engineer this owncloud code.
Your code is not correct. You should not bother backbutton etc, but activity life cycle. You should pause your audio in onPause() and resume in onResume(). So move code to onPause() and get rid of onKeyDown() and move code from your onRestart() to onResume(). And remove all methods you do not need, line onDestroy(), onStart() etc

Categories

Resources