I Want to detect Screen Resolution - android

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.

Related

Video stops and goes to initial stage after exiting full screen to normal screen

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();
}*/
}

Fetching Accelerometer Value in Android

I am trying to store accelerometer X, Y, Z value in a Text File but I am getting run time error, after some of seconds similar value start inserting in the file.
Simple GUI
TextArea Showing Text File Values.
Now code is here, Please can some one tell me where I am doing mistake or what change i should do in code?
Thanks
public class MainActivity extends Activity implements SensorEventListener
{
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tvx,tvy,tvz;
EditText etshowval;
RelativeLayout layout;
private String acc;
private String read_str = "";
private final String filepath = "/sdcard/acc.txt";
private BufferedWriter mBufferedWriter;
private BufferedReader mBufferedReader;
private float x;
private float y;
private float z;
public static final int MSG_DONE = 1;
public static final int MSG_ERROR = 2;
public static final int MSG_STOP = 3;
private boolean mrunning;
private Handler mHandler;
private HandlerThread mHandlerThread;
private Handler uiHandler = new Handler(){
public void handleMessage(Message msg){
String str = (String) msg.obj;
switch (msg.what)
{
case MSG_DONE:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
break;
case MSG_ERROR:
Toast.makeText(getBaseContext(),str,
Toast.LENGTH_SHORT).show();
break;
case MSG_STOP:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
default:
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title = (TextView)findViewById(R.id.name);
tvx = (TextView)findViewById(R.id.xval);
tvy = (TextView)findViewById(R.id.yval);
tvz = (TextView)findViewById(R.id.zval);
etshowval = (EditText)findViewById(R.id.showval);
title.setText("Accelerator");
mHandlerThread = new HandlerThread("Working Thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(r);
}
private Runnable r = new Runnable(){
#Override
public void run ()
{
while(true)
{
if (mrunning)
{
Message msg1 = new Message();
try
{
WriteFile(filepath,acc);
msg1.what = MSG_DONE;
msg1.obj = "Start to write to SD 'acc.txt'";
}
catch (Exception e)
{
msg1.what = MSG_ERROR;
msg1.obj = e.getMessage();
}
uiHandler.sendMessage(msg1);
}
else
{
Message msg2 = new Message();
msg2.what = MSG_STOP;
msg2.obj = "Stop to write to SD 'acc.txt'";
uiHandler.sendMessage(msg2);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
public void onStartClick(View view)
{
start();
}
public void onStopClick(View view)
{
stop();
}
public void onReadClick(View view)
{
etshowval.setText(ReadFile(filepath));
}
private synchronized void start()
{
mrunning = true;
}
private synchronized void stop()
{
mrunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
#Override
public void onSensorChanged(SensorEvent sensorEvent)
{
// TODO Auto-generated method stub
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
x = sensorEvent.values[0];
y = sensorEvent.values[1];
z = sensorEvent.values[2];
acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
tvx.setText("X = "+ String.valueOf(x));
tvy.setText("Y = "+ String.valueOf(y));
tvz.setText("Z = "+ String.valueOf(z));
}
}
public void CreateFile(String path)
{
File f = new File(path);
try {
Log.d("ACTIVITY", "Create a File.");
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ReadFile (String filepath)
{
mBufferedReader = null;
String tmp = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedReader = new BufferedReader(new FileReader(filepath));
// Read string
while ((tmp = mBufferedReader.readLine()) != null)
{
tmp += "\n";
read_str += tmp;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return read_str;
}
public void WriteFile(String filepath, String str)
{
mBufferedWriter = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
mBufferedWriter.write(str);
mBufferedWriter.newLine();
mBufferedWriter.flush();
mBufferedWriter.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean FileIsExist(String filepath)
{
File f = new File(filepath);
if (! f.exists())
{
Log.e("ACTIVITY", "File does not exist.");
return false;
}
else
return true;
}
#Override
protected void onPause()
{
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
super.onPause();
}
}

Thread in my code does not work

Here is the code, Results Activity should start if button is clicked:
public class Tab19 extends Activity {
ImageButton button1;
SoundPool mSoundPool;
AssetManager assets;
int catSound;
int countLoadedSound;
Context mContext;
ProgressDialog dialog;
int count = 0;
TextView t;
boolean has_been_clicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab19);
count = getIntent().getIntExtra("CountNum", 0);
mContext = this;
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
catSound = loadSound("catSound.mp3");
button1 = (ImageButton)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
playSound(catSound);
Intent firstIntent = new Intent(Tab19.this, Results.class);
TextView t = (TextView)findViewById(R.id.t);
t.setText("score: " + ++count +"/18");
firstIntent.putExtra("CountNum", count);
has_been_clicked = true;
startActivity(firstIntent);
finish();
}
});
new Thread(
new Runnable() {
public void run() {
while (!has_been_clicked) {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
Intent i=new Intent(getBaseContext(),Results.class);
i.putExtra("CountNum", count);
startActivity(i);
finish();
return;
}
private void sleep(int i) {
// TODO Auto-generated method stub
}
}
).start(); }
#Override
protected void onDestroy() {
super.onDestroy(); }
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Не могу загрузить файл " + fileName,
Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
} }
If button is not clicked Thread should start next Activity within 10 seconds, but it does not happen, please help me find a mistake. Thanks in advance
Into your thread change the while loop into an if statement:
if (!has_been_clicked) {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
I think you should change your code to
boolean has_been_clicked = true;
...
while (has_been_clicked) {
has_been_clicked = false;
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
Intent i=new Intent(getBaseContext(),Results.class);
i.putExtra("CountNum", count);
startActivity(i);
finish();
return;

Implementing audio player in listview in android

I have listview which contains a list of audio files with play button and seekbar. I displayed the listview using base adapter.
When I click a play button of a listview I want to play an audio file. I successfully implemented this but when i click another play button in list two audio files are playing continuously, It will continue for all onclick of play button. How can I restrict the mediaplayer to play in one position and if I click a another icon it have to stop the old media player and start to play the new one. Can anyone say me how do I implement this ?
Hi I am using this code
public class PlayerList extends Activity {
private static final String TAG = "log";
ListView listV;
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();;
String[] strArray = { "/mnt/sdcard/Nal.mp3", "/mnt/sdcard/Nal2.mp3",
"/mnt/sdcard/Nal3.mp3", "/mnt/sdcard/sample1.mp3", };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
listV = (ListView) findViewById(R.id.HomePagelistView1);
for (int i = 0; i < strArray.length; i++) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("title", "File Name");
hmap.put("description", "File description");
hmap.put("url", strArray[i]);
arrList.add(hmap);
}
FileListAdapter sAdapter = new FileListAdapter(arrList, PlayerList.this);
listV.setAdapter(sAdapter);
}
}
And the FileListAdapter file is given below
public class FileListAdapter extends BaseAdapter implements
OnCompletionListener, OnSeekBarChangeListener {
private MediaPlayer mp;
private Handler mHandler = new Handler();;
private Utilities utils;
SeekBar seekBar;// = (SeekBar) findViewById(R.id.homeList_seekBar1);
String songPath = "";
// ImageView imageVPlay;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public FileListAdapter(ArrayList<HashMap<String, String>> data,
Context context) {
this.data = data;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.homelist, parent, false);
final ImageView imageVDownload = (ImageView) vi
.findViewById(R.id.homeListimageDownload); // download
final ImageView imageVPlay = (ImageView) vi
.findViewById(R.id.homeListimagePlay); // play
final TextView textVTitle = (TextView) vi
.findViewById(R.id.homeListTextTitle); // email ID
final TextView textVDescription = (TextView) vi
.findViewById(R.id.homeListTextDesc); // email ID
seekBar = (SeekBar) vi.findViewById(R.id.homeList_seekBar1);
textVTitle.setText(data.get(position).get("title"));
textVDescription.setText(data.get(position).get("description"));
// /////////////////////////////////// set image tick and download
String loadFilePath = data.get(position).get("url");
// String loadFileName = data.get(position).get("title");
File ffPath = new File(loadFilePath);
String loadfileNameWithExt = ffPath.getName();
Log.i(TAG, "load file and name path " + " " + loadfileNameWithExt
+ " " + loadFilePath);
imageVPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String selectFilePath = data.get(position).get("url");
String selectFileName = data.get(position).get("title");
Log.i(TAG, "selected file and name path " + selectFileName
+ " " + selectFilePath);
songPath = selectFilePath;
mediaplayerMethod(selectFilePath);
imageVPlay.setImageResource(R.drawable.list_pause);
textVTitle.setVisibility(View.INVISIBLE);
textVDescription.setVisibility(View.INVISIBLE);
seekBar.setVisibility(View.VISIBLE);
}
});
return vi;
}
protected void mediaplayerMethod(String filepath) {
Log.d(TAG, "mediaplayerMethod audio file path " + filepath);
mp = new MediaPlayer();
mp.setOnCompletionListener(FileListAdapter.this); // Important
seekBar.setOnSeekBarChangeListener(FileListAdapter.this);
utils = new Utilities();
playSong(filepath);
}
private void playSong(final String fileptath) {
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
String xmlString = (String) message.obj;
Log.d(TAG, "handleMessage ");
try {
// mp.prepare();
mp.start();
seekBar.setProgress(0);
seekBar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread() {
#Override
public void run() {
Log.d(TAG, "run ");
try {
mp.reset();
mp.setDataSource(fileptath);
Log.i(TAG, "internal file");
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message message = handler.obtainMessage(1, "");
handler.sendMessage(message);
}
};
thread.start();
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int) (utils.getProgressPercentage(
currentDuration, totalDuration));
seekBar.setProgress(progress);
try {
double progVal = (progress / 100.0) * (360.0);
int progInt = (int) Math.ceil(progVal);
} catch (NumberFormatException e) {
Log.e(TAG, "NumberFormatException " + e);
}
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException " + e);
}
}
};
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
updateProgressBar();
}
}// FileListAdapter
Release your old MediaPlayer when You going to start a new instance. For example:
protected void mediaplayerMethod(String filepath) {
Log.d(TAG, "mediaplayerMethod audio file path " + filepath);
if(mp != null){
mp.release();
}
mp = null;
mp = new MediaPlayer();
mp.setOnCompletionListener(FileListAdapter.this); // Important
seekBar.setOnSeekBarChangeListener(FileListAdapter.this);
utils = new Utilities();
playSong(filepath);
}

I have 2 activities. I need to play one background music to all the activities.I want play and stop song from main activity

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();
}

Categories

Resources