Related
Hi am trying to stream online radio while opening my app when buffering first time it runs fine while i close the app and then start again the app it plays from where the player last closed and then stopped after it ends and i have to startup manually to stream the url for current level of radio
my coding:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
ImageView list_activity_check;
ImageView share,speaker,mute, control;
DrawerListAdapter drawerListAdapter;
ListView listview_nav;
private SmallBang mSmallBang;
String [] Items={"Program Lists","Rate app"} ;
int [] images={R.drawable.pro_logo,
R.drawable.rate_icon} ;
String[] titles = {
"Ippadikku Idhayam",
"Akilam 360",
"Cine Pattarai",
"Palsuvai Thoranam",
"Pesum Noolagam",
"Lollu Cafe",
"Kavi Saagaram",
"Aa muthal Akk",
"Thiraicholai",
"Kathamba Saaral",
"Paarkatha Pakkangal",
"Pagadi Panna Porom",
};
public static final String[] fromtime = new String[]{"10:30 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};
public static final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};
Integer[] images0 = {
R.drawable.ipadikku_idhayam,
R.drawable.akilam_360,
R.drawable.cine_pattarai,
R.drawable.palsuvai_thoranam,
R.drawable.pesum_noolagam,
R.drawable.lollu_cafe,
R.drawable.kavi_saagaram,
R.drawable.aa_muthal_akk,
R.drawable.thiraicholai,
R.drawable.kathamba_saaral,
R.drawable.paarkatha_pakkangal,
R.drawable.pagadi_panna_porom,
};
//************* Current Show ***************//
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
ImageView music;
int media1;
int intValue1;
AdapAdapter Adapadapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
//***************************************//
SeekBar seekbar;
AudioManager audioManager;
MediaPlayer media, mediaPlayer;
boolean playPause = false;
boolean intialStage = true;
int intvalue ;
ImageView timer;
private static final int NOTIFICATION_ID = 1;
String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification();
mSmallBang = SmallBang.attach2Window(this);
list_activity_check = (ImageView) findViewById(R.id.list_view);
share = (ImageView) findViewById(R.id.share);
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
control = (ImageView) findViewById(R.id.play);
timer = (ImageView) findViewById(R.id.timer);
//************ Current show ************//
db = this.openOrCreateDatabase("MukilApp",Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");
rowItems = new ArrayList<Program>();
for (int i = 0; i < titles.length; i++) {
Program item = new Program(images0[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
lvshow = (ListView) findViewById(R.id.lvshow);
// listView.setVisibility(View.INVISIBLE);
final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
for (int i = 0; i < adapter.getCount(); i++) {
Program rowItem = (Program) adapter.getItem(i);
iImageId = rowItem.getImageId();
sTitle = rowItem.getTitle();
sFrom = rowItem.getFromtime();
sTo = rowItem.getTotime();
db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");
}
final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
"AND ToTiming >= time('now', 'localtime')\n", null);
if (cView.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView.moveToNext()) {
sImageID.add(cView.getString(1));
iTitle.add(cView.getString(2));
sQuantity.add(cView.getString(3));
sQuantity1.add(cView.getString(4));
Adapadapter = new AdapAdapter(this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
//*************************************//
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
// startActivity(slideactivity, bndlanimation);
startActivityForResult(slideactivity, 1001,bndlanimation);
// finish();
}
});
}
});
media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
media.start();
media.setLooping(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (intialStage) {
new Player()
.execute(URL);
}
intvalue = mediaPlayer.getAudioSessionId();
control.setBackgroundResource(R.drawable.pause);
control.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (playPause == false) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
});
speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
media.setVolume(0, 0);
mediaPlayer.setVolume(0, 0);
speaker.setImageResource(R.drawable.speaker);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
mute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
media.setVolume(1, 1);
mediaPlayer.setVolume(1, 1);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title
}
try {
seekbar = (SeekBar) findViewById(R.id.seekbar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
listview_nav = (ListView) findViewById(R.id.listview_nav);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
listview_nav.setAdapter(drawerListAdapter);
listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
startActivity(in);
}else if(position == 1){
}
}
});
list_activity_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_activity_check.setImageResource(R.drawable.playlist);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
slideactivity.putExtra("sessionvalue", intvalue);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.setImageResource(R.drawable.share_icon);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
if(mediaPlayer == null){//check mp
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
if(media==null){//check mp
if(!media.isPlaying()){
media.start();
}
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void addNotification() {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("MUKIL FM")
.setContentText("Smartah Kelunga Ungal MukilFm");
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
mediaPlayer.prepareAsync();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
String result=data.getStringExtra("result");
if(result.equalsIgnoreCase("STOP")){
onStop();
finish();
}else if(result.equalsIgnoreCase("Do Nothing")){
Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStop() {
super.onStop();
if(media != null){
// media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
// mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
mediaPlayer.release();
media.release();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// super.onBackPressed();
}
}
please help me in fixing this issues..
Thank you in advance..
In your onStop() of your activity stop and release the media player.
Place the below code in your onStop():
#Override
public void onStop() {
super.onStop();
if(media != null){
media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
This is the proper way to stop media player.
Hope it helps:)
I am working on a video player where I have used custom play/pause, fullscreen etc control buttons for normal screen and default media controller for full screen, which I have customized by adding a control button so that the full screen can be exited and switch back to normal small screen. I am able to full screen the video, but once I click that control button in full screen mode, the video stops and goes back to initial state, though the full screen can be switched to normal screen mode. What I should I do or change in my code so that the video can continue playing? I am searching google for the past three hours still could not find an exact solution. :(
Here is my code:
VideoFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
frame = (FrameLayout)rootView.findViewById(R.id.frame);
frame2 = (FrameLayout)rootView.findViewById(R.id.frame2);
frame3 = (FrameLayout)rootView.findViewById(R.id.frame3);
marquee = (TextView)rootView.findViewById(R.id.marquee);
marquee.setSelected(true);//focusing the marquee
video = (VideoView) rootView.findViewById(R.id.videoview1);
seekBar = (SeekBar)rootView.findViewById(R.id.seekBar1);
runtime = (TextView)rootView.findViewById(R.id.runtime);
current = (TextView)rootView.findViewById(R.id.current);
list = (ListView)rootView.findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// _context=this;
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)rootView.findViewById(R.id.play);
back = (ImageButton)rootView.findViewById(R.id.prev);
next = (ImageButton)rootView.findViewById(R.id.next);
full = (ImageButton)rootView.findViewById(R.id.full);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
full.setOnClickListener(this);
//action bar controls
bar = getActivity().getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
seekBar.setBackgroundColor(Color.BLACK);
seekBar.setProgressDrawable(getResources().getDrawable( R.drawable.seekbar));
seekBar.setScaleY(1f);
ShapeDrawable thumb = new ShapeDrawable(new OvalShape());
thumb.getPaint().setColor(Color.CYAN);
thumb.setIntrinsicHeight(20);
thumb.setIntrinsicWidth(20);
seekBar.setThumb(thumb);
EditText editText = new EditText(getActivity().getApplicationContext());
getActivity().getActionBar().setCustomView(editText);
Scanner("/sdcard/");//storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
listAdapter=new VideoListAdapter(getActivity().getApplicationContext(),listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
dm=new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//////////////////changing list item background on click///////////////////
list.setVisibility(View.GONE);
//frame = (FrameLayout)view.findViewById(R.id.frame);
//video = (VideoView) view.findViewById(R.id.videoview1);
//list.setSelection(position);
view.setSelected(true);
///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
list.clearChoices();
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
selected_item=position;
// view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
list.setItemChecked(position, true);
list.setSelection(position);
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
marquee.setText(title);
//bar.setTitle(title);
//Log.e(TAG, name);
//Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
index = position;
play.setImageResource(R.drawable.pause);
frame2.setVisibility(View.VISIBLE);
frame3.setVisibility(View.VISIBLE);
frame.setVisibility(View.VISIBLE); ///is this the problem?
video.setVideoPath(listTest.get(position));
video.requestFocus();
video.start();
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play.setImageResource(R.drawable.play);
video.stopPlayback();
video.clearFocus();
list.setVisibility(View.VISIBLE);
frame.setVisibility(View.GONE);
//seekBar.refreshDrawableState();
frame2.setVisibility(View.GONE);
frame3.setVisibility(View.GONE);
}
});
}
catch(Exception e){e.printStackTrace();}
video.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(video.getDuration());
seekBar.postDelayed(onEverySecond, 1000);
time= video.getDuration();
long sec = (time / 1000) % 60;
long min = (time / (60 * 1000))%60;
long hour = time / (60 * 60 * 1000);
String s = (sec < 10) ? "0" + sec : "" + sec;
String m = (min < 10) ? "0" + min : "" + min;
String h = "" + hour;
String time = "";
if(hour > 0) {
time = h + ":" + m + ":" + s;
} else {
time = m + ":" + s;
}
runtime.setText(""+time);
}
});
}
});
}
return rootView;
}
private Runnable onEverySecond=new Runnable() {
#Override
public void run() {
if(seekBar != null) {
seekBar.setProgress(video.getCurrentPosition());
run = video.getCurrentPosition();
long sec2 = (run / 1000) % 60;
long min2 = (run / (60 * 1000))%60;
long hour2 = run / (60 * 60 * 1000);
String s2 = (sec2 < 10) ? "0" + sec2 : "" + sec2;
String m2 = (min2 < 10) ? "0" + min2 : "" + min2;
String h2 = "" + hour2;
String run = "";
if(hour2 > 0) {
run = h2 + ":" + m2 + ":" + s2;
} else {
run = m2 + ":" + s2;
}
current.setText(""+run);
}
if(video.isPlaying()) {
seekBar.postDelayed(onEverySecond, 1000);
}
}
};
///////////////////orientation change//////////////////////
/* #Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getActivity().getApplicationContext(), "landscape", Toast.LENGTH_SHORT).show();
video.setLayoutParams(new FrameLayout.LayoutParams(600,270));//changing layout size
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(getActivity().getApplicationContext(), "portait", Toast.LENGTH_SHORT).show();
video.setLayoutParams(new FrameLayout.LayoutParams(350, dm.widthPixels));//changing layout size
}
}*/
/////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp4"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(video.isPlaying())
{
video.pause();
progress=video.getCurrentPosition();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
video.start();
seekBar.setProgress(video.getCurrentPosition());
seekBar.setMax(video.getDuration());
seekBar.postDelayed(onEverySecond, 1000);
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
video.stopPlayback();
video.refreshDrawableState();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
selected_item=index;
listAdapter.notifyDataSetChanged();//shifting the highlight to the song played
}
else
{
index = (list.getAdapter().getCount()-1);
selected_item=index;
listAdapter.notifyDataSetChanged();
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
//mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
video.setVideoURI(uri);
} 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();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
}
try {
//video.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
video.start();
title = uri.getLastPathSegment();
marquee.setText(title);
play.setImageResource(R.drawable.pause);
}
if (v.equals(next))
{
video.stopPlayback();
video.refreshDrawableState();
index = index +1;
if(index>(listSoundNames.size()-1))
{
index=0;
}
play.setImageResource(R.drawable.pause);
//index = index +1;
selected_item=index;
listAdapter.notifyDataSetChanged();
//Toast.makeText(MP3.this, ""+selected_item, Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
//mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
video.setVideoURI(uri);
} 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();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
}
try {
//mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
video.start();
title = uri.getLastPathSegment();
marquee.setText(title);
}
if(v.equals(full))
{
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
/*Uri uri = Uri.parse(listTest.get(index).toString());
Toast.makeText(getApplicationContext(), "full", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType((uri), "video/*");
startActivity(intent);*/
Intent intent = new Intent(getActivity().getApplicationContext(),Full.class);
Bundle b2 = new Bundle();
b2.putString("path", uri.toString());
b2.putInt("progress", video.getCurrentPosition());
intent.putExtras(b2);
this.startActivity(intent);
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser) {
// this is when actually seekbar has been seeked to a new position
video.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
int progress = seekBar.getProgress();
if (video != null && video.isPlaying()) {
// Set the position of the currently playing
video.seekTo(progress);
}
}
///////////////////////////stopping the current audio/video when tab is swiped/////////////////////////////////
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
// If we are becoming invisible, then...
///video.start();
//Log.e("MyFragment", "Visible again. Starting audio.");
//video.clearFocus();
//play.setImageResource(R.drawable.pause);
if (!isVisibleToUser) {
Log.e("MyFragment", "Not visible anymore. Stopping audio.");
// TODO stop audio playback
/* play.setImageResource(R.drawable.play);
video.stopPlayback();
video.clearFocus();
list.setVisibility(View.VISIBLE);
frame.setVisibility(View.GONE);
//seekBar.refreshDrawableState();
frame2.setVisibility(View.GONE);
*/
//video.stopPlayback();
video.pause();
//video.clearFocus();
play.setImageResource(R.drawable.play);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Full.java// for the full screen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullsc);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle bundle = getIntent().getExtras();
path = bundle.getString("path");
pos = bundle.getInt("progress");
Uri uri = Uri.parse(path);
video = (VideoView) findViewById(R.id.fullv);
getActionBar().hide();
/* video.setMediaController(new MediaController(this){
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
((Activity) getContext()).finish();
return super.dispatchKeyEvent(event);
}
});*/
controller = new CMediaController(this);
/* controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
//next button clicked
Toast.makeText(getApplicationContext(), "next", Toast.LENGTH_SHORT).show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
v.requestLayout();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//previous button clicked
Toast.makeText(getApplicationContext(), "prev", Toast.LENGTH_SHORT).show();
}
});*/
video.setMediaController(controller);
video.setVideoURI(uri);
video.seekTo(pos);
video.requestFocus();
video.start();
}
}
fullsc.xml//layout for full screen
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000">
<VideoView
android:layout_gravity="center"
android:id="#+id/fullv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:keepScreenOn="true"
/>
</LinearLayout>
CMediaController.java // for the media controller customization
public class CMediaController extends MediaController {
Context mContext;
//private OnMediaControllerInteractionListener mListener;
public CMediaController(Context context) {
super(context);
// TODO Auto-generated constructor stub
mContext = context;
}
#Override
public void setAnchorView(View view) {
super.setAnchorView(view);
ImageButton full = new ImageButton(mContext);
full.setBackgroundResource(R.id.full);
full.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
//next button clicked
Toast.makeText(mContext, "return to small", Toast.LENGTH_SHORT).show();
((Activity) getContext()).finish();//exiting but stopping the video and setting it to initial state
/*
Intent intent = new Intent(mContext,VideoFragment.class);
//Bundle b2 = new Bundle();
b2.putString("path", uri.toString());
b2.putInt("progress", video.getCurrentPosition());
intent.putExtras(b2);
mContext.startActivity(intent);*/
}}));
/*full = (ImageButton)findViewById(R.id.full);*/
//full.setOnClickListener(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
addView(full, params);
}
/*#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "small", Toast.LENGTH_SHORT).show();
}*/
}
My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} 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();
}
try {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.
This is my main activity which is actually a tab activity. I am choosing list of song and i am trying to play radio in activity given below.
public class MainActivity extends TabActivity {
String[] actions = new String[] { "Tune-Up", "About Us", "Like-Us",
"Other", "Exit" };
Spinner country_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
TabHost tabHost = getTabHost();
TabSpec allcallspec = tabHost.newTabSpec("listner");
allcallspec.setIndicator("listener");
Intent allIntent = new Intent(this, Tab_Listner.class);
allcallspec.setContent(allIntent);
// Tab for recived call
TabSpec recivespec = tabHost.newTabSpec("Like");
// setting Title and Icon for the Tab
recivespec.setIndicator("Like");
Intent reciveIntent = new Intent(MainActivity.this, Tab_Like.class);
recivespec.setContent(reciveIntent);
TabSpec recivespec1 = tabHost.newTabSpec("Categery");
// setting Title and Icon for the Tab
recivespec1.setIndicator("CateGories");
Intent reciveIntent1 = new Intent(MainActivity.this,
Category_name.class);
recivespec1.setContent(reciveIntent1);
tabHost.addTab(recivespec);
tabHost.addTab(allcallspec); // Adding photos tab
// Adding songs tab
tabHost.addTab(recivespec1); // Adding songs tab
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuItem mainMenuSpinner = menu.findItem( R.id.menu_main_spinner);
// setupMainMenuSpinner( mainMenuSpinner );
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
getMenuInflater().inflate(R.menu.mainactivity, menu);
Log.i("Android Version is", "Belove Froyo Action Bar Not Displayed");
MenuItem statusSpinner = menu.findItem(R.id.menu_status_spinner);
setupStatusSpinner(statusSpinner);
}
return super.onCreateOptionsMenu(menu);
}
private void setupStatusSpinner(MenuItem item) {
View view = item.getActionView();
if (view instanceof Spinner) {
Spinner spinner = (Spinner) view;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, actions);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
switch (arg2) {
case 1:
Log.i("About US", "Go");
startActivity(new Intent(MainActivity.this,
About_Us.class));
break;
case 2:
String url = "https://www.facebook.com/musicbreeds";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
case 3:
Log.i("Other", "Go");
startActivity(new Intent(MainActivity.this, Other.class));
break;
case 4:
Log.i("Exit", "unSuccess");
System.out.print("not.......................");
System.exit(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
TextView tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
}
}
Play_Radio activity, In this activity i play and pause songs. i want to have play/pause button at bottom in my MainActivity to stop and play current song.
public class Play_Radio extends Activity {
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
Dialog dialog;
public static String name, rating, like, radio_url, id, listner, image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.play_radio);
if (audioStreamer != null) {
try {
Log.i("Already ply", "Succss");
audioStreamer.stop();
} catch (Exception e) {
}
} else {
Log.i("First time", "Play");
}
initControls();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("On Pause is call", "Succcess");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
Log.i("Android Device above", "Home Enbled");
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
private void initControls() {
iv_like = (ImageView) findViewById(R.id.iv_activity_like);
iv_like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
Toast.makeText(getApplicationContext(),
"Thanks For like Our Station", Toast.LENGTH_LONG)
.show();
}
});
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
playButton = (ImageView) findViewById(R.id.imageView1);
playButton.setEnabled(false);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.i("Click sadg ", "success");
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
if (audioStreamer.getMediaPlayer().isPlaying()) {
Log.i("play ", "success");
audioStreamer.getMediaPlayer().pause();
playButton.setImageResource(R.drawable.play_radio_play);
} else {
Log.i("pause", "success");
audioStreamer.getMediaPlayer().start();
audioStreamer.startPlayProgressUpdater();
playButton.setImageResource(R.drawable.play_radio_pause);
}
isPlaying = !isPlaying;
}
});
// rating radio sation
ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
rankBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rankDialog = new Dialog(Play_Radio.this,
R.style.FullHeightDialog);
rankDialog.setContentView(R.layout.rating_bar);
rankDialog.setCancelable(true);
ratingBar = (RatingBar) rankDialog
.findViewById(R.id.dialog_ratingbar);
float userRankValue = 0;
// ratingBar.setRating(userRankValue);
ratingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
// TODO Auto-generated method stub
cus_rating = rating;
}
});
Button updateButton = (Button) rankDialog
.findViewById(R.id.rank_dialog_button);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Play_Radio.this,
"Thanks For Rating Our Stations",
Toast.LENGTH_LONG).show();
rankDialog.dismiss();
}
});
// now that the dialog is set up, it's time to show it
rankDialog.show();
}
});
String urlstring2 = Tab_Listner.radio_url;
Toast.makeText(Play_Radio.this, "Please Wait...", Toast.LENGTH_LONG)
.show();
startStreamingAudio(urlstring2);
tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}
private void startStreamingAudio(String urlstring) {
try {
dialog = new Dialog(Play_Radio.this,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.progress_layout);
dialog.setTitle("loading...");
dialog.show();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (audioStreamer != null) {
audioStreamer.interrupt();
}
audioStreamer = new StreamingMediaPlayer(this, textStreamed,
playButton, progressBar, dialog);
audioStreamer.startStreaming(urlstring, 5208, 216);
} catch (Exception e) {
Log.e(getClass().getName(), "Error starting to stream audio.", e);
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
}
i have already add play/pause button in playradio activity and its work but i want to play pause button on mainactivity for start and stop play song which are already play run in to radio activity
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte
private TextView textStreamed;
private ImageView playButton;
private Dialog dialog;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context, TextView textStreamed,
ImageView playButton, ProgressBar progressBar, Dialog dialog) {
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
this.dialog = dialog;
}
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
// Dialog dialog=null;
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(),
"Unable to initialize the MediaPlayer for fileUrl="
+ mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(),
"Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),
"downloadingMedia.dat");
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead / 1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// mediaPlayer.release();
}
return false;
} else {
return true;
}
}
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum
// buffered data
if (totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error copying buffered conent.", e);
}
}
} else if (mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000) {
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
moveFile(downloadingMediaFile, bufferedFile);
Log.e(getClass().getName(),
"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),
"Buffered File length: " + bufferedFile.length() + "");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so
// update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
+ ") with extra (" + extra + ")");
return false;
}
});
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after
// transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File.
// Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),
"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on
// exit. If it's already deleted, then this won't mean anything. If
// you want to
// keep and track fully downloaded files for later use, write
// caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile, bufferedFile);
mediaPlayer.pause();
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
boolean atEndOfFile = mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mediaPlayer.start();
}
oldBufferedFile.delete();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + "Kb"));
float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
progressBar.setSecondaryProgress((int) (loadProgress * 100));
if (dialog != null)
dialog.dismiss();
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to
// the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed
.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
progressBar.setProgress((int) (progress * 100));
if (dialog != null)
dialog.dismiss();
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
public void moveFile(File oldLocation, File newLocation) throws IOException {
if (oldLocation.exists()) {
BufferedInputStream reader = new BufferedInputStream(
new FileInputStream(oldLocation));
BufferedOutputStream writer = new BufferedOutputStream(
new FileOutputStream(newLocation, false));
try {
// byte[] buff = new byte[8192];
/* changing the size of the buffer */
byte[] buff = new byte[16384];
int numChars;
while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
writer.write(buff, 0, numChars);
}
} catch (IOException ex) {
throw new IOException("IOException when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
} finally {
try {
if (reader != null) {
writer.close();
reader.close();
}
} catch (IOException ex) {
Log.e(getClass().getName(),
"Error closing files when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
} else {
throw new IOException(
"Old location does not exist when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
public void change_volume(float vol) {
Log.i("Media Player volume change", "Success" + vol);
mediaPlayer.setVolume(vol, vol);
}
public void stop() {
// TODO Auto-generated method stub
mediaPlayer.stop();
}
public void stoppreviousPlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer.release();
}
}
}
you need a Service which is independent to the activity to play the song
public class SongService extends Service {
MediaPlayer mm;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mm = MediaPlayer.create(this, R.raw.mainmenu2);
mm.setLooping(true);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mm.stop();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
mm.start();
}
}
then add this whenever you want to play the song in the service.
startService(new Intent(this, SongService.class));
and to finish it add this:
stopService(new Intent(MainMenu.this,SongService.class));
So when you press the button start the service, and whenever you press the stop button stop it. this is how you can play songs through activities.
First you have to create a raw folder in res folder and paste the song you want to play there.
MainActivity,java======
protected void onCreate(){
MediaPlayer backgroundSong;
backgroundSong = MediaPlayer.create(MainActivity.this, R.raw.your_song_name);
backgroundSong.start();}
#Override
protected void stopSong() {
// TODO Auto-generated method stub
backgroundSong.release();
}
OtherActivity.java
protected void onPause(){
MainActivity ma = new MainActivity();
ma.stopSong();
}
I have an android application with a country map divided into Districts...
and in the database.xml file i put the XY coordinates positions for each District in the map...
But, when I run the application on a device with a different screen size,
the positions change and Didn't fit the positions that I need!
So, Please I Want to know how to detect the screen size, and create a separate XY database for each screen resolution!
Thank you in Advance,
here is the MainActivity.java Code, if you want anything else I will post it,
please I need your help! :(
private final Context appContext = MainActivity.this;
RelativeLayout relativeLayoutMap;
ProgressDialog xyProgressDialog;
Dialog dialog;
Spinner spinner;
MediaPlayer mediaPlayer;
static String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final static String TARGET_BASE_PATH = extStorageDirectory + "/";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayoutMap = (RelativeLayout) findViewById(R.id.mapContainer);
checklanguage();
clickRadioButton();
playMusicOnCoordinatesClick();
new saveFoldertoSDCard().execute("MyApp");
**//Display myDisplay = getWindowManager().getDefaultDisplay();
//Point point = new Point();
//myDisplay.getSize(point);
//int width = point.x;
//int height = point.y;**
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void clickRadioButton() {
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
saveLanguageSelection(true);
}else{
saveLanguageSelection(false);
}
rdbtnEnglish.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
saveLanguageSelection(isChecked);
}
});
}
public void elabirate() {
int coordinates = Coordinates.sCoordinatesList.size();
int i;
for (i = 0; i < coordinates; i++) {
final Button btnclick = new Button(appContext);
btnclick.setId(i);
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
btnclick.setText("" + Coordinates.sCoordinatesList.get(i).getName());
}else{
btnclick.setText("" + Coordinates.sCoordinatesList.get(i).getArabicCityName());
}
btnclick.setBackgroundResource(R.drawable.round_button_selector);
btnclick.setTextColor(Color.CYAN);
LayoutParams lp = new LayoutParams(
android.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.app.ActionBar.LayoutParams.WRAP_CONTENT);
lp.topMargin = Coordinates.sCoordinatesList.get(i).getX();
lp.leftMargin = Coordinates.sCoordinatesList.get(i).getY();
relativeLayoutMap.addView(btnclick, lp);
btnclick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = btnclick.getId();
Intent intent = new Intent();
intent.setClass(appContext, CityActivity.class);
intent.putExtra("btnid", id.toString());
startActivity(intent);
}
});
}
}
public void changeCoordinatesLanguage(View view){
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
int coordinates = Coordinates.sCoordinatesList.size();
int i;
for (i = 0; i < coordinates; i++) {
final Button btnCoordinates = (Button) findViewById(i);
if(rdbtnEnglish.isChecked()){
btnCoordinates.setText("" + Coordinates.sCoordinatesList.get(i).getName());
loadCityList();
}else{
btnCoordinates.setText("" + Coordinates.sCoordinatesList.get(i).getArabicCityName());
loadCityList();
}
}
}
public class GetCoordinates extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
xyProgressDialog = new ProgressDialog(appContext);
xyProgressDialog.setMessage("Loading...");
xyProgressDialog.setCancelable(false);
xyProgressDialog.show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return Coordinates.getCity();
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
try {
xyProgressDialog.dismiss();
if (result) {
elabirate();
loadCityList();
} else {
Toast.makeText(appContext, "Unable to load City list",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO: handle exception
}
super.onPostExecute(result);
}
}
public void loadImage(){
dialog = new Dialog(appContext);
dialog.setContentView(R.layout.progress_dialog);
dialog.setTitle("Load Progress");
dialog.show();
}
public class saveFoldertoSDCard extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new Dialog(appContext);
dialog.setContentView(R.layout.progress_dialog);
dialog.setTitle("My App");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return copyFileOrDir(params[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
try {
//xyProgressDialog.dismiss();
dialog.dismiss();
if (result) {
String path = Environment.getExternalStorageDirectory()
.toString()
+ "/MyApp/MyAppdata.xml";
new GetCoordinates().execute(path);
}
} catch (Exception e) {
// TODO: handle exception
}
super.onPostExecute(result);
}
}
private Boolean copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists())
if (!dir.mkdirs())
;
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
copyFileOrDir(p + assets[i]);
}
}
return true;
} catch (IOException ex) {
return false;
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
in = assetManager.open(filename);
if (filename.endsWith(".png")) // extension was added to avoid
// compression on APK file
newFileName = TARGET_BASE_PATH
+ filename.substring(0, filename.length() - 4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
}
}
public void saveLanguageSelection(boolean value) {
SharedPreferences Shared_preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
SharedPreferences.Editor editor = Shared_preferences.edit();
if (value) {
editor.putString("lang", "english");
} else {
editor.putString("lang", "arabic");
}
editor.commit();
}
public void checklanguage() {
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
RadioButton rdbtnArabic = (RadioButton) findViewById(R.id.rdBtnArabic);
SharedPreferences Shared_preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
String txtlanguage = Shared_preferences.getString("lang", "null");
if (txtlanguage != "null") {
if (txtlanguage.equals("english")) {
rdbtnEnglish.setChecked(true);
rdbtnArabic.setChecked(false);
} else {
rdbtnEnglish.setChecked(false);
rdbtnArabic.setChecked(true);
}
} else {
rdbtnEnglish.setChecked(true);
rdbtnArabic.setChecked(false);
saveLanguageSelection(true);
}
}
public void showWeather(View view) {
String url = "http://m.accuweather.com/";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//parse: to check the availability of the url, ex: 123?
startActivity(browserIntent);
}
public void aboutApp(View view) {
openAboutDialog();
}
#SuppressWarnings("deprecation")
private void openAboutDialog() {
final AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog.setTitle("About");
alertDialog.setMessage("MyApp");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
public void loadCityList(){
Integer type=0;
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
type=0;
}else{
type=1;
}
CityList.getAllCityList(type);
CityListAdapter cityAdapter = new CityListAdapter(appContext, CityList.sCityList);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(cityAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg2 > 0){
TextView txtcityId = (TextView) view.findViewById(R.id.txtCityId);
TextView txtXyId = (TextView) view.findViewById(R.id.txtxyId);
Intent intent = new Intent();
intent.setClass(appContext, CityImagesActivity.class);
intent.putExtra("xyid", txtXyId.getText().toString());
intent.putExtra("cityid", txtcityId.getText().toString());
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void playMusicOnCoordinatesClick() {
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
try {
AssetFileDescriptor afd = getAssets().openFd("Intro.mp3");
mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.setVolume(100, 100);
mediaPlayer.start();
}
public void calledSearch(View view){
Intent intent = new Intent();
intent.setClass(appContext, SearchActivity.class);
startActivity(intent);
}
You can use something like:
Display myDisplay = getWindowManager().getDefaultDisplay();
Point point = new Point();
myDisplay.getSize(point);
int width = point.x;
int height = point.y;
as per this awesome answer.
If your map view is not full screen then I suggest using percentages to set the size of the map. This way you can use a percentage offset with your coordinates to alleviate the varying screen size issue. You definitely don't want to store different sets of XML co-ordinates for different screen resolutions.