Media player not starting after stopping - java

below is my code for media player. It doesn't start again after I stop. How to solve this? Even though I have called the prepare method before calling the start method. Also why doesn't the music stop playing even after I exit the programme. Please advice.
public class MainActivity extends Activity {
Button play,pause,stop;
CheckBox c1,c2,c3;
MediaPlayer song1,song2,song3;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
c1=(CheckBox)findViewById(R.id.checkBox1);
c2=(CheckBox)findViewById(R.id.checkBox2);
c3=(CheckBox)findViewById(R.id.checkBox3);
song1=MediaPlayer.create(this, R.raw.finalcountdown);
song2=MediaPlayer.create(this, R.raw.invincible);
song3=MediaPlayer.create(this, R.raw.somewhereibelong);
builder=new AlertDialog.Builder(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.main, menu);
return true;
}
public void start(View view) throws IllegalStateException, IOException
{
if(c1.isChecked())
{
if(!song1.isPlaying())
{
song1.prepare();
song1.start();
}
else{
song1.start();
}
}
if(c2.isChecked())
{
if(!song2.isPlaying())
{
song2.prepare();
song2.start();
}
else{
song2.start();
}
}
if(c3.isChecked())
{
if(!song3.isPlaying())
{
song3.prepare();
song3.start();
}
else{
song3.start();
}
}
else{
builder.setMessage("Please mark a checkbox");
}
}
public void stop(View view)
{
if(c1.isChecked())
song1.stop();
else if (c2.isChecked())
song2.stop();
else if (c3.isChecked())
song3.stop();
else
builder.setMessage("Error message ");
}
public void pause(View view)
{
if(c1.isChecked())
{
song1.pause();
}
else if(c2.isChecked())
{
song2.pause();
}
else if(c3.isChecked())
{
song3.pause();
}
else
builder.setMessage("error message");
}
}

you need to put song1.release() and release methods for other songs inside the stop method. Refer the life cycle of media player for further info.
http://developer.android.com/reference/android/media/MediaPlayer.html

You have to release the player OnPause or OnDestroy method.
#Override
public void onDestroy() {
if(c1!= null)c1.release();
else if (c2!= null)c2.release();
else if (c3!= null)c3.release();
else
//something
}

Related

Show a progress Bar when Rewarded video Ads is loading

I want to use Rewarded video ads (Admob) but I want to show a progress bar while the video ads is loading
I already try to did it with async task just to see if the video will load but it didn't work
#SuppressLint("StaticFieldLeak")
public class videoAd extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(Void... voids) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
});
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (mRewardedVideoAd.isLoaded()){
Toast.makeText(SetFullWallpaper.this, "Video loaded", Toast.LENGTH_SHORT).show();
mRewardedVideoAd.show();
}
}
}
Now I want to load a progress bar if the video is not loaded yet
Thank you
This is how I did it:
I had a button, which when clicked showed the ad, so I had a boolean variable which tracked whether the button has been clicked:
boolean buttonClicked = false
These lines were in my onCreate function:
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getContext());
rewardedVideoAdListener = new RewardedVideoAdListener() {
#Override
public void onRewardedVideoAdLoaded() {
if(buttonClicked) {
showAd();
}
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
if(buttonClicked) {
progressBar.setVisibility(View.INVISIBLE);
Toast toast = Toast.makeText(getContext(), "Please try again later", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRewardedVideoCompleted() {
}
};
mRewardedVideoAd.setRewardedVideoAdListener(rewardedVideoAdListener);
loadRewardedVideoAd();
pointsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAd();
}
});
This was my showAd function:
public void showAd(){
if (mRewardedVideoAd.isLoaded()) {
progressBar.setVisibility(View.GONE);
mRewardedVideoAd.show();
buttonClicked = false;
} else {
loadRewardedVideoAd();
progressBar.setVisibility(View.VISIBLE);
buttonClicked = true;
}
}
How this works is, the app tries to load the ad in the background by calling the loadRewaredVideoAd() function when the activity/fragment is created. Then when the user clicks the button,showAd() function is called and one of two things happen:
1) If the ad was successfully loaded, it shows the ad.
2) If not, it calls loadRewardedVideoAd() again and shows a progressbar this time. It also sets buttonClicked to true. Then if the ad loads, the onRewardedVideoAdLoaded() function is called which calls showAd() again and this time the 1st option happens.
If the ad didn't load this time as well, then onRewardedVideoAdFailedToLoad(int i)is called and it shows a toast saying the user to try again later.
add OnProgressUpdate() in your class that extends AsyncTask and add progress dialog in this.
I am placing an admob video, which is executed when you enter the activity. In my case, I put an executable loop to start the video when it is already loaded.
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
This is part of all my code
private boolean started = false;
private Handler handler = new Handler();
private void initializeAdMob() {
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(getString(R.string.id_block_activity), new AdRequest.Builder().build());
}
}
private void showRewardedVideoAd() {
if (BaseInteractor.isNetworkAvailable(this)) {
showProgressBar(true);
start();
}
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
if (started) {
start();
}
}
};
public void stop() {
started = false;
handler.removeCallbacks(runnable);
}
public void start() {
started = true;
handler.postDelayed(runnable, 2000);
}
finally I stop the runnable in
#Override
public void onRewardedVideoAdOpened() {
showProgressBar(false);
stop();
}
I hope this helps you.

