I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity
public class Main extends Activity implements MediaPlayerControl {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
Handler mHandler = new Handler();
public TextView subtitles,subtitles2;
static Context context;
#SuppressLint("HandlerLeak")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.Main);
subtitles = (TextView) findViewById(R.id.subs2);
subtitles2 = (TextView) findViewById(R.id.subs21);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this)
/*
* {
*
* #Override public void hide() { mMediaController.show(0); } }
*/;
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.AudioView));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Next button clicked
Intent intent = new Intent(Main.this, Hello.class);
startActivity(intent);
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
// Previous button clicked
Intent intent = new Intent(Main.this, Sorry.class);
startActivity(intent);
}
});
// String audioFile = "" ;
try {
mMediaPlayer.setDataSource(this, Uri
.parse("android.resource://com.app.suadmon/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("1111+");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("555+");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("666+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("777+");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("888+");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("999+");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Thank you");
subtitles2.setText(".............");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
// mMediaPlayer.reset();
mMediaPlayer.start();
}
});
}
});
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Intent stopplay = new Intent(Main.this, Hello.class);
startActivity(stopplay);
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void pause() {
// TODO Auto-generated method stub
mMediaPlayer.pause();
}
protected void onPause() {
super.onPause();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.pause();
}
protected void onResume() {
super.onResume();
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
}
// public void onUserLeaveHint(){
// mMediaPlayer.stop();
// super.onUserLeaveHint();
// }
/*
* public void stopPlayback(){ mMediaPlayer.stop(); }
*/
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
Intent intent = new Intent(Main.this, Show.class);
startActivity(intent);
super.onBackPressed();
}
}
and Log Cat's here.
How can I fix this. I have no idea.
Can anyone help me. Please !!!
You need to stop and release the media player before your activity finishes. Try adding this to your activity:
#Override
protected void onDestroy() {
super.onDestroy();
if(mMediaPlayer != null)
{
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
Related
I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.
Here's my code currently, everything works except background audio.
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageButton btn;
private ImageView img;
private boolean playPause;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
//mp.start();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
img.setImageResource(R.drawable.ic_toweron);
img.setAlpha(1.0f);
playPause = true;
}
} else {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btn.setBackgroundResource(R.drawable.ic_play_button);
img.setImageResource(R.drawable.ic_toweroff);
img.setAlpha(0.3f);
playPause = false;
}
}
}
});
try {
mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Any help would be much appreciated.
use service to play audio file instant of activity.
here is simple code how to use media player in service.
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
//region "member variable"
boolean isServiceRunning = false;
ArrayList<Song> PlayerList = new ArrayList<>();
MediaPlayer mediaPlayer;
int position = 0;
MainActivity mainActivity;
private final IBinder mBinder = new LocalBinder();
int playingMood;
private final static int MAX_VOLUME = 15;
Toast toast;
public static MusicService objService;
//endregion
//region "service method"
#Override
public void onCreate() {
objService = this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
isServiceRunning = true;
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
// showNotification(false);
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
playPrevious();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
playNext();
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
stop();
stopForeground(true);
stopSelf();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
objService = null;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
//returns the instance of the service
public class LocalBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
//endregion
//region "Media player"
public void SongRequest() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
//Handel UI on main activity
mainActivity.showPlayer();
mediaPlayer = new MediaPlayer();
mainActivity.updatePlayerUI();
prepareMediaPlayer(PlayerList.get(position).getUrl());
} catch (Exception ex) {
ex.printStackTrace();
}
}
void showToast(String text) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
toast.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// try {
mediaPlayer.start();
mainActivity.checkPlaying(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
mainActivity.sentUpdateBroadcast(true);
if (playingMood == 1) {
mediaPlayer.start();
}
if (playingMood == 2) {
playNext();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (mainActivity != null)
mainActivity.updateProgressBuffer(percent);
if (percent == 1)
mainActivity.showPlayer();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
try {
Log.i("MediaPlayer", "error");
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
void startPrepare(String url) {
prepareMediaPlayer(url);
}
void prepareMediaPlayer(String url) {
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(MusicService.this);
mediaPlayer.setOnErrorListener(MusicService.this);
mediaPlayer.setOnCompletionListener(MusicService.this);
mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
//region "media player method"
public boolean play() {
if (mediaPlayer != null) {
switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
isServiceRunning = false;
if (mainActivity != null) {
mainActivity.ShowPlayer(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void playNext() {
if (position < PlayerList.size() - 1) {
position++;
mediaPlayer.stop();
SongRequest();
}
}
public void playPrevious() {
if (position > 0) {
position--;
mediaPlayer.stop();
SongRequest();
}
}
public void onError() {
}
public void onCompletion() {
}
public void onCleanMemory() {
}
public void initilizePlayerList(ArrayList<Song> list, int position) {
this.PlayerList = list;
this.position = position;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
public boolean isRunning() {
return isServiceRunning;
}
public Song getCurrentSong() {
if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
return PlayerList.get(position);
}
return null;
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void seekTo(int duration) {
if (mediaPlayer != null) {
mediaPlayer.seekTo(duration);
}
}
public int getMood() {
return playingMood;
}
public void setMood(int mood) {
playingMood = mood;
}
public void setVolume(int soundVolume) {
if (mediaPlayer != null) {
final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
mediaPlayer.setVolume(volume, volume);
}
}
//endregion
}
you can start your service from activity like this.
public void startMusicService() {
Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
for stop service use this code
public void stopMusicService() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
for bind service with activity use this
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
if (listHolder != null) {
initilizeSongsList(listHolder.list, listHolder.position);
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
where service is music service object in activity MusicService service;
So this is the working service for a single live stream URL thanks to asim.
public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
public static final String ACTION_PLAY = "com.example.action.PLAY";
private static final String STREAM_URL = "...";
private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";
MainActivity mainActivity;
MediaPlayer mediaPlayer = null;
WifiManager.WifiLock wifiLock;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class LocalBinder extends Binder {
public StreamService getServiceInstance() {
return StreamService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
wifiLock.acquire();
try {
// Set the stream URL location
mediaPlayer.setDataSource(TEST_URL);
// prepareAsync must be called after setAudioStreamType and setOnPreparedListener
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public boolean play() {
if (mediaPlayer != null) {
//switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
//player.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if( wifiLock != null) wifiLock.release();
if (mediaPlayer != null) mediaPlayer.release();
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
}
Which is implemented in the main activity:
public class MainActivity extends AppCompatActivity {
private ImageButton btn; // Play | Pause toggle button
private ImageView img; // Radio tower image that alternates between on and off
StreamService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind the view buttons to local variables
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
startStream();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (service.isplaying()) {
Log.d("pause","Pause Playback");
} else {
Log.d("play", "Start Playback");
}
}
});
}
public void startStream() {
Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
serviceIntent.setAction(StreamService.ACTION_PLAY);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stopStream() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
}
Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.
I am able to press the back button when music is not played . But when the music plays and I try to press the back button,it doesn't work. Even on pausing the music, back button not working. Please help what could be the issue. Pasting below a snippet of the code:
Inside MainActivity:
public class MainActivity extends Activity implements MediaPlayerControl {
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound = false;
private MusicController controller;
private boolean paused = false, playbackPaused = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = (ListView) findViewById(R.id.lv_song_list);
songList = new ArrayList<Song>();
getSongList();
Collections.sort(songList, new Comparator<Song>() {
#Override
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
setController();
}
// connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder) service;
// get service
musicSrv = binder.getService();
Log.e("MAIN ACT", "Inside connection");
// pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.e("MAIN ACT", "Inside disconnection");
musicBound = false;
musicSrv = null;
}
};
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
Log.e("MAIN ACT", "Inside onstart" + musicBound);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.e("MAIN ACT", "Inside ondestroy");
musicSrv = null;
}
public void getSongList() {
// retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null,
null);
if (musicCursor != null && musicCursor.moveToFirst()) {
// get columns
int titleColumn = musicCursor.getColumnIndex(MediaColumns.TITLE);
int idColumn = musicCursor.getColumnIndex(BaseColumns._ID);
int artistColumn = musicCursor.getColumnIndex(AudioColumns.ARTIST);
// add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
} while (musicCursor.moveToNext());
}
}
public void songPicked(View view) {
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if (playbackPaused) {
setController();
playbackPaused = false;
}
controller.show(0);
Log.d(this.getClass().getName(), "Inside song picked");
}
private void setController() {
// set the controller up
controller = new MusicController(this);
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.lv_song_list));
controller.setEnabled(true);
}
// play next
private void playNext() {
musicSrv.playNext();
if (playbackPaused) {
setController();
playbackPaused = false;
}
controller.show(0);
}
// play previous
private void playPrev() {
musicSrv.playPrev();
if (playbackPaused) {
setController();
playbackPaused = false;
}
controller.show(0);
}
#Override
protected void onPause() {
super.onPause();
paused = true;
musicSrv.pausePlayer();
}
#Override
protected void onResume() {
super.onResume();
if (paused) {
setController();
paused = false;
}
}
#Override
public void onBackPressed() {
if (musicSrv != null){
super.onBackPressed();
Log.e("MAIN ACT", "Inside onbackpress");
}
}
//
// #Override
// public boolean onKeyDown(int keyCode, KeyEvent event)
// {
// Log.e("MAIN ACT", "Inside onkeydown1");
// if ((keyCode == KeyEvent.KEYCODE_BACK))
// { //Back key pressed
// //Things to Do
// Log.e("MAIN ACT", "Inside onkeydown2");
// if(musicSrv!= null)
// {
// musicSrv.pausePlayer();
// musicSrv=null;
// }
// finish();
// return true;
// }
// return super.onKeyDown(keyCode, event);
// }
#Override
protected void onStop() {
Log.e("MAIN ACT", "Inside onstop");
if (playIntent != null) {
Log.e("MAIN ACT", "Inside onstop1");
unbindService(musicConnection);
musicBound = false;
boolean flagservice = stopService(playIntent);
Log.d("MAIN ACT", "Inside onstop1" + flagservice);
}
controller.hide();
super.onStop();
}
#Override
public void start() {
Log.d(this.getClass().getName(), "START");
musicSrv.go();
}
#Override
public void pause() {
playbackPaused = true;
Log.d(this.getClass().getName(), "PAUSE");
musicSrv.pausePlayer();
}
#Override
public int getDuration() {
if (musicSrv != null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else
return 0;
}
#Override
public int getCurrentPosition() {
if (musicSrv != null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else
return 0;
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public boolean isPlaying() {
if (musicSrv != null && musicBound) {
Log.e("MAIN ACT", "Inside isplaying");
boolean value = musicSrv.isPng();
return value;
} else
return false;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
Service Class:
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
// media player
private MediaPlayer player;
// song list
private ArrayList<Song> songs;
// current position
private int songPosn;
private String songTitle = "";
private static final int NOTIFY_ID = 1;
private boolean shuffle = false;
private Random rand;
private final IBinder musicBind = new MusicBinder();
#Override
public IBinder onBind(Intent intent) {
Log.d(this.getClass().getName(), "BIND");
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(this.getClass().getName(), "UNBIND");
if (player.isPlaying()) {
player.stop();
player.release();
Log.d(this.getClass().getName(), "UNBIND1");
}
return false;
}
#Override
public void onCreate() {
// create the service
// create the service
super.onCreate();
// initialize position
songPosn = 0;
if (player == null) {
// create player
player = new MediaPlayer();
initMusicPlayer();
}
player.reset();
rand = new Random();
}
public void initMusicPlayer() {
// set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Song> theSongs) {
this.songs = theSongs;
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
public void playSong() {
// play a song
player.reset();
// get song
Song playSong = songs.get(songPosn);
songTitle = playSong.getTitle();
// get id
long currSong = playSong.getId();
// set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
Log.d("MUSIC SERVICE", "Inside playsong");
}
public void setShuffle() {
if (shuffle)
shuffle = false;
else
shuffle = true;
}
#Override
public void onCompletion(MediaPlayer mp) {
if (player.isPlaying()) {
mp.stop();
mp.release();
}
if (player.getCurrentPosition() < 0) {
mp.reset();
playNext();
}
}
public void setSong(int songIndex) {
this.songPosn = songIndex;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
Log.e("ERROR", "Inside onError");
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
if (!player.isPlaying()) {
Log.d(this.getClass().getName(), "ONPREPARE");
try
{
mp.start();
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songTitle);
Notification not = builder.build();
Log.e("MUSIC SERVICE", "Inside prepare");
startForeground(NOTIFY_ID, not);
}
public void stop() {
if (!player.isPlaying()) {
player.stop();
Log.d("MUSIC SERVICE", "Inside stop");
}
}
public int getPosn() {
return player.getCurrentPosition();
}
public int getDur() {
return player.getDuration();
}
public boolean isPng() {
return player.isPlaying();
}
public void pausePlayer() {
if (player.isPlaying()) {
player.pause();
}
}
public void seek(int posn) {
player.seekTo(posn);
}
public void go() {
if (!player.isPlaying()) {
Log.d(this.getClass().getName(), "GO");
player.start();
}
}
public void playPrev() {
songPosn--;
if (songPosn < 0)
songPosn = songs.size() - 1;
playSong();
}
// skip to next
public void playNext() {
songPosn++;
if (songPosn >= songs.size())
songPosn = 0;
playSong();
if (shuffle) {
int newSong = songPosn;
while (newSong == songPosn) {
newSong = rand.nextInt(songs.size());
}
songPosn = newSong;
} else {
songPosn++;
if (songPosn <= songs.size())
songPosn = 0;
}
playSong();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(this.getClass().getName(), "ON DESTROY");
stopForeground(true);
if (player != null) {
if (player.isPlaying()) {
player.stop();
}
player.release();
}
}
}
MediaController class:
public class MusicController extends MediaController {
public MusicController(Context c){
super(c);
}
#Override
public void hide(){
Log.d(this.getClass().getName(),"Hide");
super.show();
}
#Override
public void show(int timeout) {
Log.d(this.getClass().getName(),"Show");
super.show(0);
}
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
int keyCode = event.getKeyCode();
if(keyCode == KeyEvent.KEYCODE_BACK)
{
Log.d(this.getClass().getName(),"DispACH");
super.hide();
Context c = getContext();
((Activity) c).finish();
return true;
}
return super.dispatchKeyEvent(event);
}
}
Why do you want to handle the Back key in onKeyDown . The Activity will taken care of finishing itself when back key is pressed.
Remove the onKeyDown method from Activity if your aim is to handle BACK Key there.
You can stop and release the MediaPlayer Instance in Activity onDestroy
Also, If you need to do any specific work on back press , do it in onBackPressed method before calling super.onBackPressed.
If media controller is visible when music play, you need to handle the KEYCODE_BACK to finish the Activity
Add this in your MusicController class
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if(keyCode == KeyEvent.KEYCODE_BACK){
finish();
return true;
}
return super.dispatchKeyEvent(event);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
//release meadia playes here
super.onBackPressed();
}
I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity.
This my code.
public class Main extends Activity implements MediaPlayerControl, OnClickListener {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
public TextView subtitles;
Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
subtitles = (TextView) findViewById(R.id.subs1);
Button btnvol = (Button) findViewById(R.id.volc);
btnvol.setOnClickListener(this);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
try {
mMediaPlayer
.setDataSource(
this,
Uri.parse("android.resource://com.app.audioplayer/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IllegalStateException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("Stupid");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("Sorry");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("555+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("OMG");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("AFK");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("Help me !");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Oh no !");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
mMediaPlayer.start();
}
});
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
// TODO Auto-generated method stub
super.onPause();
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I think I have an error with "if else". How can I fix this ?
Try first mMediaPlayer.stop() and then release it by mMediaPlayer.release()
you can try this,
after release you should set mediaplayer null
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
I am developing an application that, among other things, plays some video files (streaming). I would like to prepare the MediaPlayer in one activity but play the video once it is ready in another activity, so that the user can navigate through the content of the first activity to kill some time. Is this possible?
There is an static MediaPlayer defined in the Application class, like this:
public class EGDF_App extends Application {
private static MediaPlayer mediaPlayer = null;
public static MediaPlayer getMediaPlayer() {
if(mediaPlayer == null)
return new MediaPlayer();
else
return mediaPlayer;
}
}
I have a button with a text (Load video). This text is changed when the video is ready, and when the user clicks on it, it triggers the following activity.
The problem is that I get the following error in LogCat:
09-06 20:43:34.606: D/ChapterPlayer(31999): surfaceCreated called
09-06 20:43:34.684: V/ChapterPlayer(31999): startVideoPlayback
09-06 20:43:34.684: E/MediaPlayer(31999): start called in state 1
09-06 20:43:34.684: E/MediaPlayer(31999): error (-38, 0)
09-06 20:43:34.684: D/ChapterPlayer(31999): surfaceChanged called
09-06 20:43:34.700: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
09-06 20:43:34.715: E/MediaPlayer(31999): Error (-38,0)
09-06 20:43:34.715: D/ChapterPlayer(31999): onCompletion called
09-06 20:43:34.751: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
This is the code contained in the first Activity:
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
if(((String) b.getText()).equals(loadChapter)){
prepareVideo(view);
}else if(((String) b.getText()).equals(watchChapter)){
Intent intent = new Intent(this,ChapterAsyncMediaPlayerActivity.class);
intent.putExtra(Constants.chapterVideoResParse, getIntent().getExtras().getString(Constants.chapterVideoResParse));
intent.putExtra("duration", String.valueOf(duration));
startActivity(intent);
}
}
private void prepareVideo(View view){
MediaPlayer mMediaPlayer;
String path;
final Button button = (Button) view;
String resource = extras.getString(Constants.chapterVideoResParse);
path = SecurityHandler.obtainURL(resource, this.getResources().openRawResource(R.raw.output), 10);
try {
// Gets the media player and set the listeners
mMediaPlayer = EGDF_App.getMediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
button.setText(getString(R.string.watch_chapter_button_text));
Log.i("MediaPlayer", "MediaPlayer ready");
duration = mp.getDuration();
Log.i("Video duration", String.valueOf(mp.getDuration()));
}
});
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is the code in the second Activity:
public class ChapterAsyncMediaPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaPlayerControl {
private static final String TAG = "ChapterPlayer";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private MediaController mController;
private SurfaceView mPreview;
private SurfaceHolder holder;
// private String path;
// private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private Handler handler = new Handler();
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_media_player);
mPreview = (SurfaceView) findViewById(R.id.mediaPlayerSurface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setKeepScreenOn(true);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mController.show();
return false;
}
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = EGDF_App.getMediaPlayer();
// mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
// mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mController = new MediaController(this);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
mController.setMediaPlayer(this);
mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
handler.post(new Runnable(){
#Override
public void run() {
mController.setEnabled(true);
mController.show();
}
});
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
mIsVideoReadyToBePlayed = true;
mController.setMediaPlayer(this);
mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
handler.post(new Runnable(){
#Override
public void run() {
mController.setEnabled(true);
mController.show();
}
});
if (mIsVideoReadyToBePlayed) {
startVideoPlayback();
}
}
#Override
protected void onPause() {
super.onPause();
mMediaPlayer.pause();
}
#Override
protected void onRestart() {
super.onPause();
mMediaPlayer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
mMediaPlayer.setScreenOnWhilePlaying(true);
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(mMediaPlayer != null)
return mMediaPlayer.getCurrentPosition();
else
return 0;
}
#Override
public int getDuration() {
if(mMediaPlayer != null)
return mMediaPlayer.getDuration();
else
return 0;
}
#Override
public boolean isPlaying() {
if(mMediaPlayer != null)
return mMediaPlayer.isPlaying();
else
return false;
}
#Override
public void pause() {
if(mMediaPlayer != null)
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
if(mMediaPlayer != null)
mMediaPlayer.start();
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed) {
startVideoPlayback();
}
}
}
I would appreciate some help or advice. Thanks!
I don't think you're saving the MediaPlayer in your application, you're just returning a new instance of it. Try changing it as so:
public static MediaPlayer getMediaPlayer() {
if(mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
return mediaPlayer;
}
I received a NullPointerException to one of the last lines of an activity regarding a Timer. What happens in the activity is 5 .ogg files is played one after the other. The error points to the the last TimerTask. I post the whole code, please do not get scared, there are many repetitions in the code. I don't know what did the user before the error, it doesn't emerge on my phone.
java.lang.NullPointerException
at com.b2creativedesigns.eyetest.AmslerGrid1$5.run(AmslerGrid1.java:343)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Partial code:
public class AmslerGrid1 extends Activity {
Button btnFinish;
Button btnMute;
ImageView imgAG;
TextView tvResult;
MediaPlayer help1, help2, help3, help4, help5;
int paused=0;
long del=250;
int intentcounter=0;
int p=10;
int length;
private Timer timer;
boolean out;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.amslergrid1);
out = false;
imgAG = (ImageView)findViewById(R.id.imgAG);
tvResult = (TextView)findViewById(R.id.tvAGResult);
btnFinish = (Button)findViewById(R.id.btnAGResult);
btnMute = (Button)findViewById(R.id.btnAGmute);
help1 = MediaPlayer.create(AmslerGrid1.this, R.raw.ag1);
help2 = MediaPlayer.create(AmslerGrid1.this, R.raw.ag2);
help3 = MediaPlayer.create(AmslerGrid1.this, R.raw.ag3);
help4 = MediaPlayer.create(AmslerGrid1.this, R.raw.ag4);
help5 = MediaPlayer.create(AmslerGrid1.this, R.raw.ag5);
timer = new Timer("AmslerGridTimer");
timer.schedule(TimerHelp1, 2000);
help1.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer cim) {
if (paused == 0)
{
}
help1.release();help1=null;
timer = new Timer("AmslerGridTimer");
timer.schedule(TimerHelp2, 1500);
}
});
help2.setOnCompletionListener(new OnCompletionListener() {...
help3.setOnCompletionListener(new OnCompletionListener() {...
help4.setOnCompletionListener(new OnCompletionListener() {...
help5.setOnCompletionListener(new OnCompletionListener() {...
#Override
public void onCompletion(final MediaPlayer cim) {
if (paused == 0)
{
}
help5.release();help5=null;
}
});
}
#Override
protected void onPause() {
super.onPause();
if (help1 != null)
{
help1.pause();
length=help1.getCurrentPosition();
}
...
else if (help5 != null)
{
help5.pause();
length=help5.getCurrentPosition();
}
p=0;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (help1 != null)
{
if (p==0){
help1.seekTo(length); help1.start();
help1.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer cim) {
help1.release();help1=null;
}
});
paused=0;p=1;
}
}
...
else if (help5 != null)
{
if (p==0){
help5.seekTo(length); help5.start();
help5.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer cim) {
help5.release();help5=null;
}
});
paused=0;p=1;
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
timer = null;
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
out = true;
if (help1 != null)
{
help1.stop();
}
else if (help2 != null)
{
help2.stop();
}
else if (help3 != null)
{
help3.stop();
}
else if (help4 != null)
{
help4.stop();
}
else if (help5 != null)
{
help5.stop();
}
Intent intentstart = new Intent(AmslerGrid1.this, MainActivity.class);
intentstart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intentstart);
}
return super.onKeyDown(keyCode, event);
}
private TimerTask TimerHelp1 = new TimerTask() {
#Override
public void run() {
if (!out) help1.start();p=1;
}
};
private TimerTask TimerHelp2 = new TimerTask() {
#Override
public void run() {
if (!out) help2.start();p=1;
}
};
private TimerTask TimerHelp3 = new TimerTask() {
#Override
public void run() {
if (!out) help3.start();p=1;
}
};
private TimerTask TimerHelp4 = new TimerTask() {
#Override
public void run() {
if (!out) help4.start();p=1;
}
};
private TimerTask TimerHelp5 = new TimerTask() {
#Override
public void run() {
if (!out) help5.start();p=1; //error line. Maybe out is null?
}
};
}