I have a problem with my app. I have an app that streams radio stations. The stream starts when the user clicks on a item of the gridview. To stop the stream i made a button(stop) that appears when the stream starts. The problem appears when the user click many times the same item of the gridview because when click on stop button the stream don't stop, how can i solve that ?
public class MainActivity extends ActionBarActivity {
private GridView grid;
private InterstitialAd interstitial, inter2;
private TextView name;
private ProgressBar bar;
private ImageView stop;
private RelativeLayout rela;
private RadioPlayerManager mRadioManager;
private String[] web = {
"Radio RDS",
"Rai 1 Radio",
"Radio R101",
"Radio RTL102.5",
"Radio Virgin",
"Radio RMC",
"Radio Antenna1",
"Radio 105",
"Radio Milano",
"Radio Onda Libera",
};
private int[] imageId = {
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
R.drawable.playy,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadioManager = new RadioPlayerManager();
rela = (RelativeLayout) findViewById(R.id.relativeLayout);
bar = (ProgressBar) findViewById(R.id.progressBar);
stop = (ImageView) findViewById(R.id.imageView);
name = (TextView) findViewById(R.id.textView3);
grid = (GridView) findViewById(R.id.gridView1);
bar.setVisibility(View.GONE);
rela.setVisibility(View.GONE);
CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid.setAdapter(adapter);
ads();
listeners();
firstRun();
animations();
}
private void ads() {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-5426545253667840/9595287619");
inter2 = new InterstitialAd(this);
inter2.setAdUnitId("ca-app-pub-5426545253667840/9595287619");
AdRequest adRequest1 = new AdRequest.Builder().build();
inter2.loadAd(adRequest1);
inter2.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
AdRequest adRequest2 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest2);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
public void onAdClosed() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
// Load the interstitial ad again
interstitial.loadAd(adRequest);
}
});
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
}
}
private void firstRun() {
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun", true);
if (firstrun) {
new android.app.AlertDialog.Builder(this)
.setTitle("Radio Italia") //set the Title text
.setMessage("Ciao! " +
"Con Radio Italia puoi ascoltare la maggior parte delle radio italiane gratis, senza nessun costo." +
"Radio Italia ha al suo interno degli spot(ads) che aiutano lo sviluppatore a continuare il suo lavoro." +
"Se ti piace l'app non dimenticarti di darli 5 stele su Play Store. Grazie!")
.setNeutralButton("OK!", null).show(); //Sets the button type
}
// Save the state with shared preferences
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun", false)
.commit();
}
private void listeners() {
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
rela.setVisibility(View.VISIBLE);
bar.setVisibility(View.VISIBLE);
if (position == 0) {
mRadioManager.play("http://www.rds.it:8000/stream", mediaPlayerCallback);
name.setText("Stai ascoltando RDS");
bar.setVisibility(View.INVISIBLE);
}
if (position == 1) {
mRadioManager.play("http://icestreaming.rai.it/1.mp3", mediaPlayerCallback);
name.setText("Stai ascoltando Rai 1");
bar.setVisibility(View.INVISIBLE);
}
if (position == 2) {
mRadioManager.play("http://str30.creacast.com/r101a", mediaPlayerCallback);
name.setText("Stai ascoltando R101");
bar.setVisibility(View.INVISIBLE);
}
if (position == 3) {
mRadioManager.play("http://shoutcast.rtl.it:3010/stream/1/", mediaPlayerCallback);
name.setText("Stai ascoltando RTL102.5");
bar.setVisibility(View.INVISIBLE);
}
if (position == 4) {
mRadioManager.play("http://shoutcast.unitedradio.it:1301/", mediaPlayerCallback);
name.setText("Stai ascoltando Virgin Radio");
bar.setVisibility(View.INVISIBLE);
}
if (position == 5) {
mRadioManager.play("http://shoutcast.unitedradio.it:1103/", mediaPlayerCallback);
name.setText("Stai ascoltando RMC");
bar.setVisibility(View.INVISIBLE);
}
if (position == 6) {
mRadioManager.play("http://s3.mediastreaming.it:7568/", mediaPlayerCallback);
name.setText("Stai ascoltando Antenna1");
bar.setVisibility(View.INVISIBLE);
}
if (position == 7) {
mRadioManager.play("http://shoutcast.unitedradio.it:1101/", mediaPlayerCallback);
name.setText("Stai ascoltando Radio105");
bar.setVisibility(View.INVISIBLE);
}
if (position == 8) {
mRadioManager.play("http://sh1.inmystream.info:8175/", mediaPlayerCallback);
name.setText("Stai ascoltando Radio Milano");
bar.setVisibility(View.INVISIBLE);
}
if (position == 9) {
mRadioManager.play("http://s6.mediastreaming.it:9064/", mediaPlayerCallback);
name.setText("Stai ascoltando Onda Libera");
bar.setVisibility(View.INVISIBLE);
} else {
mRadioManager.stop();
}
}
;
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRadioManager.stop();
rela.setVisibility(View.INVISIBLE);
interstitial.show();
}
});
}
private void animations() {
Animation anim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.abc_fade_in);
anim.setDuration(1500);
name.setAnimation(anim);
anim.setRepeatCount(Animation.INFINITE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.share:
shareIt();
break;
case R.id.play:
gp();
break;
case R.id.like:
fb();
break;
case R.id.plus:
plus();
break;
}
return true;
}
private void fb() {
try {
Intent fb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/315814045239841"));
startActivity(fb);
} catch (Exception e) {
Intent fb = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/Denis-Projects-315814045239841/"));
startActivity(fb);
}
}
private void shareIt() {
String shareBody = "Ascult cele mai tari posturi de manele cu aplicatia Radio manele 2016. Descarc-o si tu,e gratuit! https://play.google.com/store/apps/details?id=com.denisprojects.radiomanele2016";
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Radio manele 2016");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Distribuie"));
}
private void gp() {
// TODO Auto-generated method stub
Intent gp = new Intent(Intent.ACTION_VIEW);
gp.setData(Uri.parse("https://play.google.com/store/apps/developer?id=DenisProjects"));
startActivity(gp);
}
private void plus() {
Intent plus = new Intent(Intent.ACTION_VIEW);
plus.setData(Uri.parse("https://plus.google.com/u/0/102131527060290623635"));
startActivity(plus);
}
private MediaPlayerCallback mediaPlayerCallback = new MediaPlayerCallback() {
#Override
public void onMetadata(String value){
}
#Override
public void onError() { rela.setVisibility(View.VISIBLE);
name.setText("Errore!Scegli altra radio");
}
#Override
public void onBuffering() {
}
#Override
public void onPlaying() {
}
#Override
public void onStopped() {
}
};
}
public class RadioPlayerManager {
private MultiPlayer mMultiPlayer;
private MediaPlayerCallback mCallback;
private static String TAG = RadioPlayerManager.class.getSimpleName();
public RadioPlayerManager() {
try {
java.net.URL.setURLStreamHandlerFactory(new java.net.URLStreamHandlerFactory() {
public java.net.URLStreamHandler createURLStreamHandler(String protocol) {
Log.d(TAG, "Asking for stream handler for protocol: '" + protocol + "'");
if ("icy".equals(protocol))
return new com.spoledge.aacdecoder.IcyURLStreamHandler();
return null;
}
});
} catch (Throwable t) {
Log.w(TAG, "Cannot set the ICY URLStreamHandler - maybe already set ? - " + t);
}
}
public void play(String url, MediaPlayerCallback callback) {
mCallback = callback;
mMultiPlayer = new MultiPlayer(mPlayerCallback, MultiPlayer.DEFAULT_AUDIO_BUFFER_CAPACITY_MS, MultiPlayer.DEFAULT_DECODE_BUFFER_CAPACITY_MS);
mMultiPlayer.playAsync(url);
mCallback.onBuffering();
}
public void stop() {
mMultiPlayer.stop();
}
private PlayerCallback mPlayerCallback = new PlayerCallback() {
#Override
public void playerStarted() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.onPlaying();
}
});
}
#Override
public void playerPCMFeedBuffer(boolean b, int i, int i1) {
}
#Override
public void playerStopped(int i) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.onStopped();
}
});
}
#Override
public void playerException(Throwable throwable) {
mCallback.onError();
}
#Override
public void playerMetadata(String key, final String value) {
if ("StreamTitle".equals(key)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.onMetadata(value);
}
});
}
}
#Override
public void playerAudioTrackCreated(AudioTrack audioTrack) {
}
public boolean isPlaying(){
mMultiPlayer.stop();
return true;
}
};
}
public interface MediaPlayerCallback {
void onMetadata(String value);
void onError();
void onBuffering();
void onPlaying();
void onStopped();
}
No one knows how to do that ?
it is better to not start playing if the selected gridview item is already playing. so you can store the value of playing gridview item and check it before you call mRadioManager.play("http://s6.mediastreaming.it:9064/", mediaPlayerCallback);
Related
I set an interstitial after press a play button in the app.
Ok, this runs perfect but the interstitial appears immediately after the button pressed.
Is there a way to add a delay of to say 10 sec before it pop ups? Ie. user press plays and 10 sec after the interstitial appears.
In the code I have the following lines:
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
}
}
public void onClickPlayButton(View view) {
radioService.play();
interstitial.show();
}
Here is my full MainActity.java
public class MainActivity extends BaseActivity {
private InterstitialAd interstitial;
private static boolean displayAd;
private Button playButton;
private Button pauseButton;
private Button stopButton;
private Button nextButton;
private Button previousButton;
private ImageView stationImageView;
private TextView titleTextView;
private TextView albumTextView;
private TextView artistTextView;
private TextView trackTextView;
private TextView statusTextView;
private TextView timeTextView;
private Intent bindIntent;
private TelephonyManager telephonyManager;
private boolean wasPlayingBeforePhoneCall = false;
private RadioUpdateReceiver radioUpdateReceiver;
public static RadioService radioService;
private AdView mAdView;
private String STATUS_BUFFERING;
private static final String TYPE_AAC = "aac";
private static final String TYPE_MP3 = "mp3";
private Handler handler;
private AudioManager leftAm;
private SeekBar volControl;
private ContentObserver mVolumeObserver;
public static int stationID = 0;
public static boolean isStationChanged = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
interstitial = new InterstitialAd(MainActivity.this);
interstitial.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXXXXX");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
interstitial.loadAd(adRequest);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
displayInterstitial();
}
}, 60000);
// Bind to the service
try {
bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
}
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (telephonyManager != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
handler = new Handler();
initialize();
// Prepare an Interstitial Ad Listener
//interstitial.setAdListener(new AdListener() {
//public void onAdLoaded() {
// Call displayInterstitial() function
//displayInterstitial();
//}
//});
}
///public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
///if (interstitial.isLoaded()) {
///interstitial.show();
///}
///}
// agrega boton share a la app
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Listen to my radio https://play.google.com/store/apps/details?id=radio");
mShare.setShareIntent(shareIntent);
}
return true;
}
// fin boton share
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT
|| newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
try {
setContentView(R.layout.activity_main);
handler.post(new Runnable() {
#Override
public void run() {
initialize();
if (radioService.getTotalStationNumber() <= 1) {
nextButton.setEnabled(false);
nextButton.setVisibility(View.INVISIBLE);
previousButton.setEnabled(false);
previousButton.setVisibility(View.INVISIBLE);
}
updateStatus();
updateMetadata();
updateAlbum();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void initialize() {
try {
displayAd = Boolean.parseBoolean(getResources().getString(
R.string.is_display_ad));
STATUS_BUFFERING = getResources().getString(
R.string.status_buffering);
playButton = (Button) this.findViewById(R.id.PlayButton);
pauseButton = (Button) this.findViewById(R.id.PauseButton);
stopButton = (Button) this.findViewById(R.id.StopButton);
nextButton = (Button) this.findViewById(R.id.NextButton);
previousButton = (Button) this.findViewById(R.id.PreviousButton);
pauseButton.setEnabled(false);
pauseButton.setVisibility(View.INVISIBLE);
stationImageView = (ImageView) findViewById(R.id.stationImageView);
playButton.setEnabled(true);
stopButton.setEnabled(false);
titleTextView = (TextView) this.findViewById(R.id.titleTextView);
albumTextView = (TextView) this.findViewById(R.id.albumTextView);
artistTextView = (TextView) this.findViewById(R.id.artistTextView);
trackTextView = (TextView) this.findViewById(R.id.trackTextView);
statusTextView = (TextView) this.findViewById(R.id.statusTextView);
timeTextView = (TextView) this.findViewById(R.id.timeTextView);
// volume
leftAm = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = leftAm
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = leftAm.getStreamVolume(AudioManager.STREAM_MUSIC);
volControl = (SeekBar) findViewById(R.id.volumebar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar a0, int a1,
boolean a2) {
leftAm.setStreamVolume(AudioManager.STREAM_MUSIC,
a1, 0);
}
});
Handler mHandler = new Handler();
// in onCreate put
mVolumeObserver = new ContentObserver(mHandler) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
if (volControl != null && leftAm != null) {
int volume = leftAm
.getStreamVolume(AudioManager.STREAM_MUSIC);
volControl.setProgress(volume);
}
}
};
this.getContentResolver()
.registerContentObserver(
System.getUriFor(System.VOLUME_SETTINGS[AudioManager.STREAM_MUSIC]),
false, mVolumeObserver);
// vloume
startService(new Intent(this, RadioService.class));
displayAd();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
volControl = (SeekBar) findViewById(R.id.volumebar);
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
int index = volControl.getProgress();
volControl.setProgress(index + 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
int index = volControl.getProgress();
volControl.setProgress(index - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void displayAd() {
if (displayAd == true) {
// Create the adView
try {
if (mAdView != null) {
mAdView.destroy();
}
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
} catch (OutOfMemoryError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else {
LinearLayout layout = (LinearLayout) findViewById(R.id.adLayout);
layout.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
layout.setVisibility(View.INVISIBLE);
}
}
public void updatePlayTimer() {
timeTextView.setText(radioService.getPlayingTime());
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
timeTextView.setText(radioService.getPlayingTime());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
}
}
public void onClickPlayButton(View view) {
radioService.play();
interstitial.show();
}
public void onClickPauseButton(View view) {
radioService.pause();
}
public void onClickStopButton(View view) {
radioService.stop();
resetMetadata();
updateDefaultCoverImage();
}
public void onClickNextButton(View view) {
resetMetadata();
playNextStation();
updateDefaultCoverImage();
}
public void onClickPreviousButton(View view) {
resetMetadata();
playPreviousStation();
updateDefaultCoverImage();
}
public void playNextStation() {
radioService.stop();
radioService.setNextStation();
/*
* if(radioService.isPlaying()) {
* radioService.setStatus(STATUS_BUFFERING); updateStatus();
* radioService.stop(); radioService.play(); } else {
* radioService.stop(); }
*/
}
public void playPreviousStation() {
radioService.stop();
radioService.setPreviousStation();
/*
* if(radioService.isPlaying()) {
* radioService.setStatus(STATUS_BUFFERING); updateStatus();
* radioService.stop(); radioService.play(); } else {
* radioService.stop(); }
*/
}
public void updateDefaultCoverImage() {
try {
String mDrawableName = "station_"
+ (radioService.getCurrentStationID() + 1);
int resID = getResources().getIdentifier(mDrawableName, "drawable",
getPackageName());
int resID_default = getResources().getIdentifier("station_default",
"drawable", getPackageName());
if (resID > 0)
stationImageView.setImageResource(resID);
else
stationImageView.setImageResource(resID_default);
albumTextView.setText("");
} catch(Exception e) {
e.printStackTrace();
}
}
public void updateAlbum() {
String album = radioService.getAlbum();
String artist = radioService.getArtist();
String track = radioService.getTrack();
Bitmap albumCover = radioService.getAlbumCover();
albumTextView.setText(album);
if (albumCover == null || (artist.equals("") && track.equals("")))
updateDefaultCoverImage();
else {
stationImageView.setImageBitmap(albumCover);
radioService.setAlbum(LastFMCover.album);
if (radioService.getAlbum().length()
+ radioService.getArtist().length() > 50) {
albumTextView.setText("");
}
}
}
public void updateMetadata() {
String artist = radioService.getArtist();
String track = radioService.getTrack();
// if(artist.length()>30)
// artist = artist.substring(0, 30)+"...";
artistTextView.setText(artist);
trackTextView.setText(track);
albumTextView.setText("");
}
public void resetMetadata() {
radioService.resetMetadata();
artistTextView.setText("");
albumTextView.setText("");
trackTextView.setText("");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (radioService != null) {
if (!radioService.isPlaying() && !radioService.isPreparingStarted()) {
// radioService.stopSelf();
radioService.stopService(bindIntent);
}
}
if (mAdView != null) {
mAdView.destroy();
}
if (telephonyManager != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
unbindDrawables(findViewById(R.id.RootView));
Runtime.getRuntime().gc();
}
private void unbindDrawables(View view) {
try {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
// finish();
}
#Override
protected void onResume() {
super.onResume();
/* Register for receiving broadcast messages */
if (radioUpdateReceiver == null)
radioUpdateReceiver = new RadioUpdateReceiver();
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_CREATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_DESTROYED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_STARTED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_CONNECTING));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_START_PREPARING));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_PREPARED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_PLAYING));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_PAUSED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_STOPPED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_COMPLETED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_ERROR));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_BUFFERING_START));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_BUFFERING_END));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_METADATA_UPDATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_ALBUM_UPDATED));
if (wasPlayingBeforePhoneCall) {
radioService.play();
wasPlayingBeforePhoneCall = false;
}
if (radioService != null) {
if (isStationChanged) {
if (stationID != radioService.getCurrentStationID()) {
radioService.stop();
radioService.setCurrentStationID(stationID);
resetMetadata();
updateDefaultCoverImage();
}
if (!radioService.isPlaying())
radioService.play();
isStationChanged = false;
}
}
}
/* Receive Broadcast Messages from RadioService */
private class RadioUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RadioService.MODE_CREATED)) {
} else if (intent.getAction().equals(RadioService.MODE_DESTROYED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateDefaultCoverImage();
updateMetadata();
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_STARTED)) {
pauseButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
playButton.setEnabled(true);
stopButton.setEnabled(false);
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_CONNECTING)) {
pauseButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
playButton.setEnabled(false);
stopButton.setEnabled(true);
updateStatus();
} else if (intent.getAction().equals(
RadioService.MODE_START_PREPARING)) {
pauseButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
playButton.setEnabled(false);
stopButton.setEnabled(true);
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_PREPARED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
} else if (intent.getAction().equals(
RadioService.MODE_BUFFERING_START)) {
updateStatus();
} else if (intent.getAction().equals(
RadioService.MODE_BUFFERING_END)) {
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_PLAYING)) {
if (radioService.getCurrentStationType().equals(TYPE_AAC)) {
playButton.setEnabled(false);
stopButton.setEnabled(true);
} else {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
playButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
}
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_PAUSED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_STOPPED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_COMPLETED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
// radioService.setCurrentStationURL2nextSlot();
// radioService.play();
updateStatus();
} else if (intent.getAction().equals(RadioService.MODE_ERROR)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
} else if (intent.getAction().equals(
RadioService.MODE_METADATA_UPDATED)) {
updateMetadata();
updateStatus();
updateDefaultCoverImage();
} else if (intent.getAction().equals(
RadioService.MODE_ALBUM_UPDATED)) {
updateAlbum();
}
}
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
wasPlayingBeforePhoneCall = radioService.isPlaying();
radioService.stop();
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
if (wasPlayingBeforePhoneCall) {
radioService.play();
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
// A call is dialing,
// active or on hold
wasPlayingBeforePhoneCall = radioService.isPlaying();
radioService.stop();
}
super.onCallStateChanged(state, incomingNumber);
}
};
public void updateStatus() {
String status = radioService.getStatus();
if (radioService.getTotalStationNumber() > 1) {
/*
* if (status != "") status = radioService.getCurrentStationName() +
* " - " + status; else status =
* radioService.getCurrentStationName();
*/
String title = radioService.getCurrentStationName();
try {
titleTextView.setText(title);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
statusTextView.setText(status);
} catch (Exception e) {
e.printStackTrace();
}
}
// Handles the connection between the service and activity
private final ServiceConnection radioConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
radioService = ((RadioService.RadioBinder) service).getService();
if (radioService.getTotalStationNumber() <= 1) {
nextButton.setEnabled(false);
nextButton.setVisibility(View.INVISIBLE);
previousButton.setEnabled(false);
previousButton.setVisibility(View.INVISIBLE);
}
updateStatus();
updateMetadata();
updateAlbum();
updatePlayTimer();
radioService.showNotification();
/*
* Uncomment following line if you want auto-play while starting the
* app
*/
// radioService.play();
}
#Override
public void onServiceDisconnected(ComponentName className) {
radioService = null;
}
};
}
Use a Handler. See this code:
new Handler().postDelayed(new Runnable(){
public void run() {
//Your your code here.
}
}, 5000); //Here 5000 is the time delay. Change it accordingly.
Kvaibhav01's answer will work. You can also use Timer:
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
public void run() {
//your code here
}
}, 1000); //delay in ms
I tried the handler and now works (I messed up the order)
This is the correct code:
public void onClickPlayButton(View view) {
radioService.play();
new Handler().postDelayed(new Runnable(){
public void run() {
interstitial.show();
}
}, 10000);
Thank you very much for the help!
I am creating this application which has three tabs. Tab1 is used to handle bluetooth incoming and outgoing connections. The major problem comes here is once i click the connect button the connection is created but when i switch tabs and then jump back to tab1 everything is lost as the tab is reinitialized. I want to stop this from happening. Please suggest me the correction in my code.
Here is the MainActivity.java file
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
private TabLayout tabLayout;
StringBuilder recDataString = new StringBuilder();
int handlerState = 0;
private ViewPager viewPager;
int initialize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Manual"));
tabLayout.setSelectedTabIndicatorColor(Color.BLACK);
tabLayout.addTab(tabLayout.newTab().setText("Status"));
tabLayout.addTab(tabLayout.newTab().setText("Database"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager)findViewById(R.id.pager);
Pager adapter = new Pager(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setOnTabSelectedListener(this);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("BS");
Log.d("********", "ID = " + id);
/*if (id.equalsIgnoreCase("F")) {
sendToConnectedThread(id);
}*/
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.nitesh.finaltab.DATA_BROADCAST");
getApplicationContext().registerReceiver(broadcastReceiver,filter);
}
public int getInitialize(){
return initialize;
}
public void setInitialize(int m){
this.initialize = m;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Here is the Pager.java file
public class Pager extends FragmentStatePagerAdapter {
int tabcount;
public Pager(FragmentManager fm, int tabcount){
super(fm);
this.tabcount = tabcount;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount(){return tabcount;}
}
And here is the Tab1.java file
public class Tab1 extends Fragment {
SQLiteDatabase alexadb,activitydb;
MainActivity mainActivity= new MainActivity();
StringBuilder recDataString = new StringBuilder();
String address = "98:D3:32:20:5A:57";
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
int handlerState = 0;
public boolean isBtConnected = false;
ProgressDialog progressDialog;
int initialize = 0;
Handler bluetoothIn;
BluetoothAdapter myBluetooth;
BluetoothSocket bluetoothSocket;
ConnectedThread connectedThread ;
Button connect,forward,reverse,left,right,stop;
int speed;
String datatoSend;
private final long REPEAT_DELAY = 50;
boolean autoIncreament,autoDecreament;
View view;
private Handler repeatUpdateHandler = new Handler();
private Handler senddataUpdatehandler = new Handler();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
createDatabase();
view = inflater.inflate(R.layout.tab1, container, false);
forward = (Button) view.findViewById(R.id.bforward);
reverse = (Button) view.findViewById(R.id.breverse);
left = (Button) view.findViewById(R.id.bleft);
stop = (Button) view.findViewById(R.id.bstop);
connect = (Button)view.findViewById(R.id.buttonConnect);
right = (Button) view.findViewById(R.id.bright);
Toast.makeText(getContext(), "Tab1 Initiated", Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Ready to connect?");
handler();
class RepetitiveUpdater implements Runnable {
#Override
public void run() {
if (autoIncreament) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecreament) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Process Initiated", Toast.LENGTH_SHORT).show();
new CheckBT().execute();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// bluetoothConnect.sendData("R");
Log.d("Right", "Button is clicked");
sendData("R");
insertIntoActivityDB("Right Button is clicked");
}
});
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("L");
insertIntoActivityDB("Left Button is clicked");
}
});
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData("B");
insertIntoActivityDB("Reverse Button is clicked");
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autoDecreament = false;
autoIncreament = false;
sendData("S");
insertIntoActivityDB("Stop Button is clicked");
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
sendData("F");
insertIntoActivityDB("Forward Button is clicked");
}
});
forward.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
autoIncreament = true;
autoDecreament = false;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
forward.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && autoIncreament) {
autoIncreament = false;
autoDecreament = true;
sendData("D");
repeatUpdateHandler.post(new RepetitiveUpdater());
}
return false;
}
});
return view;
}
public void handler() {
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endofLineIndex = recDataString.indexOf("~");
if (endofLineIndex > 0) {
// String dataInPrint = recDataString.substring(0,endofLineIndex);
String data = recDataString.substring(1, endofLineIndex);
Log.d("Received Text", "" + data);
String first = recDataString.substring(0, 1);
Log.d("First letter ", "Hello" + first);
if (first.equalsIgnoreCase("P")) {
insertIntoAlexaDB(data);
}
if (first.equalsIgnoreCase("V")) {
insertIntoAlexaDB(data);
} else {
}
recDataString.delete(0, recDataString.length());
// dataInPrint = " ";
data = "";
first = " ";
}
}
}
};
}
public void increment(){
speed++;
sendData("F");
Log.d("Increasing Speed"," "+speed);
}
public void decrement() {
if (speed > 0) {
speed--;
sendData("D");
Log.d("Decreasing Speed", " " + speed);
}
}
public class CheckBT extends AsyncTask<Void, Void, Void>//UI Thread
{
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getContext(), "Connecting you", "From Alexa");
Toast.makeText(getContext(),"Conneting",Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
if (bluetoothSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = myBluetooth.getRemoteDevice(address);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID); //Create RFCOMM connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
bluetoothSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
Toast.makeText(getContext(), "HC-05 didn't respond", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getContext(), "Connection Failed. Try Again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
isBtConnected = true;
connectedThread = new ConnectedThread(bluetoothSocket);
connectedThread.start();
}
progressDialog.dismiss();
}
}
private class ConnectedThread extends Thread{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the thread
public ConnectedThread(BluetoothSocket bluetoothSocket){
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
//create I/O streams for connection
tmpIn = bluetoothSocket.getInputStream();
tmpOut = bluetoothSocket.getOutputStream();
}catch (IOException
e){}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public boolean getBluetoothStatus() {
Toast.makeText(getContext(),"Bluetooth Status from thread"+isBtConnected,Toast.LENGTH_SHORT).show();
return isBtConnected;
}
public void run(){
byte[] buffer = new byte[256];
int bytes;
//keep looping ot listen for received messages
while(true){
try{
Log.d("Running"," Connected_Thread");
isBtConnected = true;
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer,0,bytes);
//Send the obtained bytes to the UIActivity via handler
bluetoothIn.obtainMessage(handlerState,bytes,-1,readMessage).sendToTarget();
}catch (IOException e){
break;
}
}
}
}
public void sendData(String data) {
try {
bluetoothSocket.getOutputStream().write(data.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creation of DATABASE**/
public void createDatabase(){
alexadb = getContext().openOrCreateDatabase("AlexaDB", Context.MODE_PRIVATE,null);
activitydb= getContext().openOrCreateDatabase("ActivityDB",Context.MODE_PRIVATE,null);
alexadb.execSQL("CREATE TABLE IF NOT EXISTS alexa(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
activitydb.execSQL("CREATE TABLE IF NOT EXISTS activity(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
}
public boolean insertIntoAlexaDB( String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO alexa(data)VALUES('" + data + "');";
alexadb.execSQL(query);
return true;
}
}
public boolean insertIntoActivityDB(String data){
if (data.equalsIgnoreCase(" ")) {
return false;
} else {
String query = "INSERT INTO activity(data)VALUES('" + data + "');";
activitydb.execSQL(query);
return true;
}
}
}
Is this happening only when you select the last tab? Take a look at the offscreen page limit parameter: basically you can set the number of pages to retain in memory when you scroll the ViewPager. In your case, an offscreen page limit of 2 should be enough to always keep all the pages in memory.
I am trying to create a music player in ViewPager when the user swipes, the player should play the next song. The views are updating correctly but the song is not sync with them. For example, it's playing the second song in the first fragment. I tried a lot of things but I'm not able to find where is the issue. Please anyone give me a solution. Thanks in advance.
public class AudioActivity extends AppCompatActivity {
List<PlayerModel> audioList;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
audioList=getIntent().getParcelableArrayListExtra(getString(R.string.SONG_LIST));
position=getIntent().getIntExtra(getString(R.string.SONG_POSITION),0);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
AudioActivity.ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new AudioActivity.ViewPagerAdapter(getSupportFragmentManager());
AudioPlayerAdapter audioPlayerAdapter=new AudioPlayerAdapter();
for(int i=0;i<audioList.size();i++) {
adapter.addFragment(audioPlayerAdapter.newInstance(audioList, i), AppConstants.AUDIO_PLAYER);
}
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new CubeInTransformer());
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void setFragment(Fragment fragment, int position,String title) {
mFragmentList.set(position,fragment);
mFragmentTitleList.set(position,title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
My Fragment
public class AudioPlayerAdapter extends Fragment implements SeekBar.OnSeekBarChangeListener {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
TextView textStatus, textIntValue, textStrValue;
Messenger mService = null;
boolean mIsBound;
public static Handler messageHandler;
long duration, currSongPosition;
ImageView displayArt;
TextView playerName;
TextView totTime;
TextView fromTime;
List<PlayerModel> songList;
RecyclerView songRecyclerView;
ImageButton showList;
ImageButton playAudio;
ImageButton pauseAudio;
ImageButton stepForward;
ImageButton stepBackward;
ImageButton shuffleAudio;
ImageButton volumeAudio;
ImageButton repeatAudio;
int songPosition;
SeekBar songProgressBar;
SeekBar volumeSeekBar;
private Intent playIntent;
//binding
private boolean musicBound = false;
private float x1, x2;
static final int MIN_DISTANCE = 150;
//activity and playback pause flags
private boolean paused = false, playbackPaused = false;
private Handler mHandler = new Handler();
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
public AudioPlayerAdapter newInstance(List<PlayerModel> playerList, int position) {
AudioPlayerAdapter fragment = new AudioPlayerAdapter();
Bundle b = new Bundle();
b.putParcelableArrayList(AppConstants.SONG_LIST, (ArrayList<? extends Parcelable>) playerList);
b.putInt(AppConstants.SONG_POSITION, position);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_music_player, container, false);
songList = getArguments().getParcelableArrayList(getString(R.string.SONG_LIST));
songPosition = getArguments().getInt(getString(R.string.SONG_POSITION), 0);
LogUtil.error("Song Position",songPosition+"-->"+songList.get(songPosition).getPlayerTitle());
FieldIntialization(view);
if (playIntent == null) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), songPosition);
getActivity().startService(playIntent);
}
DataInitialization(songPosition);
messageHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MusicService.MSG_SET_INT_VALUE:
break;
case MusicService.MSG_PLAY:
LogUtil.error("Pause", "Pause");
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
break;
case MusicService.MSG_PAUSE:
LogUtil.error("Play", "Play");
playAudio.setImageResource(R.drawable.ic_play_white_24dp);
break;
case MusicService.MSG_NEXT:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_PREVIOUS:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_UPDATE_SEEKBAR:
duration = msg.getData().getLong(getString(R.string.SONG_DURATION));
currSongPosition = msg.getData().getLong(getString(R.string.SONG_CURR_DURATION));
break;
case MusicService.MSG_SHUFFLE_OFF:
Toast.makeText(getActivity(), "Shuffle Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_SHUFFLE_ON:
Toast.makeText(getActivity(), "Shuffle On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_ON:
Toast.makeText(getActivity(), "Repeat On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_OFF:
Toast.makeText(getActivity(), "Repeat Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_CLOSE:
getActivity().finish();
break;
case MusicService.MSG_STOP:
break;
default:
super.handleMessage(msg);
}
}
};
return view;
}
/* #Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
*//* outState.putString("textStatus", textStatus.getText().toString());
outState.putString("textIntValue", textIntValue.getText().toString());
outState.putString("textStrValue", textStrValue.getText().toString());*//*
}
private void restoreMe(Bundle state) {
if (state != null) {*//*
textStatus.setText(state.getString("textStatus"));
textIntValue.setText(state.getString("textIntValue"));
textStrValue.setText(state.getString("textStrValue"));*//*
}
}*/
public void stopService() {
getActivity().stopService(new Intent(getActivity(), MusicService.class));
}
private void sendMessageToService(int action) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
getActivity().startService(startIntent);
}
private void sendMessageToServiceWithData(int action, int currPosition) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
startIntent.putExtra(getString(R.string.SEEK_POSITION), currPosition);
getActivity().startService(startIntent);
}
private void FieldIntialization(View view) {
songProgressBar = (SeekBar) view.findViewById(R.id.seekBar);
volumeSeekBar = (SeekBar) view.findViewById(R.id.volumeSeekBar);
displayArt = (ImageView) view.findViewById(R.id.songImage);
playerName = (TextView) view.findViewById(R.id.songName);
totTime = (TextView) view.findViewById(R.id.endTime);
fromTime = (TextView) view.findViewById(R.id.startTime);
songRecyclerView = (RecyclerView) view.findViewById(R.id.songRecyclerView);
showList = (ImageButton) view.findViewById(R.id.showList);
stepForward = (ImageButton) view.findViewById(R.id.step_next);
stepBackward = (ImageButton) view.findViewById(R.id.step_prev);
shuffleAudio = (ImageButton) view.findViewById(R.id.shuffle);
repeatAudio = (ImageButton) view.findViewById(R.id.repeat);
playAudio = (ImageButton) view.findViewById(R.id.play_pause);
volumeAudio = (ImageButton) view.findViewById(R.id.speaker);
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
songRecyclerView.addItemDecoration(new MarginDecoration(getActivity()));
songRecyclerView.setHasFixedSize(true);
songRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
SongRecyclerAdapter songRecyclerAdapter = new SongRecyclerAdapter(songList,
getActivity()
);
if (songList.size() > 0) {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
} else {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
}
songRecyclerView.setAdapter(songRecyclerAdapter);
songRecyclerAdapter.setOnDataChangeListener(new onRefreshFavListener() {
#Override
public void onFavRefresh(int position) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), position);
getActivity().startService(playIntent);
updatePlayerView(position);
}
});
}
private void DataInitialization(final int position) {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
LogUtil.error("Update",position+"-->"+songList.get(position));
updatePlayerView(position);
showList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((int) showList.getTag() == R.drawable.ic_up_white_24dp) {
showList.setBackgroundResource(R.drawable.ic_down_white_24dp);
showList.setTag(R.drawable.ic_down_white_24dp);
songRecyclerView.setVisibility(View.VISIBLE);
} else {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
}
}
});
songProgressBar.setOnSeekBarChangeListener(this);
final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekBar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
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);
}
});
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
sendMessageToService(MusicService.MSG_CHECK_PLAYING_STATUS);
}
});
stepForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_NEXT);
}
});
stepBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_PREVIOUS);
}
});
shuffleAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_SHUFFLE);
}
});
repeatAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_REPEAT);
}
});
}
public void updatePlayerView(int songIndex) {
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
LogUtil.error("Song List",songIndex+"-->"+songList.get(songIndex).getPlayerTitle());
playerName.setText(songList.get(songIndex).getPlayerTitle());
totTime.setText(Utility.convertDuration(Long.parseLong(songList.get(songIndex).getPlayerDuration())));
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=?",
new String[]{String.valueOf(songList.get(songIndex).getPlayerAlbumId())},
null);
cursor.moveToFirst();
displayArt.setScaleType(ImageView.ScaleType.FIT_XY);
displayArt.setImageBitmap(Constants.getDefaultAlbumArt(getActivity(), songList.get(songIndex).getPlayerAlbumId()));
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
public void updateProgressBar() {
// mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
*/
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
sendMessageToService(MusicService.MSG_UPDATE_SEEKBAR);
// Displaying Total Duration time
totTime.setText("" + Utility.milliSecondsToTimer(duration));
// Displaying time completed playing
fromTime.setText("" + Utility.milliSecondsToTimer(currSongPosition));
// Updating progress bar
int progress = (int) (Utility.getProgressPercentage(currSongPosition, duration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
/**
* When user starts moving the progress handler
*/
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
// mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
*/
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// mHandler.removeCallbacks(mUpdateTimeTask);
int currentPosition = Utility.progressToTimer(seekBar.getProgress(), (int) duration);
sendMessageToServiceWithData(MusicService.MSG_SEEK, currentPosition);
// update timer progress again
updateProgressBar();
}
}
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 have a ProgressDialog, and I want to do something when the dialog dissappears (but I do not want put my action after the progressdialog.dismiss).
Is it possible to:
----> if No ---> Do something
Check if dialog is showing
----> if Yes
/|\ |
| \|/
--------------------- Wait
Don't think to difficult, I just want to perform an action, but only if there is no dialog, and if there is one, to perform the action when the dialog is done.
Thank you!
EDIT: My activity:
import verymuchimportshere..
public class ScroidWallpaperGallery extends Activity {
private WallpaperGalleryAdapter wallpaperGalleryAdapter;
private final WallpaperManager wallpaperManager;
private final ICommunicationDAO communicationDAO;
private final IFavouriteDAO favouriteDAO;
private final List<Integer> preloadedList;
private Wallpaper selectedWallpaper;
private static final int PICK_CONTACT = 0;
private static final int DIALOG_ABOUT = 0;
public ScroidWallpaperGallery() {
super();
if (!DependencyInjector.isInitialized()) {
DependencyInjector.init(this);
}
this.wallpaperManager = DependencyInjector.getInstance(WallpaperManager.class);
this.communicationDAO = DependencyInjector.getInstance(ICommunicationDAO.class);
this.favouriteDAO = DependencyInjector.getInstance(IFavouriteDAO.class);
this.preloadedList = new ArrayList<Integer>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.initGallery();
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(this.getString(R.string.loadingText));
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
else {
SharedPreferences settings = getSharedPreferences("firstrun", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
new AlertDialog.Builder(this).setTitle("How to").setMessage("Long press item to add/remove from favorites.").setNeutralButton("Ok", null).show();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
if (this.wallpaperGalleryAdapter != null) {
this.updateGalleryAdapter();
return;
}
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
new FillGalleryTask(progressDialog, this).start();
}
private void updateGalleryAdapter() {
this.updateGalleryAdapter(this.wallpaperManager.getWallpapers());
}
private synchronized void updateGalleryAdapter(Wallpaper[] wallpapers) {
this.wallpaperGalleryAdapter = new WallpaperGalleryAdapter(this, wallpapers, this.wallpaperManager);
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setAdapter(this.wallpaperGalleryAdapter);
}
private void initGallery() {
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Wallpaper wallpaper = (Wallpaper)parent.getItemAtPosition(position);
showPreviewActivity(wallpaper);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
selectedWallpaper = (Wallpaper)wallpaperGalleryAdapter.getItem(position);
new Thread(new Runnable() {
#Override
public void run() {
preloadThumbs(wallpaperGalleryAdapter.getWallpapers(), (position + 1), 3);
}
}).start();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedWallpaper = null;
}
});
this.registerForContextMenu(gallery);
}
private void showPreviewActivity(Wallpaper wallpaper) {
WallpaperPreviewActivity.showPreviewActivity(this, wallpaper);
}
private void preloadThumbs(Wallpaper[] wallpapers, int index, int maxCount) {
for (int i = index; (i < (index + maxCount)) && (i < wallpapers.length); i++) {
if (this.preloadedList.contains(i)) {
continue;
}
try {
this.wallpaperManager.getThumbImage(wallpapers[i]);
this.preloadedList.add(i);
}
catch (ClientProtocolException ex) {
// nothing to do - image will be loaded on select
}
catch (IOException ex) {
// nothing to do - image will be loaded on select
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (this.selectedWallpaper == null
|| !(v instanceof Gallery)) {
return;
}
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.gallery_context_menu, menu);
if (this.favouriteDAO.isFavourite(this.selectedWallpaper.getId())) {
menu.findItem(R.id.galleryRemoveFavouriteMenuItem).setVisible(true);
}
else {
menu.findItem(R.id.galleryAddFavouriteMenuItem).setVisible(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (this.selectedWallpaper == null) {
return false;
}
switch (item.getItemId()) {
case R.id.galleryAddFavouriteMenuItem:
this.favouriteDAO.add(this.selectedWallpaper.getId());
return true;
case R.id.galleryRemoveFavouriteMenuItem:
this.favouriteDAO.remove(this.selectedWallpaper.getId());
return true;
}
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aboutMenuItem:
this.showDialog(DIALOG_ABOUT);
return true;
case R.id.settingsMenuItem:
this.startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.recommendMenuItem:
this.recommendWallpaper();
return true;
case R.id.favouritesMenuItem:
FavouriteListActivity.showFavouriteListActivity(this);
return true;
case R.id.closeMenuItem:
this.finish();
return true;
}
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ABOUT:
return new AboutDialog(this);
default:
return null;
}
}
private void recommendWallpaper() {
if (this.selectedWallpaper == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
this.startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_CONTACT:
this.onPickContactActivityResult(resultCode, data);
break;
}
}
private void onPickContactActivityResult(int resultCode, Intent data) {
if (resultCode == 0) {
return;
}
Communication[] communications = this.communicationDAO.getCommunications(data.getData());
if (communications.length < 1) {
AlertDialogFactory.showInfoMessage(this, R.string.infoText, R.string.noCommunicationFoundInfoText);
return;
}
CommunicationChooseDialog dialog = new CommunicationChooseDialog(this, communications, new CommunicationChosenListener() {
#Override
public void onCommunicationChosen(Communication communication) {
handleOnCommunicationChosen(communication);
}
});
dialog.show();
}
private void handleOnCommunicationChosen(Communication communication) {
Wallpaper wallpaper = this.selectedWallpaper;
if (communication.getType().equals(Communication.Type.Email)) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { communication.getValue() });
intent.putExtra(Intent.EXTRA_SUBJECT, getBaseContext().getString(R.string.applicationName));
intent.putExtra(Intent.EXTRA_TEXT, String.format(getBaseContext().getString(R.string.recommendEmailPattern),
wallpaper.getWallpaperUrl()));
intent.setType("message/rfc822");
this.startActivity(intent);
}
else if (communication.getType().equals(Communication.Type.Mobile)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", communication.getValue());
intent.putExtra("sms_body", String.format(getBaseContext().getString(R.string.recommendSmsPattern),
wallpaper.getWallpaperUrl()));
intent.setType("vnd.android-dir/mms-sms");
this.startActivity(intent);
}
}
private class FillGalleryTask extends LongTimeRunningOperation<Wallpaper[]> {
private final Context context;
public FillGalleryTask(Dialog progressDialog, Context context) {
super(progressDialog);
this.context = context;
}
#Override
public void afterOperationSuccessfullyCompleted(Wallpaper[] result) {
updateGalleryAdapter(result);
}
#Override
public void handleUncaughtException(Throwable ex) {
if (ex instanceof WallpaperListReceivingException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
ex.getMessage(),
new ShutDownAlertDialogOnClickListener());
}
else if (ex instanceof IOException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
R.string.downloadException,
new ShutDownAlertDialogOnClickListener());
}
else {
throw new RuntimeException(ex);
}
}
#Override
public Wallpaper[] onRun() throws Exception {
// retrieving available wallpapers from server
wallpaperManager.loadAvailableWallpapers(getBaseContext());
Wallpaper[] wallpapers = wallpaperManager.getWallpapers();
// preloading first 3 thumbs
preloadThumbs(wallpapers, 0, 3);
return wallpapers;
}
}
private class ShutDownAlertDialogOnClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}
}
Try this,
private void doSomethingWhenProgressNotShown() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doSomethingWhenProgressNotShown();
}
}, 500);
}
//isnt running- do something here
}
I think you can use this code:
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
}
//isnt running
Or you can set listeners:
mProgressDialog.setOnCancelListener(listener);
mProgressDialog.setOnDismissListener(listener);