Press Twice to exit the activity not working

i need to close and activity and start another only when the user presses back twice. I am using this code
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
Log.e("Entering","Yes");
DatabaseHandler db=new DatabaseHandler(AddBreakfastActivity.this);
db.deleteTodaysUnsavedMenu(Integer.parseInt(newDay),Integer.parseInt(newIntMonth));
Intent intent=new Intent(AddBreakfastActivity.this,ProvidersUpdateActivity.class);
startActivity(intent);
finish();
}
else {
this.doubleBackToExitPressedOnce = true;
Log.e("BOOLEANVALUE", String.valueOf(doubleBackToExitPressedOnce));
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
On pressing back once the app exits and shows the Toast message.
It doesnt wait for the second press. How can i resolve this?
Thank you.
EDIT
Found it to be working as expected when the back button is pressed. However shows aforesaid issue when called from
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home){
onBackPressed();
}
}
you can also do this with on keydown event as code below remove backpressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==KeyEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_BACK)
{
if (doubleBackToExitPressedOnce) {
Log.e("Entering","Yes");
DatabaseHandler db=new DatabaseHandler(AddBreakfastActivity.this);
db.deleteTodaysUnsavedMenu(Integer.parseInt(newDay),Integer.parseInt(newIntMonth));
Intent intent=new Intent(AddBreakfastActivity.this,ProvidersUpdateActivity.class);
startActivity(intent);
finish();
}
else {
this.doubleBackToExitPressedOnce = true;
Log.e("BOOLEANVALUE", String.valueOf(doubleBackToExitPressedOnce));
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
return false;
}
}
return super.onKeyDown(keyCode, event);
}
Here's an example of "Press Twice to Exit" with fragments:
boolean doublePressToQuit = false;
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
if (doublePressToQuit) {
DashBoardActivity.this.finish();
} else {
this.doublePressToQuit = true;
Toast.makeText(this, getString(R.string.quit_notification), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doublePressToQuit = false;
}
}, 2000);
}
}
}
Include super.onBackPressed(); inside your IF statement to override the onBackPressed() event.
Try the below code, it works for me
boolean firstBackPressed = false;
.
.
.
#Override
public void onBackPressed() {
if (!firstBackPressed) {
firstBackPressed = true;
Toast.makeText(MainMenu.this, "Press back again to exit", Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed();
}
}
Please find this
private boolean isShownExit;
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
drawerLayout.closeDrawer(Gravity.LEFT);
isShownExit = false;
return;
} else {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
if (!isShownExit) {
isShownExit = true;
showToast(this, "Press again to exit");
} else {
hideSoftKeyboardDialogDismiss(this);
startAnotherActivityHereWhichDoYouwant();
}
} else {
getSupportFragmentManager().popBackStack();
}
}
}

Mediaplayer : pause called in state 1 - Android Eclipse

