I am trying to run my Android radio app in the background. So when I click the back button after a little time it has been forced to stop. Automatically calls the onDestroy() method. How do I fix this problem?
This is the main activity class onBackPressed() button code.
#Override
public void onBackPressed(){
System.out.println("onBackPressed");
serviceIntent.addCategory(Intent.CATEGORY_HOME);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(serviceIntent);
moveTaskToBack(true);
//activity.moveTaskToBack(true);
}
This is the console log
> I/System.out: onPrepared I/System.out: onBackPressed I/System.out:
> onDestroy I/System.out: onDestroy1 I/System.out: onDestroy2
> V/MediaPlayer: resetDrmState: mDrmInfo=null
> mDrmProvisioningThread=null mPrepareDrmInProgress=false
> mActiveDrmScheme=false V/MediaPlayer: cleanDrmObj: mDrmObj=null
> mDrmSessionId=null W/MediaPlayer: mediaplayer went away with unhandled
> events
MainActivity
package com.jiat.yesradio;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements MusicStoppedListener {
private ImageView imagePlayPause;
String stream = "https://radio.lankayes.lk/8002/stream";
boolean musicPlaying = false;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate MainA");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePlayPause = (ImageView) findViewById(R.id.imagePlayPause);
imagePlayPause.setImageResource(R.drawable.play_icon);
serviceIntent = new Intent(this, MyPlayService.class);
// serviceIntent = new Intent(this, SimpleMyPlayService.class);
ApplicationClass.context = (Context) MainActivity.this;
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("onClick");
if (!musicPlaying) {
System.out.println("onClick_inside_music_player");
startService(serviceIntent);
playAudio();
imagePlayPause.setImageResource(R.drawable.pause_icon);
musicPlaying = true;
}
else {
stopPlayService();
stopService(serviceIntent);
imagePlayPause.setImageResource(R.drawable.play_icon);
musicPlaying = false;
}
}
});
}
#Override
public void onBackPressed(){
System.out.println("onBackPressed");
/* serviceIntent.addCategory(Intent.CATEGORY_HOME);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(serviceIntent);*/
moveTaskToBack(true); //activity.moveTaskToBack(true);
}
private void stopPlayService() {
System.out.println("stopPlayService");
try {
stopService(serviceIntent);
} catch (SecurityException e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void playAudio() {
System.out.println("playAudio");
serviceIntent.putExtra("AudioLink", stream);
// serviceIntent.putExtra("SimpleAudioLink", stream);
try {
startService(serviceIntent);
} catch (SecurityException e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onMusicStopped() {
System.out.println("onMusicStopped");
imagePlayPause.setImageResource(R.drawable.play_icon);
musicPlaying = false;
}
}
MyPlayService class.
package com.jiat.yesradio;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyPlayService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnInfoListener,
MediaPlayer.OnBufferingUpdateListener {
private MediaPlayer mediaPlayer;
String link;
private MusicStoppedListener musicStoppedListener;
Context context;
public MyPlayService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
System.out.println("onBind");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
link = intent.getStringExtra("AudioLink");
mediaPlayer.reset();
musicStoppedListener = (MusicStoppedListener) ApplicationClass.context;
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setDataSource(link);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy");
if (mediaPlayer != null) {
System.out.println("onDestroy1");
if (mediaPlayer.isPlaying()) {
System.out.println("onDestroy2");
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
System.out.println("onBufferingUpdate");
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
/* if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
musicStoppedListener.onMusicStopped();
stopSelf();*/
System.out.println("onCompletion");
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int i1) {
System.out.println("onError");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this, "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA_ERROR_SERVER_DIED", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA_ERROR_UNKNOWN", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
System.out.println("onInfo");
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
System.out.println("onPrepared");
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
System.out.println("onSeekComplete");
}
}
Related
I created a virtual assistant app in Android Studio and it working fine until I exit the app window and the process stops. I want to make the app run in the background always so when it get's the wake word anytime it will respond. I tried using a Service but I couldn't make it work.
Can you help me please?
This is my code:
package com.eylon.jarvis;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.Locale;
import ai.picovoice.porcupine.Porcupine;
import ai.picovoice.porcupine.PorcupineActivationException;
import ai.picovoice.porcupine.PorcupineActivationLimitException;
import ai.picovoice.porcupine.PorcupineActivationRefusedException;
import ai.picovoice.porcupine.PorcupineActivationThrottledException;
import ai.picovoice.porcupine.PorcupineException;
import ai.picovoice.porcupine.PorcupineInvalidArgumentException;
import ai.picovoice.porcupine.PorcupineManager;
import ai.picovoice.porcupine.PorcupineManagerCallback;
enum AppState {
STOPPED,
WAKEWORD,
STT
}
public class MainActivity extends AppCompatActivity {
private static final String ACCESS_KEY = "Oc8ZOSkVtJHWKhVW3iGMedHDSCSXn6P4vQtrQBl8hNLXwLmxLhs2AA==";
private PorcupineManager porcupineManager = null;
TextView textView;
ToggleButton button;
private SpeechRecognizer speechRecognizer;
private Intent speechRecognizerIntent;
private AppState currentState;
private void displayError(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private final PorcupineManagerCallback porcupineManagerCallback = new PorcupineManagerCallback() {
#Override
public void invoke(int keywordIndex) {
runOnUiThread(() -> {
textView.setText("");
try {
// need to stop porcupine manager before speechRecognizer can start listening.
porcupineManager.stop();
} catch (PorcupineException e) {
displayError("Failed to stop Porcupine.");
return;
}
speechRecognizer.startListening(speechRecognizerIntent);
currentState = AppState.STT;
});
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text1);
button = findViewById(R.id.button1);
if (!SpeechRecognizer.isRecognitionAvailable(this)) {
displayError("Speech Recognition not available.");
}
// Creating the Intent of the Google speech to text and adding extra variables.
speechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en-US");
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, "en-US");
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Start speaking");
try {
porcupineManager = new PorcupineManager.Builder()
.setAccessKey(ACCESS_KEY)
.setKeyword(Porcupine.BuiltInKeyword.JARVIS)
.setSensitivity(0.7f)
.build(getApplicationContext(), porcupineManagerCallback);
} catch (PorcupineInvalidArgumentException e) {
onPorcupineInitError(
String.format("%s\nEnsure your accessKey '%s' is a valid access key.", e.getMessage(), ACCESS_KEY)
);
} catch (PorcupineActivationException e) {
onPorcupineInitError("AccessKey activation error");
} catch (PorcupineActivationLimitException e) {
onPorcupineInitError("AccessKey reached its device limit");
} catch (PorcupineActivationRefusedException e) {
onPorcupineInitError("AccessKey refused");
} catch (PorcupineActivationThrottledException e) {
onPorcupineInitError("AccessKey has been throttled");
} catch (PorcupineException e) {
onPorcupineInitError("Failed to initialize Porcupine " + e.getMessage());
}
currentState = AppState.STOPPED;
}
private void onPorcupineInitError(final String errorMessage) {
runOnUiThread(() -> {
TextView errorText = findViewById(R.id.text1);
errorText.setText(errorMessage);
ToggleButton recordButton = findViewById(R.id.button1);
recordButton.setChecked(false);
recordButton.setEnabled(false);
});
}
#Override
protected void onStop() {
if (button.isChecked()) {
stopService();
button.toggle();
speechRecognizer.destroy();
}
super.onStop();
}
private boolean hasRecordPermission() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED;
}
private void requestRecordPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},
0);
}
#SuppressLint("SetTextI18n")
private void playback(int milliSeconds) {
speechRecognizer.stopListening();
currentState = AppState.WAKEWORD;
new Handler(Looper.getMainLooper()).postDelayed(() -> {
if (currentState == AppState.WAKEWORD) {
porcupineManager.start();
textView.setText("Listening for " + Porcupine.BuiltInKeyword.JARVIS + " ...");
}
}, milliSeconds);
}
private void stopService() {
if (porcupineManager != null) {
try {
porcupineManager.stop();
} catch (PorcupineException e) {
displayError("Failed to stop porcupine.");
}
}
textView.setText("");
speechRecognizer.stopListening();
speechRecognizer.destroy();
currentState = AppState.STOPPED;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) {
displayError("Microphone permission is required for this app!");
requestRecordPermission();
} else {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new SpeechListener());
playback(0);
}
}
public void process(View view) {
if (button.isChecked()) {
if (hasRecordPermission()) {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new SpeechListener());
playback(0);
} else {
requestRecordPermission();
}
} else {
stopService();
}
}
private class SpeechListener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#SuppressLint("SwitchIntDef")
#Override
public void onError(int error) {
switch (error) {
case SpeechRecognizer.ERROR_AUDIO:
displayError("Error recording audio.");
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
displayError("Insufficient permissions.");
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
case SpeechRecognizer.ERROR_NETWORK:
displayError("Network Error.");
break;
case SpeechRecognizer.ERROR_NO_MATCH:
if (button.isChecked()) {
displayError("No recognition result matched.");
playback(1000);
}
case SpeechRecognizer.ERROR_CLIENT:
return;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
displayError("Recognition service is busy.");
break;
case SpeechRecognizer.ERROR_SERVER:
displayError("Server Error.");
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
displayError("No speech input.");
break;
default:
displayError("Something wrong occurred.");
}
stopService();
button.toggle();
}
#Override
public void onResults(Bundle results) {
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
audioResponseSelecting(data.get(0).toLowerCase(Locale.ROOT));
textView.setText(data.get(0));
playback(3000);
}
#Override
public void onPartialResults(Bundle partialResults) {
ArrayList<String> data = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
audioResponseSelecting(data.get(0).toLowerCase(Locale.ROOT));
textView.setText(data.get(0));
}
#Override
public void onEvent(int eventType, Bundle params) {
}
}
// The response selecting function.
public void audioResponseSelecting(String transcript)
{
if (transcript.equals(("Good morning").toLowerCase(Locale.ROOT)))
{
executeResponse(R.raw.good_morning);
}
else if (transcript.equals(("Who is your creator").toLowerCase(Locale.ROOT)))
{
executeResponse(R.raw.creator);
}
}
// The audio file response execution function.
public void executeResponse(final int audio)
{
MediaPlayer response = MediaPlayer.create(MainActivity.this, audio);
response.start();
}
}
By design, all SpeechRecognizer's methods "must be invoked only from the main application thread."
Main application thread is also referred to as "UI thread".
This means that SpeechRecognizer cannot run in a service.
I am a newbie in Android Developer
I am building a game app on Android Studio. But, I have had a problem about Background music while playing game. I have used Bound Service to handle through the class: MusicService extends Service implements MediaPlayer.OnErrorListener. But, my App was stopped when I run.
I have tried to fixed and explored solutions, but, I can't run app...
This is source code:
MusicService.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MusicService extends Service implements MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MediaPlayer Player;
public MusicService() {
}
public class ServiceBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
Player = MediaPlayer.create(this, R.raw.one);
mPlayer.setOnErrorListener(this);
if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}
public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();
}
}
public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}
and, MainActivity.java
public class MainActivity extends AppCompatActivity {
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.ServiceBinder binder = (MusicService.ServiceBinder)service;
mServ =binder.getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
// Activity create UI its
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Activity start.
#Override
protected void onStart() {
super.onStart();
// create Intent for MusicService.
Intent intent = new Intent(MainActivity.this,MusicService.class);
// call method bindService(..) to bind activity
this.bindService(intent, Scon, Context.BIND_AUTO_CREATE);
}
//Activity stop
#Override
protected void onStop() {
super.onStop();
if (mIsBound) {
this.unbindService(Scon);
mIsBound = false;
}
}
Then, I didn't also forget add the code following in AndroidManifest
<service
android:name=".MusicService"
android:enabled="true"
android:exported="true"></service>
That's all problems mine. This makes me so confuse
Help you, please
Thank you very much
Can you add more log debug in logcat? Not sure but I guess problem is you call:
mPlayer.start();
in onStartComand(). Your service should implement MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,MediaPlayer.OnCompletionListener and above function should be call in
void onPrepared(MediaPlayer mp)
i try to run a code of application game 3D but the application don't work in my device and in onglet 'android Monitor' in android studio i have this fatal exception :
07-22 15:40:29.015 22222-22245/? E/AndroidRuntime: FATAL EXCEPTION: GLThread 4132
Process: com.anisbulbul.car.race, PID: 22222
java.lang.NoClassDefFoundError: com.badlogic.gdx.backends.android.AndroidGL10
at com.badlogic.gdx.backends.android.AndroidGraphics.setupGL(AndroidGraphics.java:301)
at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceCreated(AndroidGraphics.java:346)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1500)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1239)
and this is the code of the activity
// Copyright: 2015, anisbulbul
// Home page: http://www.codecanyon.net/user/anisbulbul
package com.anisbulbul.car.race;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.anisbulbul.car.race.assets.GameAssets;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
public class MainActivity extends AndroidApplication implements
GameHelper.GameHelperListener, ActionResolver {
protected AdView adViewMain;
private GameHelper gameHelper;
protected View gameView;
AdView adView;
RelativeLayout layout;
private InterstitialAd interstitialAd;
private static final String AD_UNIT_ID_BANNER = "ca-app-pub-8606268298440779/7190429247";
private static final String AD_UNIT_ID_INTERSTITIAL = "ca-app-pub-8606268298440779/5713696049";
private static final String MORE_APPS_URL = "http://codecanyon.net/user/anisbulbul/portfolio";
private static boolean IS_ADMOB_ACTIVE = true;
private static boolean DEBUG = false;
private static boolean IS_PLAY_SERVICE_ACTIVE = true;
private static String GOOGLE_PLAY_URL;
private static String FACEBOOK_SHARE_URL;
private static String TWITTER_SHARE_URL;
private static String GOOGLE_PLUS_SHARE_URL;
private static String BLOG_URL;
#Override
public String[] getAchievmentIDs() {
String achievmentIDs[] = {
getResources().getString(R.string.achievement_bigginer),
getResources().getString(R.string.achievement_starter_good),
getResources().getString(R.string.achievement_race_cup_2),
getResources().getString(R.string.achievement_after_death),
getResources().getString(R.string.achievement_in_the_last_station) };
return achievmentIDs;
}
#Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
private AdView createAdView() {
this.adViewMain = new AdView(this);
this.adViewMain.setAdSize(AdSize.SMART_BANNER);
this.adViewMain.setAdUnitId(AD_UNIT_ID_BANNER);
this.adViewMain.setId(12345);
LayoutParams var1 = new LayoutParams(-1, -2);
var1.addRule(12, -1);
var1.addRule(14, -1);
this.adViewMain.setLayoutParams(var1);
this.adViewMain.setBackgroundColor(-16777216);
return this.adViewMain;
}
private View createGameView(AndroidApplicationConfiguration var1) {
this.gameView = this.initializeForView(new CarRace3D(this), var1);
LayoutParams var2 = new LayoutParams(-1, -2);
var2.addRule(10, -1);
var2.addRule(14, -1);
var2.addRule(2, this.adViewMain.getId());
this.gameView.setLayoutParams(var2);
return this.gameView;
}
private void startAdvertising(AdView var1) {
var1.loadAd((new AdRequest.Builder()).build());
}
#Override
public void faceBookPost(String fbMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"https://facebook.com/share?url=https://play.google.com/store/apps/details?id="+getPackageName()+"&title="+fbMessage);
sendIntent.setType("text/plain");
this.startActivity(sendIntent);
}
#Override
public void googlePlusPost(String gplusMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"https://plus.google.com/share?url=https://play.google.com/store/apps/details?id="+getPackageName()+"&title="+gplusMessage);
sendIntent.setType("text/plain");
this.startActivity(sendIntent);
}
#Override
public void twitterPost(String twMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"https://twitter.com/intent/tweet?url=https://play.google.com/store/apps/details?id="+getPackageName()+"&related=codecanyon.net&text=i got high score"+twMessage);
sendIntent.setType("text/plain");
this.startActivity(sendIntent);
}
#Override
public void getAchievementsGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(Games.Achievements
.getAchievementsIntent(this.gameHelper.getApiClient()), 101);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void getLeaderboardHighScoreGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(
Games.Leaderboards.getLeaderboardIntent(
this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_high_score_race)),
100);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void getLeaderboardTrophyGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(
Games.Leaderboards.getLeaderboardIntent(
this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_race_trophy)),
100);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void getAllLeaderboardGPGS() {
if (this.gameHelper.isSignedIn()) {
this.startActivityForResult(Games.Leaderboards
.getAllLeaderboardsIntent(this.gameHelper.getApiClient()),
1);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public boolean getSignedInGPGS() {
return this.gameHelper.isSignedIn();
}
#Override
public void loginGPGS() {
if(IS_PLAY_SERVICE_ACTIVE){
try {
this.runOnUiThread(new Runnable() {
public void run() {
MainActivity.this.gameHelper.beginUserInitiatedSignIn();
}
});
} catch (Exception var2) {
;
}
}
}
public void onActivityResult(int var1, int var2, Intent var3) {
super.onActivityResult(var1, var2, var3);
this.gameHelper.onActivityResult(var1, var2, var3);
}
public void onBackPressed() {
GameAssets.isGamePause = true;
if (GameAssets.isGameSound) {
GameAssets.raceMusic.pause();
GameAssets.accidentMusic.pause();
GameAssets.moveMusic.pause();
}
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setTitle(R.string.app_name);
ScrollView scrollView = new ScrollView(MainActivity.this);
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText(R.string.back_option_text);
textView.setPadding(4, 0, 4, 10);
dialogLayout.addView(textView);
Button resumeButton = new Button(this);
resumeButton.setText("Resume");
resumeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(resumeButton);
Button moreGamesApps = new Button(this);
moreGamesApps.setText("More Games & Apps");
moreGamesApps.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(MORE_APPS_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(moreGamesApps);
Button rateButton = new Button(this);
rateButton.setText("Rate Game");
rateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(GOOGLE_PLAY_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(rateButton);
Button facebookButton = new Button(this);
facebookButton.setText("Facebook");
facebookButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(FACEBOOK_SHARE_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(facebookButton);
Button twitterButton = new Button(this);
twitterButton.setText("Twitter");
twitterButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(TWITTER_SHARE_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(twitterButton);
Button googlePlusButton = new Button(this);
googlePlusButton.setText("Google Plus");
googlePlusButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(GOOGLE_PLUS_SHARE_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(googlePlusButton);
Button blogButton = new Button(this);
blogButton.setText("Blog");
blogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(BLOG_URL)));
dialog.dismiss();
GameAssets.isGamePause = false;
}
});
dialogLayout.addView(blogButton);
Button quitButton = new Button(this);
quitButton.setText("Quit");
quitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
dialogLayout.addView(quitButton);
scrollView.addView(dialogLayout);
dialog.setContentView(scrollView);
dialog.show();
dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
R.drawable.icon);
}
public void onCreate(Bundle var1) {
super.onCreate(var1);
this.getWindow().addFlags(128);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
cfg.useAccelerometer = true;
cfg.useCompass = false;
FACEBOOK_SHARE_URL = "https://www.facebook.com/sharer/sharer.php?display=popup&u=http%3A%2F%2Fcodecanyon.net%2Fitem%2Frecorder-and-equalizer-player-with-effect%2F9904887%3Futm_source%3Dsharefb";
GOOGLE_PLAY_URL = "https://play.google.com/store/apps/developer?id="
+ getPackageName();
TWITTER_SHARE_URL = "https://twitter.com/intent/tweet?text=Check+out+%27Recorder+and+Equalizer+Player+with+Effect%27+on+%23EnvatoMarket+%23codecanyon&url=http%3A%2F%2Fcodecanyon.net%2Fitem%2Frecorder-and-equalizer-player-with-effect%2F9904887%3Futm_source%3Dsharetw";
GOOGLE_PLUS_SHARE_URL = "https://plus.google.com/share?url=http%3A%2F%2Fcodecanyon.net%2Fitem%2Frecorder-and-equalizer-player-with-effect%2F9904887%3Futm_source%3Dsharegp";
BLOG_URL = "http://anisbulbul.blogspot.com/";
this.requestWindowFeature(1);
this.getWindow().setFlags(1024, 1024);
this.getWindow().clearFlags(2048);
layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(-1, -1));
adView = this.createAdView();
// layout.addView(adView);
layout.addView(this.createGameView(cfg));
this.setContentView(layout);
this.startAdvertising(adView);
this.interstitialAd = new InterstitialAd(this);
this.interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
if(DEBUG){
Toast.makeText(getApplicationContext(),
"Finished Loading Interstitial", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onAdClosed() {
if(DEBUG){
Toast.makeText(getApplicationContext(), "Closed Interstitial",
Toast.LENGTH_SHORT).show();
}
}
});
if (this.gameHelper == null) {
this.gameHelper = new GameHelper(this, 1);
this.gameHelper.enableDebugLog(true);
}
this.gameHelper.setup(this);
}
#Override
public void onSignInFailed() {
}
#Override
public void onSignInSucceeded() {
}
#Override
public void onStart() {
super.onStart();
if(IS_PLAY_SERVICE_ACTIVE){
this.gameHelper.onStart(this);
}
}
#Override
public void onStop() {
super.onStop();
if(IS_PLAY_SERVICE_ACTIVE){
this.gameHelper.onStop();
}
}
#Override
public void openUri(String uri) {
this.startActivity(new Intent("android.intent.action.VIEW", Uri
.parse(uri)));
}
#Override
public void quitApplication() {
}
#Override
public void submitScoreGPGS(long score) {
if(this.gameHelper.isSignedIn()){
Games.Leaderboards.submitScore(this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_high_score_race), score);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void submitTrophyGPGS(long score) {
if(this.gameHelper.isSignedIn()){
Games.Leaderboards.submitScore(this.gameHelper.getApiClient(),
this.getString(R.string.leaderboard_race_trophy), score);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void unlockAchievementGPGS(String achievementId) {
if(this.gameHelper.isSignedIn()){
Games.Achievements
.unlock(this.gameHelper.getApiClient(), achievementId);
} else if (!this.gameHelper.isConnecting()) {
this.loginGPGS();
return;
}
}
#Override
public void showRated() {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ getPackageName())));
} catch (ActivityNotFoundException e) {
}
}
#Override
public void showShare() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, " Brain Puzzle Game "
+ " Visit: http://play.google.com/store/apps/details?id="
+ getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
public void addLayout() {
try {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded()) {
layout.addView(adView);
}
}
});
} catch (Exception e) {
}
}
#Override
public void showOrLoadInterstital() {
if (IS_ADMOB_ACTIVE) {
try {
runOnUiThread(new Runnable() {
public void run() {
addLayout();
if (interstitialAd.isLoaded()) {
interstitialAd.show();
if(DEBUG){
Toast.makeText(getApplicationContext(),
"Showing Interstitial", Toast.LENGTH_SHORT)
.show();
}
} else {
AdRequest interstitialRequest = new AdRequest.Builder()
.build();
interstitialAd.loadAd(interstitialRequest);
if(DEBUG){
Toast.makeText(getApplicationContext(),
"Loading Interstitial", Toast.LENGTH_SHORT)
.show();
}
}
}
});
} catch (Exception e) {
}
}
}
}
build.gradle file :
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.anisbulbul.car.race"
minSdkVersion 9
targetSdkVersion 25
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile project(':_3DCarRace')
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.android.gms:play-services:5.+'
//compile files('libs/gdx-backend-android-sources.jar')
//compile files('libs/gdx-backend-android.jar')
//compile "com.android.support:support-v7:25.3.1"
compile 'com.deadpan-gamez:libGdx-game-common:1.22'
compile fileTree(include: ['*.jar'], dir: 'libs')
}
i try to fix it but no solution
Thank you in advance.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hi I was following a tutorial I found to make an app that plays a radio, the app works until you exit because then the sound stops. I have researched and found out that it needs to be a service but I am not sure how to change it to a service, this is the code I used.
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
I tried changing it but I am not sure how to put the functions from the main activity into a new service and then run it.
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
} // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I tried using the above code but I do not know how to start the action and whether or not it will work.
Thank you for reading :)
Call a service from your main activity.
startService(new Intent(MusicService.ACTION_PLAY));
your service class.
public class MusicService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
return START_STICKY;
}
I am new to Android. I'm trying to create a music player which will play specific MP3 based on the count (controlled by Rc variable) and based on the button sequence (controlled by BitCount variable) should change. And I have one stop button by clicking which I should be able to stop the music.
My problem is everything is working fine when UI is on foreground but when screen goes to background then also music start running (it's OK let music be running on background) but when once again I bring my UI from background to foreground than by clicking stop button I am unable to stop the music, it runs continuously. This same problem is happening when I am rotating my mobile.
Code:
package com.example.tallite;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
MediaPlayer OurSong;
public Handler handler1 = new Handler();
Button Start;
Button Stop;
Button Button21;
Button Button22;
Button StopButton;
public int GProgreess=0;
int Rc=0;
int BitCount=6;
int SeekPos=0;
int Period=500;
int BreakVar=0;
Thread myThread ;
public TextView text1,text2,text3,text4;
private SeekBar bar;
private TextView textProgress,textAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
text1 = (TextView)findViewById(R.id.textbit1);
text2 = (TextView)findViewById(R.id.textbit2);
text3 = (TextView)findViewById(R.id.textbit3);
text4 = (TextView)findViewById(R.id.textbit4);
Button21=(Button)findViewById(R.id.button21);
Button22=(Button)findViewById(R.id.button22);
StopButton=(Button)findViewById(R.id.buttonstop);
bar = (SeekBar)findViewById(R.id.seekBar1);
textProgress = (TextView)findViewById(R.id.textViewProgress);
OurSong=MediaPlayer.create(MainActivity.this,R.raw.a);
try {
OurSong.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bar.setOnSeekBarChangeListener(this); // set seekbar listener.
/*handler1.post(runnable1);
stopPlaying();*/
StopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
stopPlaying();
BitCount=5;
handler1.removeCallbacks(runnable1);
}/****End of on clk******/
});/*****End of set on clk listener*****/
Button21.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
stopPlaying();
Rc=0;
BitCount=13;
handler1.removeCallbacks(runnable1);
handler1.post(runnable1);
}/****End of on clk******/
});/*****End of set on clk listener*****/
Button22.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
stopPlaying();
Rc=0;
BitCount=15;
handler1.removeCallbacks(runnable1);
handler1.post(runnable1);
}/****End of on clk******/
});/*****End of set on clk listener*****/
}
#Override
protected void onStart() {
//the activity is become visible.
super.onStart();
/*handler1.removeCallbacks(runnable1);*/
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
//the activity is no longer visible.
super.onStop();
Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
//The activity about to be destroyed.
super.onDestroy();
Toast.makeText(this, "onDestroy()", Toast.LENGTH_LONG).show();
}
private void stopPlaying()
{
if (OurSong != null)
{
OurSong.stop();
OurSong.release();
OurSong = null;
}
}
/* private void stopPlaying()
{
OurSong.stop();
OurSong.release();
}*/
public Runnable runnable1= new Runnable() {
#Override
public void run() {
if(BitCount==13)
{
text1.setText("1");
text2.setText(""+Rc);
text3.setText(""+BitCount);
if(Rc==0||Rc==6||Rc==10)
{
stopPlaying();
OurSong=MediaPlayer.create(MainActivity.this,R.raw.a);
OurSong.start();
}
if(Rc==2||Rc==4||Rc==8||Rc==12)
{
stopPlaying();
OurSong=MediaPlayer.create(MainActivity.this,R.raw.b);
OurSong.start();
}
if(Rc==13)
{
stopPlaying();
OurSong=MediaPlayer.create(MainActivity.this,R.raw.c);
OurSong.start();
}
Rc++;
if(Rc>BitCount)
{
text4.setText(""+Rc);
Rc=0;
}
}/****End of bitcount=13****/
if(BitCount==15)
{
text1.setText("2");
text2.setText(""+Rc);
text3.setText(""+BitCount);
if(Rc==0||Rc==8||Rc==12)
{
stopPlaying();
OurSong=MediaPlayer.create(MainActivity.this,R.raw.a);
OurSong.start();
}
if(Rc==2||Rc==4||Rc==6||Rc==10||Rc==14)
{
stopPlaying();
OurSong=MediaPlayer.create(MainActivity.this,R.raw.b);
OurSong.start();
/* Toast.makeText(getApplicationContext(), "-",
Toast.LENGTH_LONG).show();*/
}
if(Rc==15)
{
stopPlaying();
OurSong=MediaPlayer.create(MainActivity.this,R.raw.c);
OurSong.start();
/*Toast.makeText(getApplicationContext(), "|",
Toast.LENGTH_LONG).show();*/
}
Rc++;
if(Rc>BitCount)
{
text4.setText(""+Rc);
Rc=0;
}
}/***End of bitcount=15***/
if(BitCount==5)
{
text1.setText("Rc"+Rc);
stopPlaying();
}
if(BitCount==6)
{
text1.setText("x"+Rc);
stopPlaying();
}
handler1.postDelayed(runnable1, Period);
}
};
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
GProgreess=progress+20;
textProgress.setText("Bit/Minute: "+(progress+20));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekBar.setSecondaryProgress(seekBar.getProgress());
SeekPos=GProgreess;
Period=(int)(30000/SeekPos);
/*textProgress.setText("Period: "+Period);*/
}
#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;
}
}
When you close your app, ur activity is destroyed and hence reference to ur media player variable is lost. When you recreate ur activity you get a new set of reference and hence ur unable to stop it.
You will have to create a Service name it as MediaPlayerService which will deal with all media related actions like play, pause etc..
You can read about service over here:
http://developer.android.com/guide/components/services.html
If you want an example for media player, you can check RandomMusicPlayer, an excellent media player example provided by android in android sample projects.
Here is my implementation of MediaPlayerService
MediaPlayerService Class:
package com.cyberinsane.musicplayerlibrary;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MediaPlayerService extends Service implements OnCompletionListener, OnPreparedListener, OnErrorListener {
private static final int NOTIFICATION_ID = 1;
public static final String INTENT_URL = "url";
public enum MediaState {
Playing, Paused, Stopped
}
private MediaState mState = MediaState.Stopped;
private MediaPlayer mPlayer;
private NotificationManager mNotificationManager;
public String mCurrentUrl = "";
public static final String ACTION_TOGGLE_PLAYBACK = "com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK";
public static final String ACTION_PLAY = "com.cyberinsane.musicplayerlibrary.action.PLAY";
public static final String ACTION_PAUSE = "com.cyberinsane.musicplayerlibrary.action.PAUSE";
public static final String ACTION_STOP = "com.cyberinsane.musicplayerlibrary.action.STOP";
#Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
String url = intent.getExtras().getString(INTENT_URL);
if (url != null) {
if (!url.equals(mCurrentUrl)) {
mCurrentUrl = url;
mState = MediaState.Stopped;
relaxResources(true);
processPlayRequest();
} else {
if (action.equals(ACTION_TOGGLE_PLAYBACK)) {
processTogglePlaybackRequest();
} else if (action.equals(ACTION_PLAY)) {
processPlayRequest();
} else if (action.equals(ACTION_PAUSE)) {
processPauseRequest();
} else if (action.equals(ACTION_STOP)) {
processStopRequest(false);
}
}
}
}
return START_STICKY;
}
private void processTogglePlaybackRequest() {
if (mState == MediaState.Paused || mState == MediaState.Stopped) {
processPlayRequest();
} else {
processPauseRequest();
}
}
private void processPlayRequest() {
try {
if (mState == MediaState.Stopped) {
createMediaPlayerIfNeeded();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentUrl));
mPlayer.prepare();
} else if (mState == MediaState.Paused) {
mState = MediaState.Playing;
setUpAsForeground("Playing...");
if (!mPlayer.isPlaying()) {
mPlayer.start();
if (mIMediaPlayer != null) {
mIMediaPlayer.onAudioPlay();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void processPauseRequest() {
if (mState == MediaState.Playing) {
mState = MediaState.Paused;
mPlayer.pause();
relaxResources(false);
if (mIMediaPlayer != null) {
mIMediaPlayer.onAudioPause();
}
}
}
private void processStopRequest(boolean force) {
if (mState == MediaState.Playing || mState == MediaState.Paused || force) {
mState = MediaState.Stopped;
relaxResources(true);
stopSelf();
}
}
private void createMediaPlayerIfNeeded() {
if (mPlayer == null) {
mPlayer = new MediaPlayer();
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
} else
mPlayer.reset();
}
private void relaxResources(boolean releaseMediaPlayer) {
stopForeground(true);
if (releaseMediaPlayer && mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), "Media player error! Resetting.", Toast.LENGTH_SHORT).show();
Log.e("MusicPlayer", "Error: what=" + String.valueOf(what) + ", extra=" + String.valueOf(extra));
mState = MediaState.Stopped;
relaxResources(true);
if (mIMediaPlayer != null) {
mIMediaPlayer.onError();
}
return true; // true indicates we handled the error
}
#Override
public void onPrepared(MediaPlayer mp) {
mState = MediaState.Playing;
updateNotification("Playing...");
if (!mPlayer.isPlaying()) {
mPlayer.start();
if (mIMediaPlayer != null) {
mIMediaPlayer.onAudioPlay();
}
}
}
#Override
public void onCompletion(MediaPlayer mp) {
mState = MediaState.Stopped;
relaxResources(true);
stopSelf();
if (mIMediaPlayer != null) {
mIMediaPlayer.onAudioStop();
}
}
/**
* Updates the notification.
*/
private void updateNotification(String text) {
mNotificationManager.notify(NOTIFICATION_ID, buildNotification(text).build());
}
private void setUpAsForeground(String text) {
startForeground(NOTIFICATION_ID, buildNotification(text).build());
}
private NotificationCompat.Builder buildNotification(String text) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setContentTitle("Cyberinsane MusicPlayer")
.setContentText(text)
.setContentIntent(
PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(),
MediaPlayerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
.setContentInfo("Awesome");
return builder;
}
#Override
public void onDestroy() {
mState = MediaState.Stopped;
relaxResources(true);
}
public class LocalBinder extends Binder {
MediaPlayerService getService() {
return MediaPlayerService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private IMediaPlayer mIMediaPlayer;
public MediaPlayer getMediaPlayer() {
return mPlayer;
}
public void setIMediaPlayer(IMediaPlayer mediaPlayer) {
mIMediaPlayer = mediaPlayer;
}
public MediaState getMediaState() {
return mState;
}
public boolean isPlaying() {
return (mState == MediaState.Playing);
}
public String getCurrentUrl() {
return mCurrentUrl;
}
public long duration() {
if (mPlayer != null) {
return mPlayer.getDuration();
}
return 0;
}
public long position() {
if (mPlayer != null) {
return mPlayer.getCurrentPosition();
}
return 0;
}
public void seekTo(long position) {
if (mPlayer != null) {
mPlayer.seekTo((int) position);
}
}
}
MediaPlayerActivity Class:
package com.cyberinsane.musicplayerlibrary;
import java.io.File;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MediaPlayerActivity extends Activity implements IMediaPlayer {
private ImageButton mButtonPlay;
private EditText mEditTextUrl;
private SeekBar mSeekBarProgress;
private boolean mIsBound;
private String mExtStorePath;
private MediaPlayerService mMediaService;
private Handler mSeekHandler = new Handler();
private Runnable mSeekRunnable = new Runnable() {
#Override
public void run() {
seekStartUpdation();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media_player_activity);
mButtonPlay = (ImageButton) findViewById(R.id.buttonPlay);
mEditTextUrl = (EditText) findViewById(R.id.editTextURL);
mSeekBarProgress = (SeekBar) findViewById(R.id.seekBarMediaProgress);
mExtStorePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
doBindService();
initListeners();
}
private void initListeners() {
mButtonPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String urlExt = mEditTextUrl.getText().toString();
if (urlExt != null && !urlExt.equals("")) {
String url = mExtStorePath + urlExt;
startService(new Intent(MediaPlayerService.ACTION_TOGGLE_PLAYBACK).putExtra(
MediaPlayerService.INTENT_URL, url));
}
}
});
mSeekBarProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mMediaService.seekTo(seekBar.getProgress());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// empty
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// empty
}
});
}
#Override
protected void onResume() {
super.onResume();
doBindService();
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
#Override
protected void onPause() {
super.onPause();
doUnbindService();
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
mMediaService = ((MediaPlayerService.LocalBinder) service).getService();
mMediaService.setIMediaPlayer(MediaPlayerActivity.this);
setControlState();
}
#Override
public void onServiceDisconnected(ComponentName className) {
mMediaService = null;
}
};
private void doBindService() {
bindService(new Intent(MediaPlayerActivity.this, MediaPlayerService.class), mConnection,
Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
public void onAudioPlay() {
setPlayerState(true);
}
#Override
public void onAudioPause() {
setPlayerState(false);
}
#Override
public void onAudioStop() {
setPlayerState(false);
mSeekBarProgress.setProgress(0);
}
#Override
public void onError() {
// handle errors here
}
private void setControlState() {
if (mMediaService.isPlaying()) {
mEditTextUrl.setText(mMediaService.getCurrentUrl().replace(mExtStorePath, ""));
setPlayerState(true);
} else {
setPlayerState(false);
}
}
public void setPlayerState(boolean isPlaying) {
if (isPlaying) {
mButtonPlay.setImageResource(R.drawable.ic_pause);
mSeekBarProgress.setMax((int) mMediaService.duration());
seekStartUpdation();
} else {
mButtonPlay.setImageResource(R.drawable.ic_play);
seekStopUpdate();
}
}
public void seekStartUpdation() {
mSeekBarProgress.setProgress((int) mMediaService.position());
mSeekHandler.postDelayed(mSeekRunnable, 1000);
}
public void seekStopUpdate() {
mSeekHandler.removeCallbacks(mSeekRunnable);
}
}
Media Player Event Listener
package com.cyberinsane.musicplayerlibrary;
public interface IMediaPlayer {
public void onAudioPlay();
public void onAudioPause();
public void onAudioStop();
public void onError();
}
And finally my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyberinsane.musicplayerlibrary"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerActivity"
android:label="#string/app_name"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.cyberinsane.musicplayerlibrary.MediaPlayerService"
android:exported="false" >
<intent-filter>
<action android:name="com.cyberinsane.musicplayerlibrary.action.TOGGLE_PLAYBACK" />
<action android:name="com.cyberinsane.musicplayerlibrary.action.PLAY" />
<action android:name="com.cyberinsane.musicplayerlibrary.action.PAUSE" />
<action android:name="com.cyberinsane.musicplayerlibrary.action.SKIP" />
<action android:name="com.cyberinsane.musicplayerlibrary.action.REWIND" />
<action android:name="com.cyberinsane.musicplayerlibrary.action.STOP" />
</intent-filter>
</service>
</application>
</manifest>