Is it possible to add text from java coding of a list view to marquee scroll in Android. If yes can you please let me know how?
If needed I shall post the code used.
This was the XML for listview used is as follows
<?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="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
<ListView
android:id="#+id/audiolist_listView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:layout_weight="1"
android:background="#drawable/backgroundimg"
android:divider="#drawable/gradient"
android:dividerHeight="1dp"
android:scrollbars="vertical" >
</ListView>
</LinearLayout>
The java class for listview is as follows
public class Audiovediolist extends Activity implements OnItemClickListener {
private ListView audioList;
private Intent frmHome;
private ArrayList<HashMap<String, String>> dataList;
private HashMap<String, String> map;
private HashMap<String, String> data;
private int Screen_Id;
private AdView adView;
String name;
String mSign[] = { "Aries-Mesam", "Taurus-Vrushabham", "Gemini-Midhunam",
"Cancer-Karkatakam", "Leo-Simham", "Virgo-Kanya", "Libra-Tula",
"Scorpio-Vruchikam", "Sagittarius-Dhanussu", "Capricorn-Makaram",
"Aquarius-Kumbham", "Pisces-Meenam" };
Integer mImages[] = { R.drawable.meshamu, R.drawable.vrushabhamu,
R.drawable.medhunam, R.drawable.karkatakam, R.drawable.simham,
R.drawable.kanya, R.drawable.tula, R.drawable.vruchikam,
R.drawable.dhanussu, R.drawable.makaramu, R.drawable.kumbhamu,
R.drawable.meenamu };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.list);
frmHome = getIntent();
getIntentValues();
initUI();
setUI();
uiListener();
}
private void initUI() {
audioList = (ListView) findViewById(R.id.audiolist_listView);
dataList = new ArrayList<HashMap<String, String>>();
adView = new AdView(this, AdSize.SMART_BANNER, "a150b89c23af3b2");
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
layout.setGravity(Gravity.TOP);
layout.addView(adView);
adView.loadAd(new AdRequest());
}
private void uiListener() {
audioList.setOnItemClickListener(this);
}
private void getIntentValues() {
String id = frmHome.getStringExtra("Activity_Id");
Screen_Id = Integer.parseInt(id);
if (Screen_Id == 1) {
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.audioo);
this.setTitle(getResources().getString(R.string.audio));
this.setTitleColor(getResources().getColor(R.color.Beige));
} else {
this.setTitle(getResources().getString(R.string.video));
this.setTitleColor(getResources().getColor(R.color.Beige));
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.videoo);
}
}
private void setAdapter() {
SimpleAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_row, new String[] { "Image", "text" }, new int[] {
R.id.audiolist_row_img, R.id.audiolist_row_tv });
audioList.setAdapter(adapter);
}
private void setUI() {
for (int a = 0; a <= 11; a++) {
map = new HashMap<String, String>();
map.put("Image", "" + mImages[a]);
map.put("text", mSign[a]);
dataList.add(map);
map = null;
}
}
#Override
protected void onStart() {
super.onStart();
setAdapter();
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
/*
* private class NextTask extends AsyncTask<Void,Void,Void> { ProgressDialog
* progressDailog = new ProgressDialog(Audiovediolist.this);
*
* #Override protected void onPreExecute() { super.onPreExecute();
* progressDailog.setTitle("Please Wait");
* progressDailog.setMessage("URL Data Loading ...");
* progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
* progressDailog.setCancelable(true); progressDailog.show(); }
*
* #SuppressWarnings("static-access")
*
* #Override protected Void doInBackground(Void... params) { return null; }
*
* #Override protected void onPostExecute(Void result) {
* progressDailog.dismiss(); } }
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
data = dataList.get(position);
//FinalConstants.AUDIO_VIDEO = "list";
try {
NetWorkCheck netWork = new NetWorkCheck();
if (netWork.isNetWorkConnection(this)) {
if (Screen_Id == 1) {
// new NextTask().execute();
Intent audioInt=new Intent(getApplicationContext(),AudioView.class);
audioInt.setType(data.get("text"));
startActivity(audioInt);
} else if (Screen_Id == 2) {
Intent vedioInt = new Intent(this, VideoPlayActivity.class);
vedioInt.setType(data.get("text"));
startActivity(vedioInt);
}
} else {
netWork.alert();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Problem while ListItemClick",
Toast.LENGTH_SHORT).show();
}
}
}
The code for audio player where i need the text selected to scroll is as follows
public class AudioView extends Activity implements OnClickListener {
private MediaPlayer mMediaPlayer;
private ImageView mPlay;
private ImageView mPause;
private ImageView mBack;
private ImageView mFar;
private ProgressBar myProgressBar;
private boolean boolFlag = false;
private boolean isPausedInCall = false;
private String url;
private TelephonyManager mTelephoneMgr;
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
private TextView tv;
// private boolean serviceRunning;
Notification notifyDetails;
private AdView adView;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.marquee);
Toast.makeText(this,"please wait.........",Toast.LENGTH_LONG).show();
url=getIntent().getType();
initUI();
uiListener();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notifyDetails = new Notification(R.drawable.mulug_icon, url,
System.currentTimeMillis());
mTelephoneMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mTelephoneMgr != null) {
mTelephoneMgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/*if(FinalConstants.AUDIO_VIDEO=="listitem"){
LoginProgress task = new LoginProgress();
task.applicationContext = AudioView.this;
task.execute();
}*/
}
private void initUI() {
tv = (TextView) findViewById(R.id.text);
mBack = (ImageView) findViewById(R.id.back);
mPlay = (ImageView) findViewById(R.id.play);
mPause = (ImageView) findViewById(R.id.pause);
mFar = (ImageView) findViewById(R.id.fwd);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
myProgressBar.setProgressDrawable(getResources().getDrawable(
R.drawable.green_progress));
myProgressBar.setProgress(0);
adView = new AdView(this, AdSize.BANNER, "a150b89c23af3b2");
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
layout.setGravity(Gravity.TOP);
layout.addView(adView);
adView.loadAd(new AdRequest());
tv.setText(url + "more Deails Click on www.mulugu.com");
tv.setSelected(true);
}
private void uiListener() {
mPlay.setOnClickListener(this);
mPlay.setOnClickListener(this);
mPause.setOnClickListener(this);
mPause.setVisibility(android.view.View.INVISIBLE);
mBack.setOnClickListener(this);
mFar.setOnClickListener(this);
}
private Thread myThread = new Thread() {
public void run() {
while (mMediaPlayer.getCurrentPosition() < mMediaPlayer
.getDuration()) {
try {
myProgressBar
.setProgress(mMediaPlayer.getCurrentPosition());
} catch (Throwable t) {
}
}
}
};
#Override
protected void onStart() {
super.onStart();
this.setProgressBarIndeterminateVisibility(true);
try {
if (boolFlag == false) {
System.out.println(FinalConstants.URL + "mobile-audio/" + url+ ".mp3");
mMediaPlayer = MediaPlayer.create(
this,
Uri.parse(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3"));
}
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Data not available",
Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "Data Not Exist in that Url...");
super.onBackPressed();
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#Override
public void onBackPressed() {
super.onBackPressed();
mMediaPlayer.stop();
// myThread.stop();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
System.gc();
}
#Override
protected void onDestroy() {
adView.destroy();
super.onDestroy();
System.gc();
}
public PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
System.out.println("ringing state");
if (mMediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
notificationShow();
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
System.out.println("callState Idle");
if (mMediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
private void pauseMedia() {
mMediaPlayer.pause();
changePlayerIcons(false);
}
private void playMedia() {
mMediaPlayer.start();
changePlayerIcons(true);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!boolFlag) {
try {
notificationShow();
mMediaPlayer.setLooping(false);
mMediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "preparing", Toast.LENGTH_SHORT)
.show();
}
boolFlag = true;
mMediaPlayer.start();
myThread.start();
} else {
notificationShow();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.start();
}
changePlayerIcons(true);
myProgressBar.setProgress(mMediaPlayer.getCurrentPosition());
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
changePlayerIcons(false);
myProgressBar.setProgress(0);
onStart();
}
});
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
break;
case R.id.pause:
mMediaPlayer.pause();
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
break;
case R.id.back:
int dur = mMediaPlayer.getCurrentPosition();
int pos = (dur > 10000 ? dur - 5000 : 0);
mMediaPlayer.seekTo(pos);
break;
case R.id.fwd:
int curpos = mMediaPlayer.getCurrentPosition();
int dur2 = mMediaPlayer.getDuration();
int pos2 = (curpos + 5000 > dur2 ? dur2 : curpos + 5000);
mMediaPlayer.seekTo(pos2);
break;
}
}
#SuppressWarnings("deprecation")
private void notificationShow() {
Context context = getApplicationContext();
CharSequence contentTitle = "Mulugu Running";
CharSequence contentText = url + " Weekly Predictions";
Intent notifyIntent = new Intent(AudioView.this, AudioView.class);
PendingIntent intent = PendingIntent.getActivity(AudioView.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText,
intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
private void changePlayerIcons(boolean b) {
if (b) {
mPlay.setVisibility(android.view.View.INVISIBLE);
mPause.setVisibility(android.view.View.VISIBLE);
} else {
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
}
}
/*public class LoginProgress extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.dialog.dismiss();
}
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Data Loading",
"Loading .....", true);
}
#Override
protected Void doInBackground(Void... params) {
LoadUrl();
return null;
}
private void LoadUrl() {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.reset();
try {
mMediaPlayer.setDataSource(AudioView.this,Uri.parse(FinalConstants.URL + "mobile-audio/" + getIntent().getType()+ ".mp3"));
mMediaPlayer.setLooping(false); // Set looping
mMediaPlayer.prepare();
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
e.printStackTrace();
}
}
}*/
}
If you need to move text around, maybe this will help:
http://developer.android.com/guide/topics/resources/animation-resource.html#translate-element
If you have a TextView with a text that is too big and you want it to move around so people can read the whole thing, try android:ellipsize="marquee" in the .xml file, or in the Java code:
textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
If the android libraries not enough, you can always use the java via coding. Create a thread class that gets the views and change conditions over time. You can create an intent to call that class.
You can use the TextSwitcher and apply the animation on it.
Try below code:
public class TextSwitcherActivity extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener
{
private TextSwitcher m_switcher;
private Button m_nextButton;
private int m_counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_switcher = (TextSwitcher) findViewById(R.id.tsSwitcher);
m_switcher.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
m_switcher.setInAnimation(in);
m_switcher.setOutAnimation(out);
m_nextButton = (Button) findViewById(R.id.next);
m_nextButton.setOnClickListener(this);
updateCounter();
}
/**
* Update counter value
*/
public void onClick(View v)
{
m_counter++;
updateCounter();
}
/**
* Set text on textswitcher
*/
private void updateCounter()
{
m_switcher.setText(String.valueOf(m_counter));
}
public View makeView()
{
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
You can define your own animations to get the marquee effect.
Here is the example
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/mywidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textColor="#ff4500"
android:text="Simple application that shows how to use marquee, with a long text" />
In java (If you are using a Listview and binding an adapter, then in getview when u inflate Layout and its view component, set the selected flag to true to your TextView.)
tv = (TextView) this.findViewById(R.id.tv);
tv.setSelected(true);
By using below method you can convert your list of string values into a single string,
String listString = String.join(", ", list);
This will convert list values into string and with that you can achieve this. I know this is very late but I posted because there is no solution provided that's why.
Related
I have created android application to stream online radio stations but when I click start button to play radio it won't start.In service I read ip address of file from url and add it to string.When user selects radio station I add port to string with ip address.Problem starts in mediaPlayer.setOnPreparedListener !!!
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL;
final String textSource = "http://audiophileradio.stream/Ip.txt";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new MyTask().execute();
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
#Override
public boolean onUnbind(Intent intent)
{
return super.onUnbind(intent);
}
private class MyTask extends AsyncTask<Void, Void, String>
{
String textResult;
#Override
protected String doInBackground(Void... params) {
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader
= new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textResult = stringText;
return textResult;
} catch (MalformedURLException e) {
e.printStackTrace();
textResult = e.toString();
} catch (IOException e) {
e.printStackTrace();
textResult = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("DebugTag", "Value: " + textResult);
super.onPostExecute(result);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
String radio = sharedPreferences.getString("station", "8000");
if (radio != null)
{
STREAM_URL += ":" + radio;
}
mediaPlayer = new MediaPlayer();
if (!mediaPlayer.isPlaying())
{
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
mediaPlayer.setOnCompletionListener(BackgroundService.this);
}
}
}
public class Main extends Fragment
{
private ImageButton buttonPlay;
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_main,container,false);
buttonPlay = (ImageButton) view.findViewById(R.id.buttonPlay);
mPlayer = new MediaPlayer();
initControls();
buttonPlay.setTag(1);
buttonPlay.setImageResource(R.drawable.play);
buttonPlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (Integer.parseInt(buttonPlay.getTag().toString()) == 1)
{
buttonPlay.setImageResource(R.drawable.stop);
view.setTag(0);
getActivity().startService(playbackServiceIntent);
Log.e("Play", "onStop");
Toast.makeText(getActivity(), "Play", Toast.LENGTH_SHORT).show();
} else
{
buttonPlay.setImageResource(R.drawable.play);
view.setTag(1);
mPlayer.stop();
getActivity().stopService(playbackServiceIntent);
Log.e("Stop", "onPlay");
Toast.makeText(getActivity(), "Stop", Toast.LENGTH_SHORT).show();
}
}
});
playbackServiceIntent = new Intent(getActivity(), BackgroundService.class);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Audiophileradio");
}
private void startService()
{
getActivity().startService(new Intent(getActivity(),BackgroundService.class));
}
private void stopService()
{
getActivity().stopService(new Intent(getActivity(),BackgroundService.class));
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar) view.findViewById(R.id.seekBar);
audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
//volumeSeekbar.setMax(100);
volumeSeekbar.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);
//volume.setText("Volume : " + progress + "%");
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
prepareAsynch should be called after setOnPreparedListener, otherwise it may happen that prepareAsynch finished working before the listener is assigned.
I have fixed the problem! Radio didn't work because I forgot to add http:// in ip address after reading it from url !!!
I am making a music player application in android. The application has
MainActivity.java (with corresponding XML File:activity_main): This Activity has a listview that displays the list of all songs available.
PlayerScreen.java (with corresponding XML File:activity_player_screen): When a song is clicked on the first activity, this activity is launched and it plays that particular song. This activity has 3 Buttons (Play/Pause, NextSong, PreviousSong) and a seekbar.
Now this is where I am facing the problem
I have created a separate class (SeekBarThread.java) for implementing seekbar of the activity_player_screen using Threading.
The Problem is that when I call the start method for my thread class from PlayerScreen.java, nothing happens. No exception is thrown. The song keeps on playing but the widgets of the activity_player_screen stop working i.e. I can't pause the song aur play the next song. The seekbar also doesn't work.
I think I am not able to link the activity_player_screen file with both PlayerScreen.java and SeekBarThread.java properly.
This is the call to the Thread class from PlayerScreen.java
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
I don't really have an idea to get rid of the anomaly so I passed the seekbar object and mediaplayer object reference and the current context reference to the SeekBarThread class. But it didn't work.
Here is the SeekBarThread.java class code:
public class SeekBarThread implements Runnable{
private PlayerScreen myPlayerScreen;
private SeekBar seekBar;
private MediaPlayer mp;
private Context context;
public SeekBarThread(Context context, SeekBar seekBar, MediaPlayer mp) {
this.context = context;
this.seekBar = seekBar;
this.mp = mp;
}
public void run() {
((Activity)context).setContentView(R.layout.activity_player_screen);
seekBar.setMax(mp.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
int totalduration = mp.getDuration();
int currentposition = 0;
while(currentposition < totalduration) {
try {
sleep(500);
currentposition = mp.getCurrentPosition();
seekBar.setProgress(currentposition);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
activity_player_screen XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_player_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="prakhar.simplemusicplayer20.PlayerScreen">
<Button
android:id="#+id/play_pause"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:background="#drawable/pause" />
<Button
android:id="#+id/next_song"
android:layout_height="42dp"
android:layout_width="42dp"
android:background="#drawable/next"
android:layout_marginEnd="25dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/prev_song"
android:layout_height="42dp"
android:layout_width="42dp"
android:background="#drawable/previous"
android:layout_marginStart="25dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<Button
android:text="F"
android:layout_width="42dp"
android:layout_height="42dp"
android:id="#+id/forward_song"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/next_song"
android:layout_marginEnd="22dp" />
<Button
android:text="R"
android:layout_width="42dp"
android:layout_height="42dp"
android:id="#+id/rewind_song"
android:layout_marginEnd="23dp"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/play_pause" />
<SeekBar
android:id="#+id/seek_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="26dp"
android:layout_above="#+id/play_pause"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="146dp"
android:id="#+id/details_text_view" />
</RelativeLayout>
Here is the PlayerScreen.java class:
public class PlayerScreen extends AppCompatActivity implements View.OnClickListener{
private Button playPause, nextSong, prevSong;
public SeekBar mySeekBar;
private int count = 0;
public MediaPlayer mediaPlayer;
private Bundle newBundle = new Bundle();
private Intent newIntent;
private int pos;
private ArrayList<String> name;
private ArrayList<String> path;
private SeekBarThread mySeekBarThread;
private Thread myThread;
private TextView detailsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_screen);
playPause = (Button)findViewById(R.id.play_pause);
nextSong = (Button)findViewById(R.id.next_song);
prevSong = (Button)findViewById(R.id.prev_song);
mySeekBar = (SeekBar)findViewById(R.id.seek_bar);
detailsTextView = (TextView)findViewById(R.id.details_text_view);
playPause.setOnClickListener(this);
nextSong.setOnClickListener(this);
prevSong.setOnClickListener(this);
newIntent = this.getIntent();
newBundle = newIntent.getExtras();
name = newBundle.getStringArrayList("title");
path = newBundle.getStringArrayList("songpath");
pos = newBundle.getInt("post");
detailsTextView.setText(name.get(pos));
mediaPlayer = new MediaPlayer();
setMediaPlayer(pos);
}
public void setMediaPlayer(int position) {
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
File mySong = new File(path.get(pos));
mediaPlayer = new MediaPlayer();
FileInputStream is = null;
try {
is = new FileInputStream(mySong);
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setDataSource(is.getFD());
}
catch(IOException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.prepare();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
if(is != null) {
try {
is.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
mediaPlayer.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.play_pause:
count++;
if(count%2 == 0) {
v.setBackgroundResource(R.drawable.pause);
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
else {
v.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
break;
case R.id.next_song:
mediaPlayer.stop();
pos = pos + 1;
setMediaPlayer(pos);
break;
case R.id.prev_song:
mediaPlayer.stop();
pos = pos - 1;
setMediaPlayer(pos);
break;
}
}
}
Most of the onCreate() code for this is class is dealing with which song to play based on the user's choice from the previous activity. And since the song is being played, i don't think there is a problem in that part of the code.
#prakhar, Going through the code, I have found the following issues:
1) In SeekBarThread class in run() method setContentView() should not set,as it is already set in the activity class, as your are not reinitializing the click listeners.
2) Also the seekbarchangeListener should not be set in run() method and should be set in the main activity itself, as it doesn't need reinitalizing all the time.
3) The important point here is that your are initializing the SeekBarThread class before the initialization of MediaPlayer and hence there is no action even after seeking the seekbar.
A detailed code with the above modifications rectified.
public class PlayerScreen extends AppCompatActivity implements View.OnClickListener {
private Button playPause, nextSong, prevSong;
public SeekBar mySeekBar;
private int count = 0;
public MediaPlayer mediaPlayer;
private Bundle newBundle = new Bundle();
private Intent newIntent;
private int pos;
private ArrayList<String> name;
private ArrayList<String> path;
private SeekBarThread mySeekBarThread;
private Thread myThread;
private TextView detailsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playPause = (Button) findViewById(R.id.play_pause);
nextSong = (Button) findViewById(R.id.next_song);
prevSong = (Button) findViewById(R.id.prev_song);
mySeekBar = (SeekBar) findViewById(R.id.seek_bar);
detailsTextView = (TextView) findViewById(R.id.details_text_view);
playPause.setOnClickListener(this);
nextSong.setOnClickListener(this);
prevSong.setOnClickListener(this);
mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
newIntent = this.getIntent();
newBundle = newIntent.getExtras();
name = newBundle.getStringArrayList("title");
pos = newBundle.getInt("post");
detailsTextView.setText(name.get(pos));
mediaPlayer = new MediaPlayer();
setMediaPlayer(pos);
}
public void setMediaPlayer(int position) {
File mySong = new File(path.get(pos));
mediaPlayer = new MediaPlayer();
FileInputStream is = null;
try {
is = new FileInputStream(mySong);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setDataSource(is.getFD());
} catch (IOException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
mediaPlayer.start();
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_pause:
count++;
if (count % 2 == 0) {
v.setBackgroundResource(R.drawable.pause);
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
} else {
v.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
break;
case R.id.next_song:
mediaPlayer.stop();
pos = pos + 1;
setMediaPlayer(pos);
break;
case R.id.prev_song:
mediaPlayer.stop();
pos = pos - 1;
setMediaPlayer(pos);
break;
}
}
}
public class SeekBarThread implements Runnable{
private SeekBar seekBar;
private MediaPlayer mp;
private Context context;
public SeekBarThread(Context context, SeekBar seekBar, MediaPlayer mp) {
this.context = context;
this.seekBar = seekBar;
this.mp = mp;
}
public void run() {
seekBar.setMax(mp.getDuration());
int totalduration = mp.getDuration();
int currentposition = 0;
while(currentposition < totalduration) {
try {
sleep(500);
currentposition = mp.getCurrentPosition();
seekBar.setProgress(currentposition);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
In my android application while I'm playing a music, the seekbar bar is staying still. The timer of the music is running fine & the music plays from the touched position of the seek bar.
But the problem is that the seekbar is still and not moving while touching on the seekbar .
Any one help me to find a solution for this .. Thank You ..
My Activity code is ....
public class Device_AudioPlayerActivity extends Activity implements Runnable,
OnClickListener, SeekBar.OnSeekBarChangeListener {
Button btnBack;
static Button btnPause;
private Handler mHandler;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
SeekBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().hide();
setContentView(R.layout.device_audio_player);
context = this;
progressBar=(SeekBar)findViewById(R.id.progressBar);
init();
progressBar.setMax(Device_SongService.mp.getDuration());
new Thread().start();
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(true);
//-=--------------------------------------
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
Device_PlayerConstants.PROGRESSBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(Device_UtilFunctions.getDuration(i[0]));
textDuration.setText(Device_UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI() {
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (SeekBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = Device_UtilFunctions.isServiceRunning(Device_SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if (Device_PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try {
String songName = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getTitle();
String artist = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getArtist();
String album = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbum();
String composer = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if (composer != null && composer.length() > 0) {
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
} else {
textComposer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
long albumId = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = Device_UtilFunctions.getAlbumart(context, albumId);
if (albumArt != null) {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(Device_UtilFunctions.getDefaultAlbumArt(context)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
try {
if (Device_SongService.mp.isPlaying() || Device_SongService.mp != null) {
if (b)
Device_SongService.mp.seekTo(i);
} else if (Device_SongService.mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = Device_SongService.mp.getCurrentPosition();
int total = Device_SongService.mp.getDuration();
while (Device_SongService.mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = Device_SongService.mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
}
Have a look at this link.
Try using a thread in progress changed.
you have to use thread on onprogresschnaged....
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2) {
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
//here write your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
I need help, there are osvnonoe Activiti in which history is loaded tracks, when you click on the track opens an alert dialog with loading the page, then the link is redirected, and the output is a link with the track, which I send to the media player in the service, but I get a NullPointerException
Example link
http://s.spynetstation.com/m/8/Loud%20Sound/TAMFREE026/unknown-Blitzkrieg-320kbps.mp3
Error
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:783)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:761)
at com.spynetstation.MediaService.initT(MediaService.java:132)
at com.spynetstation.MainActivity$14.shouldOverrideUrlLoading(MainActivity.java:716)
at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:224)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:324)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Code Activity
public class MainActivity extends FragmentActivity {
MediaPlayer mediaPlayer;
static AudioManager am;
static CheckBox pdaStream;
Button btnNews;
static TitleAdapter titleAdapter;
static ViewPager mViewPager;
RelativeLayout RelativeLayout1;
static String selectStream;
public String stream_sel;
public static String colors_sel;
public int stream;
public static int colors;
public boolean checker;
public static boolean track;
public boolean searchtrack;
public boolean searchtrackhistory;
static SharedPreferences mSettings;
static TextView titleMusic;
static boolean replay = false;
public MusicIntentReceiver myReceiver;
//History
public LinearLayout history;
public Button btn_up;
public boolean history_view = false;
public static TextView history1;
public static TextView history2;
public static TextView history3;
public static TextView history4;
public static TextView history5;
boolean loadingFinished = true;
boolean redirect = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Create();
}
public void Create(){
setContentView(R.layout.activity_main);
//Settings
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
//Language settings
lang = mSettings.getString("lang", "default");
if (lang.equals("default")) {lang=getResources().getConfiguration().locale.getCountry();}
locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
Log.i("Lang change", "Locale="+locale);
getBaseContext().getResources().updateConfiguration(config, null);
//End Language
mViewPager = (ViewPager) findViewById(R.id.pager);
RelativeLayout1 = (RelativeLayout) findViewById(R.id.RelativeLayout1);
pdaStream = (CheckBox) findViewById(R.id.pdaStream);
pdaStream.setText(R.string.chkbox);
checker = mSettings.getBoolean("checker", false);
Log.i("Resume: checker=",""+checker);
track = mSettings.getBoolean("track", false);
Log.i("Resume: track=",""+track);
searchtrack = mSettings.getBoolean("searchtrack", false);
Log.i("Resume: searchtrack=",""+searchtrack);
searchtrackhistory = mSettings.getBoolean("searchtrackhistory", false);
Log.i("Resume: searchtrackhistory=",""+searchtrackhistory);
stream_sel = mSettings.getString("stream", "1");
Log.i("Resume: stream_sel=",""+stream_sel);
if (stream_sel.equals("0")) {
stream = 0;}
else if (stream_sel.equals("1")) {
stream = 1;}
else if (stream_sel.equals("2")) {
stream = 2;}
else stream = 1;
Log.i("Default Stream=", " "+stream);
//---
Log.i("MainActivity","onCreate");
titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(stream);
mViewPager.setOffscreenPageLimit(3);
stream_buf = stream;
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
SeekBar music = (SeekBar)findViewById(R.id.seekBar1);
initBar(music, AudioManager.STREAM_MUSIC);
if (Free) {pdaStream.setChecked(true);}
else {pdaStream.setChecked(checker);}
titleMusic = (TextView) findViewById(R.id.titleMusic);
titleMusic.setSelected(true);
titleMusic.setVisibility(View.VISIBLE);
CallReceiver.state = true;
StartHistory();
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
myReceiver = new MusicIntentReceiver();
registerReceiver(myReceiver, filter);
SearchTrack();
startService(new Intent(this, MediaService.class));
}
public void StartHistory() {
history1 = (TextView) findViewById(R.id.history1);
history1.setSelected(true);
history2 = (TextView) findViewById(R.id.history2);
history2.setSelected(true);
history3 = (TextView) findViewById(R.id.history3);
history3.setSelected(true);
history4 = (TextView) findViewById(R.id.history4);
history4.setSelected(true);
history5 = (TextView) findViewById(R.id.history5);
history5.setSelected(true);
history = (LinearLayout) findViewById(R.id.history);
history.setVisibility(View.INVISIBLE);
btn_up = (Button) findViewById(R.id.btn_up);
btn_up.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (history_view){
Log.i("StartHistory","History close");
btn_up.setBackgroundResource(R.drawable.up);
history.setVisibility(View.INVISIBLE);
history_view=false;
MediaService.only_his=false;
if (MediaService.mediaPlayer==null){
titleMusic.setText(" ");
}
} else {
Log.i("StartHistory","History open");
btn_up.setBackgroundResource(R.drawable.up2);
history.setVisibility(View.VISIBLE);
history_view=true;
if (MediaService.mediaPlayer==null){
MediaService.only_his=true;
if (stream_buf==0){
MediaService.InputHistory("http://liquid.spynetstation.com:8000/meta.txt");
MediaService.SearchInHistory("http://liquid.spynetstation.com:8000/linkable_current_track.txt");
}
if (stream_buf==1){
MediaService.InputHistory("http://main.spynetstation.com:8000/meta.txt");
MediaService.SearchInHistory("http://main.spynetstation.com:8000/linkable_current_track.txt");
}
if (stream_buf==2){
MediaService.InputHistory("http://dub.spynetstation.com:8000/meta.txt");
MediaService.SearchInHistory("http://dub.spynetstation.com:8000/linkable_current_track.txt");
}
}else {MediaService.only_his=false;}
}
}
});
}
public void SearchTrack(){
final String searchurl = "https://www.google.ru/search?q=";
titleMusic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrack){} else {
if (MediaService.currentlyPlaying != null){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(searchurl + MediaService.currentlyPlaying)));
}
}
}
});
history1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[1] != null){
ShowTrack(MediaService.searchhis[0],MediaService.his[1]);
}
}
}
});
history2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[2] != null){
ShowTrack(MediaService.searchhis[1],MediaService.his[2]);
}
}
}
});
history3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[3] != null){
ShowTrack(MediaService.searchhis[2],MediaService.his[3]);
}
}
}
});
history4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[4] != null){
ShowTrack(MediaService.searchhis[3],MediaService.his[4]);
}
}
}
});
history5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[5] != null){
ShowTrack(MediaService.searchhis[4],MediaService.his[5]);
}
}
}
});
}
public void ShowTrack(final String smetaout,String stitleout){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(stitleout);
final WebView wv = new WebView(this);
Log.d("My Webview", "ShowTrack");
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(smetaout);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(url);
Log.d("shouldOverrideUrlLoading", url);
Uri myUri = Uri.parse(url);
MediaService.initT(myUri);
MediaService.startT();
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
} else{
redirect = false;
}
}
});
alert.setView(wv);
alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alert.show();
}
}
Code Service
public class MediaService extends Service implements OnPreparedListener,OnCompletionListener{
static boolean isPlayingMain = false;
static boolean isPlayingLiquid = false;
static boolean isPlayingDubstep = false;
static MediaPlayer mediaPlayer;
static NotificationManager nm;
private static NotificationCompat.Builder mBuilder;
private static Notification.Builder mNBuilder;
public static Context ctx;
public IBinder onBind(Intent paramIntent) {
return null;
}
public static void initT(Uri urlTrack){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d("initT",""+urlTrack);
mediaPlayer.setDataSource(ctx,urlTrack);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
Log.i("MediaService", "prepare");
}
public static void startT(){
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
Log.i("MediaService", "start");
}
});
}
public static void releaseMP() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
Log.i("MediaService", "release");
mediaPlayer = null;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.i("MediaService", "onCompletion");
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.i("MediaService", "onPrepareed");
}
public void onCreate() {
super.onCreate();
ctx = getApplicationContext();
//notif(titleNotif, contentNotif);
//this.nm = ((NotificationManager)getSystemService("notification"));
}
public void onDestroy() {
//this.nm.cancelAll();
stopForeground(true);
if(CallReceiver.telManager != null) {
CallReceiver.telManager.listen(CallReceiver.phoneListener, PhoneStateListener.LISTEN_NONE);
Log.i("CallReceiver", "Destroy");
}
}
public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) {
try {
TimeUnit.SECONDS.sleep(0);
notif(getResources().getString(R.string.title_notif),getResources().getString(R.string.title_notif));
return super.onStartCommand(paramIntent, paramInt1, paramInt2);
}
catch (InterruptedException localInterruptedException) {
for (;;) {
localInterruptedException.printStackTrace();
}
}
}
public void notif(String titleNotif, String contentNotif){
//building the notification
mBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.spy)
.setContentTitle(titleNotif)
.setTicker(contentNotif)
.setOngoing(true)
//.addAction(R.drawable.media_play, "Play", notificationIntent)
;
Intent notificationIntent = new Intent(ctx, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
//Notification n = mBuilder.build();
//nm.notify(1, n);
startForeground(1, mBuilder.build());
}
}
Thank you all for your answers! Decided as follows:
In the service has changed as follows:
public static void initT(Context context,Uri urlTrack){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d("initT",""+urlTrack);
mediaPlayer.setDataSource(context,urlTrack);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}catch (IllegalArgumentException e) {
e.printStackTrace();
}
Log.i("MediaService", "prepare");
}
In Activity changed as follows:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(url);
Log.d("shouldOverrideUrlLoading", url);
Uri myUri = Uri.parse(url);
context = getApplicationContext();
MediaService.releaseMP();
MediaService.initT(context, myUri);
MediaService.startT();
return true;
}
How to set TextView Text as dynamically for scrolling marquee.
Please Help me Thanks Advance.
The Listview used for getting the list item to be played in the audio player is as follows.
public class Audiovediolist extends Activity implements OnItemClickListener {
private ListView audioList;
private Intent frmHome;
private ArrayList<HashMap<String, String>> dataList;
private HashMap<String, String> map;
private HashMap<String, String> data;
private int Screen_Id;
String name;
String mSign[] ={"1","2","3","4","5"};
Integer mImages[] = { R.drawable.m, R.drawable.v,
R.drawable.mm, R.drawable.k, R.drawable.s};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.list);
frmHome = getIntent();
getIntentValues();
initUI();
setUI();
uiListener();
}
private void initUI() {
audioList = (ListView) findViewById(R.id.audiolist_listView);
dataList = new ArrayList<HashMap<String, String>>();
}
private void uiListener() {
audioList.setOnItemClickListener(this);
}
private void getIntentValues() {
String id = frmHome.getStringExtra("Activity_Id");
Screen_Id = Integer.parseInt(id);
if (Screen_Id == 1) {
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.audioo);
this.setTitle(getResources().getString(R.string.audio));
this.setTitleColor(getResources().getColor(R.color.Beige));
} else {
this.setTitle(getResources().getString(R.string.video));
this.setTitleColor(getResources().getColor(R.color.Beige));
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.videoo);
}
}
private void setAdapter() {
SimpleAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_row, new String[] { "Image", "text" },
new int[] {
R.id.audiolist_row_img, R.id.audiolist_row_tv });
audioList.setAdapter(adapter);
}
private void setUI() {
for (int a = 0; a <= 11; a++) {
map = new HashMap<String, String>();
map.put("Image", "" + mImages[a]);
map.put("text", mSign[a]);
dataList.add(map);
map = null;
}
}
#Override
protected void onStart() {
super.onStart();
setAdapter();
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
/*private class NextTask extends AsyncTask<Void,Void,Void> {
ProgressDialog progressDailog = new ProgressDialog(Audiovediolist.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDailog.setTitle("Please Wait");
progressDailog.setMessage("URL Data Loading ...");
progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDailog.setCancelable(true);
progressDailog.show();
}
#SuppressWarnings("static-access")
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDailog.dismiss();
}
}*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
data = dataList.get(position);
try {
NetWorkCheck netWork = new NetWorkCheck();
if (netWork.isNetWorkConnection(this)) {
if (Screen_Id == 1) {
// new NextTask().execute();
Intent audioInt=new Intent(getApplicationContext(),AudioView.class);
audioInt.setType(data.get("text"));
startActivity(audioInt);
} else if (Screen_Id == 2) {
Intent vedioInt = new Intent(this, VideoPlayActivity.class);
vedioInt.setType(data.get("text"));
startActivity(vedioInt);
}
} else {
netWork.alert();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Problem while ListItemClick", Toast.LENGTH_SHORT).show();
}
}
}
The code for audio player used is
public class AudioView extends Activity implements OnClickListener {
private MediaPlayer mMediaPlayer;
private ImageView mPlay;
private ImageView mPause;
private ImageView mBack;
private ImageView mFar;
private ProgressBar myProgressBar;
// private PlayerService mService;
private boolean boolFlag = false;
private boolean isPausedInCall = false;
private String url;
private TelephonyManager mTelephoneMgr;
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
private TextView tv;
// private boolean serviceRunning;
Notification notifyDetails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.audio_main);
getIntentValues();
initUI();
uiListener();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notifyDetails = new Notification(R.drawable.mulug_icon, url,
System.currentTimeMillis());
mTelephoneMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mTelephoneMgr != null) {
mTelephoneMgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void getIntentValues() {
url = getIntent().getType();
}
private void uiListener() {
mPlay.setOnClickListener(this);
mPlay.setOnClickListener(this);
mPause.setOnClickListener(this);
mPause.setVisibility(android.view.View.INVISIBLE);
mBack.setOnClickListener(this);
mFar.setOnClickListener(this);
}
private void initUI() {
tv = (TextView) findViewById(R.id.text);
mBack = (ImageView) findViewById(R.id.back);
mPlay = (ImageView) findViewById(R.id.play);
mPause = (ImageView) findViewById(R.id.pause);
mFar = (ImageView) findViewById(R.id.fwd);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
myProgressBar.setProgressDrawable(getResources().getDrawable(
R.drawable.green_progress));
myProgressBar.setProgress(0);
tv.setText(url);
tv.setFocusable(true);
}
private Thread myThread = new Thread() {
public void run() {
while (mMediaPlayer.getCurrentPosition() < mMediaPlayer
.getDuration()) {
try {
myProgressBar
.setProgress(mMediaPlayer.getCurrentPosition());
} catch (Throwable t) {
}
}
}
};
#SuppressLint("NewApi")
#Override
public void onBackPressed() {
super.onBackPressed();
mMediaPlayer.stop();
// myThread.stop();
// mMediaPlayer.release();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
System.gc();
}
#Override
protected void onDestroy() {
super.onDestroy();
System.gc();
}
#SuppressLint("NewApi")
#Override
protected void onStart() {
super.onStart();
this.setProgressBarIndeterminateVisibility(true);
try {
if (boolFlag == false) {
System.out.println(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3");
mMediaPlayer = MediaPlayer.create(
this,
Uri.parse(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3"));
}
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Loading Problems",
Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "ServerFailed to Load...");
super.onBackPressed();
e.printStackTrace();
}
}
public PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
System.out.println("ringing state");
if (mMediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
notificationShow();
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
System.out.println("callState Idle");
if (mMediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
private void pauseMedia() {
mMediaPlayer.pause();
changePlayerIcons(false);
}
private void playMedia() {
mMediaPlayer.start();
changePlayerIcons(true);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!boolFlag) {
try {
notificationShow();
mMediaPlayer.setLooping(false);
// mMediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "preparing", Toast.LENGTH_SHORT)
.show();
}
boolFlag = true;
mMediaPlayer.start();
myThread.start();
} else {
notificationShow();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.start();
}
changePlayerIcons(true);
myProgressBar.setProgress(mMediaPlayer.getCurrentPosition());
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
changePlayerIcons(false);
myProgressBar.setProgress(0);
onStart();
}
});
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
mMediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(),
"MediaPlayer Errors", Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "MediaPlayer Errors...");
return false;
}
});
break;
case R.id.pause:
mMediaPlayer.pause();
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
break;
case R.id.back:
int dur = mMediaPlayer.getCurrentPosition();
int pos = (dur > 10000 ? dur - 5000 : 0);
mMediaPlayer.seekTo(pos);
break;
case R.id.fwd:
int curpos = mMediaPlayer.getCurrentPosition();
int dur2 = mMediaPlayer.getDuration();
int pos2 = (curpos + 5000 > dur2 ? dur2 : curpos + 5000);
mMediaPlayer.seekTo(pos2);
break;
}
}
private void notificationShow() {
Context context = getApplicationContext();
CharSequence contentTitle = "Mulugu Running";
CharSequence contentText = url + " Weekly Predictions";
Intent notifyIntent = new Intent(AudioView.this, AudioView.class);
PendingIntent intent = PendingIntent.getActivity(AudioView.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText,
intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
private void changePlayerIcons(boolean b) {
if (b) {
mPlay.setVisibility(android.view.View.INVISIBLE);
mPause.setVisibility(android.view.View.VISIBLE);
} else {
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
}
}
}
The XML used is
<?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:background="#drawable/main_audio"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.45"
android:orientation="vertical" >
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text=" for more details check on "
android:textColor="#FF0000"
android:textSize="20dp"
android:textStyle="italic" >
</TextView>
</LinearLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" >
<ImageView
android:id="#+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:src="#drawable/audio_pause" />
<ImageView
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="2dp"
android:layout_marginTop="10dp"
android:src="#drawable/audio_play" />
<ImageView
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/pause"
android:layout_marginRight="1dp"
android:layout_toLeftOf="#+id/pause"
android:layout_toRightOf="#drawable/audio_play"
android:src="#drawable/audio_bwd" />
<ImageView
android:id="#+id/fwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/pause"
android:layout_marginLeft="1dp"
android:layout_toRightOf="#+id/pause"
android:src="#drawable/audio_fwd" />
</RelativeLayout>
<ProgressBar
android:id="#+id/progressbar_Horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Here is an example:
public class TextViewMarquee extends Activity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.tv);
tv.setSelected(true); // Set focus to the textview
}
}
The xml file with the textview:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textColor="#ff4500"
android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>