I'm creating a MediaPlayer button in the ActionBar, wherein it is playing automatically when the app started and when I clicked it should be off. The problem now is that the sound is not playing and when I click the button there is an error in logcat saying...
UPDATED LOGCAT.
12-18 19:04:57.812: E/MediaPlayer(5673): attachNewPlayer called in state 32
Here is the code..
public class MainActivity extends Activity{
private MediaPlayer mp;
Item btnplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying=false;//when the media file playing is completed isPlaying=false; is must
}
});
play(null);//you are calling play by launching
}
//inflate items in actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
boolean isPlaying = false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.btnplay) //whatever you named in xml
{
play(item);
}
return super.onOptionsItemSelected(item);
}
public void play(MenuItem menuItem) {
if (!isPlaying) {
try
{
AssetFileDescriptor afd = getAssets().openFd("caketown.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();//play sound
}
catch(Exception e) {
e.printStackTrace();
}
isPlaying = true;
}
else if (isPlaying) {
mp.pause();
isPlaying = false;
}
}
Here is the menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.xxx.MainActivity" >
<item
android:id="#+id/btnplay"
android:title=""
android:icon="#drawable/ic_action_volume_on"
android:onClick="play"
android:showAsAction="always"/>
<menu>
Please help me. I'm just new here. :(
1.Please initialize mp = new MediaPlayer(); in your onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play(null);//you are calling play by launching
}
2.change it to boolean isPlaying = false; because when app start it set as boolean isPlaying = false so it will play the audio and again you click on it for pause it will work as per your code
3.change this else if
else if (isPlaying) {
mp.pause();
isPlaying=false;
}
4.change this function too
public void play(MenuItem menuItem) {
if (!isPlaying && !isPaused) {
try {
if (mp == null) {
// mp.release();
// mp.reset();
mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets()
.openFd("caketown.mp3");
mp.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying = false;// when the media file playing is completed
isPaused = false;
// Toast.makeText(getApplicationContext(), "play completed",
// Toast.LENGTH_SHORT).show(); // isPlaying=false; is must
}
});
}
mp.start();// play sound
} catch (Exception e) {
e.printStackTrace();
}
isPlaying = true;
} else if (isPlaying) {
Toast.makeText(getApplicationContext(), "play paused",
Toast.LENGTH_SHORT).show();
mp.pause();
isPlaying = false;
isPaused = true;
length = mp.getCurrentPosition();
// and for resuming the player from the position where it stopped
// lately is done by:
} else if (isPaused) {
mp.seekTo(length);
mp.start();
isPlaying = true;
isPaused = false;
}
}
Initialize isPlaying to false to get your conditional working.
Initialize MediaPlayer only once to to get the stop/pause working instead of overlapping sounds. That is, move the mp = new MediaPlayer(); to onCreate() for example.

How do I get my MenuActivity to show up?

I am following the patterns that are used in the Compass example in a new project and have most of the logic working. However, when I tap while my live card is displayed I hear the 'click' noise but my menu activity doesn't display. I think that I am missing a piece of the puzzle, but I have not been able to figure out what as of yet.
When I tap, besides the click, I also see this in logcat:
01-08 10:02:26.796: I/ActivityManager(196): START {flg=0x10008000 cmp=com.example.speeddisplay/.SpeedDisplayMenuActivity} from pid -1
So it looks like it should be starting my activity, but it doesn't show up. Here are some pieces of relevant code...although I am not sure where the issue is.
Service portion in AndroidManifest.xml:
<service
android:name="com.example.speeddisplay.service.SpeedService"
android:enabled="true"
android:icon="#drawable/ic_drive_50"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
</intent-filter>
<meta-data
android:name="com.google.android.glass.VoiceTrigger"
android:resource="#xml/voiceinput_speeddisplay" />
</service>
onStartCommand method in SpeedService.java:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Constants.DEBUG) {
Log.d(TAG, "onStartCommand");
}
if (liveCard == null) {
liveCard = timelineManager.createLiveCard(LIVE_CARD_ID);
speedRenderer = new SpeedRenderer(this, speedManager);
liveCard.setDirectRenderingEnabled(true);
liveCard.getSurfaceHolder().addCallback(speedRenderer);
// Display the options menu when the live card is tapped.
Intent menuIntent = new Intent(this, SpeedDisplayMenuActivity.class);
menuIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
liveCard.setAction(PendingIntent.getActivity(this, 0, menuIntent, 0));
liveCard.publish(PublishMode.REVEAL);
if(Constants.DEBUG){
Log.d(TAG, "liveCard published");
}
}
return START_STICKY;
}
Here is my SpeedDisplayMenuActivity.java. None of these methods are getting called.
public class SpeedDisplayMenuActivity extends Activity {
private SpeedService.SpeedBinder speedService;
private boolean mResumed;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (Constants.DEBUG) {
Log.e("Service Stuff", "Service connected.");
}
if (service instanceof SpeedService.SpeedBinder) {
speedService = (SpeedService.SpeedBinder) service;
openOptionsMenu();
}
if (Constants.DEBUG) {
Log.e("Service Stuff", "service was an instance of " + service.getClass().getName());
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
// Do nothing.
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(Constants.DEBUG){
Log.e("Menu", "Created.");
}
super.onCreate(savedInstanceState);
bindService(new Intent(this, SpeedService.class), mConnection, 0);
}
#Override
protected void onResume() {
if(Constants.DEBUG){
Log.e("Menu", "Resumed.");
}
super.onResume();
mResumed = true;
openOptionsMenu();
}
#Override
protected void onPause() {
if(Constants.DEBUG){
Log.e("Menu", "Paused.");
}
super.onPause();
mResumed = false;
}
#Override
public void openOptionsMenu() {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open");
}
if (mResumed && speedService != null) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open with correct params");
}
super.openOptionsMenu();
} else {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open with INCORRECT params");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Created");
}
getMenuInflater().inflate(R.menu.speed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Item Selected");
}
switch (item.getItemId()) {
// case R.id.read_aloud:
// mCompassService.readHeadingAloud();
// return true;
case R.id.stop:
if (Constants.DEBUG) {
Log.e("Options Menu", "Stop");
}
stopService(new Intent(this, SpeedService.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Closed");
}
super.onOptionsMenuClosed(menu);
unbindService(mConnection);
// We must call finish() from this method to ensure that the activity
// ends either when an
// item is selected from the menu or when the menu is dismissed by
// swiping down.
finish();
}
Does anybody see what I am missing?
That is right, declaring the SpeedDisplayMenuActivity is the problem in this case.
I have seen cases where many other types of exceptions / crash that normally happens in Android environment is gracefully handled in Glass.
That is definitely good for the user experience, but makes little tough on development. Hopefully some kind of settings come in future to enable exceptions as well in future!

Android: Toggle button doesnt update

I'm having some problems trying to set togglebutton (LeftLightButton) state and text after receiving value 1 at novo.charAt(0) for example. The main idea is, i click the button, it makes webview.loadUrl, and if the page changes to what i expected the toggle button state should be on, if not, it must stay off and vice versa. The way it is now, doesnt change the text neither state in case the site didnt update to the value that i was expecting.
public class MainActivity extends Activity {
private WebView webView;
private ToggleButton LeftLightButton;
private Thread webviewthread;
private String baseURL;
private boolean LeftLightButtonState;
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
baseURL = "http://192.168.1.4/i.php";
LeftLightButton = (ToggleButton) findViewById(R.id.toggleButton1);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runOnUiThread(new Runnable() {
public void run()
{
synchronized(this) {
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(context, "HTMLOUT");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
webView.loadUrl(baseURL);
}
}
});
showToast("Getting current status...");
}
public void notify(final boolean state, final ToggleButton buttonName) {
Thread thread = new Thread() {
#Override
public void run() {
synchronized (this) {
try {
wait(1000);
final ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton1);
if (!state && button.isChecked()) {
showToast("Couldnt turn OFF");
// UI
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setChecked(false);
button.setTextOff("OFF");
}
});
// end of UI
}
if (state && !button.isChecked()) {
showToast("Couldnt turn ON");
// UI
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setChecked(true);
button.setTextOn("ON");
}
});
// end of UI
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
}
public void showToast(final String toast)
{
runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
}
});
}
public void onClick(View arg0) {
final int id = arg0.getId();
switch (id) {
case R.id.toggleButton1:
if (LeftLightButtonState == true) {
webView.loadUrl(baseURL+"?L=0");
notify(false, LeftLightButton);
} else {
webView.loadUrl(baseURL+"?L=1");
notify(true, LeftLightButton);
}
break;
// even more buttons here
}
}
#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;
}
public void processHTML(String html) { // <html> <body> 1 0 0 0 </body> </html>
LeftLightButton = (ToggleButton) findViewById(R.id.toggleButton1);
String novo = android.text.Html.fromHtml(html).toString();
System.out.println("RECEIVED: "+novo);
if (novo != null) {
if (novo.charAt(0) == '0') {
LeftLightButtonState = false;
LeftLightButton.setTextOff("OFF");
LeftLightButton.setChecked(false);
}
if (novo.charAt(0) == '1') {
LeftLightButtonState = true;
LeftLightButton.setTextOn("ON");
LeftLightButton.setChecked(true);
}
System.out.println("CHEGUEI");
}
}
}
Use different string in the xml files itself. Then based on the state appropriate text will be displayed. You can call setChecked(true/false) to select or unselect the Toggle Button.. It is working fine in my project.
android:textOff="#string/dontshowtraffic"
android:textOn="#string/showtraffic"

Categories