How to make the text fade for only 20 seconds and then disappear when you click the button
This is the code
public void scoreOpenB(View v) {
findViewById(R.id.main_mess).setVisibility(View.GONE);
((TextView)findViewById(R.id.main_mess)).setText(R.string.btn_closs);
findViewById(R.id.main_mess).setVisibility(View.VISIBLE );
}
}
You can use AsyncTask to update UI after delay. Try this ;)
public void scoreOpenB(View v) {
View updateMe = findViewById(R.id.main_mess);
updateMe.setVisibility(View.GONE);
new UpdateUI().execute(updateMe);
}
}
private class updateUI extends AsyncTask<View, Integer, Long> {
View toUpdate;
protected void doInBackground(View view) {
toUpdate = view;
try {
Thread.sleep(20000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
(toUpdate(TextView)).setText(R.string.btn_closs);
toUpdate.setVisibility(View.VISIBLE);
}
}
Related
i'm trying to play stream radio using Mediaplayer with MP1 as variable of Mediaplayer i want to play it in all Fragments app,expect one activity (ActivityOne) which is contains another Mediaplayer MP2 to play,so i want to stop MP1 when i'm in (ActivityOne) activity, and play MP2 , and when i return from (ActivityOne) i want to resume MP1, my big problem is the (ActivityOne) called when i click button which is exist in fragment
my code below works only in one direction :
when i return from (ActivityOne) activity, the music stops.
structure of the app : MainAcitivty > Fragment > ActivityOne
MainActivity.java
MediaPlayer MP1;
boolean prepared = false;
boolean started = false;
PlayerTask playerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(stream);
/**/
MusicButton = findViewById(R.id.toggleButton);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (started && MusicButton.isChecked()) {
started = false;
MP1.pause();
MusicButton.setChecked(true);
} else {
started = true;
MP1.start();
MusicButton.setChecked(false);
}
}
});
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar loadingRL = findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP1.setAudioAttributes(attribs);
} else {
MP1.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
MP1.setDataSource(strings[0]);
MP1.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP1) {
MP1.start();
}
});
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
loadingRL.setVisibility(View.VISIBLE);
}
ActivityOne.java
MediaPlayer MP2;
boolean prepared = false;
boolean started = false;
ToggleButton music;
PlayerTask playerTask = null;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
coordinatorLayout = findViewById(R.id.coord);
MP2 = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP2.setAudioAttributes(attribs);
} else {
MP2.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
#Override
protected Boolean doInBackground(String... strings) {
if (!isCancelled()) {
try {
MP2.setDataSource(strings[0]);
MP2.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP2) {
MP2.start();
}
});
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
all.setVisibility(View.VISIBLE);
}
#Override
protected void onCancelled(Boolean aBoolean) {
if (isCancelled() && MP2.isPlaying()) {
MP2.stop();
}
}
}
#Override
public void onBackPressed() {
if (playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (MP2.isPlaying()) {
MP2.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
playerTask.cancel(true);
}
super.onBackPressed();
}
i spent 2 days to resolve this problem without any result ,please someone help me i will be thankful to him
You could solve this by using Otto library. First create a new Java class but choose enum instead and inside enum you can add: PLAY and PAUSE for example:
public enum PlaybackEvent {
PLAY, PAUSE
}
Then if you are not using custom Application class create one and extend Application and override inside onCreate method. Inside your app gradle add compile 'com.squareup:otto:1.3.8' then create an instance of Bus inside Application class and register. For example this would look like this:
public class MApplication extends Application {
public static Bus sBus = new Bus(ThreadEnforcer.MAIN);
#Override
public void onCreate() {
super.onCreate();
sBus.register(this);
}
Don't forget to replace in manifest default application class with your new one
<application
android:name="com.packagename.MApplication"
After that in your MainActivity class override and register/unregister your event bus in onResume and in onPause.
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
}
catch(Exception e){
e.printStackTrace();
}
}
After that in MainActivity create a public void method passing as parameter PlayBackEvent and Subscribe so you can listen a message which will be send from your fragment class. For example:
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PLAY:
if(MP1.isPlaying())
MP1.pause();
break;
case PAUSE:
if(!MP1.isPlaying())
MP1.play();
break;
}
}
And last thing you have to do is to send the message from your fragment when starting second activity and that will go:
MApplication.sBus.post(PlaybackEvent.PAUSE);
and of course you can also send a message to play again MP1 from second activity overriding onBackPressed putting inside line of code:
MApplication.sBus.post(PlaybackEvent.PLAY);
Hope this will help you to resolve the problem.
Have you tried using startActivityForResult()?
So im trying to make something like this https://play.google.com/store/apps/details?id=pt.bbarao.nightmode . I added transparrent background at first before layout and when the imagebutton is clicked, then the blackish screen filter is applied, but for some reason, the button is not working and i cant even move the seekbar around. Help is much appriciated, thank you! Heres the code:
public class Nightmode extends AppCompatActivity {
private boolean nightmodeOnOff;
public ImageButton modeOnOffButton;
private int brightness;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
setContentView(R.layout.activity_nightmode);
modeOnOffButton = (ImageButton) findViewById(R.id.nightmodeOnOffButton);
nightmodeOnOff = false;
int prog;
//Seekbar
SeekBar skbar = (SeekBar) findViewById(R.id.nightModeBar);
skbar.setMax(255);
skbar.setKeyProgressIncrement(127);
try {
brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
} catch (Exception e) {
e.printStackTrace();
}
skbar.setProgress(brightness);
skbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
if (progress <= 25) {
brightness = 25;
} else {
brightness = progress;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
WindowManager.LayoutParams lpp = getWindow().getAttributes();
lpp.screenBrightness = brightness/(float)255;
getWindow().setAttributes(lpp);
}
});
}
public void nightmodeButtonClicked(View view) {
try {
if (nightmodeOnOff) {
nightmodeOnOff = false;
turnNightOff();
} else {
nightmodeOnOff = true;
turnNightOn();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOn() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonbutton);
findViewById(R.id.activity_nightmode).setBackgroundColor(0x66000000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOff() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonoffbutton);
findViewById(R.id.activity_nightmode).setBackgroundColor(33000000);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
turnNightOff();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
turnNightOff();
}
#Override
protected void onDestroy() {
super.onDestroy();
turnNightOff();
}
#Override
protected void onPause() {
super.onPause();
turnNightOn();
}
}
I successfully implemented AdMob interstitial ads into my application but the only problem is that they are not clickable.
Here is my AdMob.java class:
import android.app.Activity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class Admob extends AdListener{
private Activity ctx;
//Admob
private InterstitialAd interstitial;
private AdRequest adRequest;
private String unitId;
public static boolean fromAdmob = false;
public Admob(Activity ctx, String unitId)
{
this.ctx = ctx;
this.unitId = unitId;
try{
this.interstitial = new InterstitialAd(this.ctx);
interstitial.setAdUnitId(unitId);
interstitial.setAdListener(this);
adRequest = new AdRequest.Builder().build();
}
catch (Exception e){
e.printStackTrace();
}
}
public void loadAd()
{
try{
interstitial.loadAd(adRequest);
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onAdLoaded() {
try{
fromAdmob = true;
interstitial.show();
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onAdFailedToLoad(int errorCode)
{
}
#Override
public void onAdClosed() {
fromAdmob = false;
}
}
And the MainPageActivity.java file:
public class MainPageActivity extends Activity implements IGameListener, IEventDelegate{
//Tags
private static final String TAG = "bubblesMainPage";
//Context
public static Activity instance;
//Media
private MediaPlayer mp;
//Ads
private Admob admob;
//TapSDK
private Tap tap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_activity);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
tr
Tap.establish(this);
tap = new Tap(this, "xxxx");
}
catch (Exception e){
e.printStackTrace();
}
//Admob
this.admob = new Admob(this, "ADMOB_ID");
//Context
instance = this;
//Media
mp = MediaPlayer.create(getApplicationContext(), R.raw.background_music);
mp.setLooping(true);
//Set activity properties
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} catch (Exception e) {
e.printStackTrace();
}
//Intents & Listeners
final Intent gamePlayActivity = new Intent(this, BubbleShooterActivity.class);
BubbleShooterActivity.listener = this;
//Animations
Animation scaleUpAnim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale_up);
findViewById(R.id.play_button).startAnimation(scaleUpAnim);
//UI Events
findViewById(R.id.play_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
try {
startActivity(gamePlayActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
findViewById(R.id.more_games_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tap.showMoreGamesWithViewControllerAndAppID((IEventDelegate)instance);
}
});
}
/*
Game methods - start
*/
#Override
public void onGameStart() {
Log.i(TAG, "onGameStart");
}
#Override
public void onLevelFailed() {
//Level failed window
try{
Intent i = new Intent(this, LostActivity.class);
startActivity(i);
}
catch (Exception e){
e.printStackTrace();
}
Log.i(TAG, "onLevelFailed");
}
#Override
public void onLevelUp() {
Log.i(TAG, "onLevelUp");
if(admob != null){
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
admob.loadAd();
}
catch (Exception e){
e.printStackTrace();
}
try{
Intent i = new Intent(instance, WonActivity.class);
startActivity(i);
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
}
#Override
public void onGameEnd() {
Log.i(TAG, "onGameEnd");
}
/*
TapSDK methods - start
*/
#Override
public void viewDidAppear() {
Log.i(TAG, "TapSDK: viewDidAppear");
}
#Override
public void viewDidDisappear() {
Log.i(TAG, "TapSDK: viewDidDisappear");
}
#Override
public void viewConnectFail(String s) {
Log.i(TAG, "TapSDK: viewConnectFail " + s);
}
#Override
public void conversion() {
Log.i(TAG, "TapSDK: conversion");
}
#Override
public void onOfferComplete(int score) {
Log.i(TAG, "TapSDK: onOfferComplete " + score);
}
/*
Activity methods start
*/
#Override
public void onBackPressed() {
Log.i(TAG, "onBackPressed");
try{
Intent exitScreen = new Intent(this, ExitActivity.class);
startActivity(exitScreen);
}
catch (Exception e){
e.printStackTrace();
Log.e(TAG, "onBackPressed: " + e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
// Monitor launch times and interval from installation
RateThisApp.onStart(this);
// If the criteria is satisfied, "Rate this app" dialog will be shown
RateThisApp.showRateDialogIfNeeded(this);
}
#Override
protected void onResume()
{
super.onResume();
if(tap != null)
tap.onResume();
mp.seekTo(0);
mp.start();
}
#Override
protected void onPause()
{
if(tap != null)
tap.onPause();
mp.pause();
super.onPause();
}
#Override
protected void onDestroy()
{
mp.stop();
mp = null;
if(tap != null)
tap.onDestroy();
super.onDestroy();
}
}
I couldn't figure out how to show the interstitial ad when the user levels up and presses the play button (which will lead him to the next level). The interstitial ad show up when he presses the home button which will take him to the MainActivity screen.
Can someone help me to make the ads clickable? Also, any suggestions on how to add the interstitial ad after each completed level? When someone has finished a level and presses the play button, an interstitial ad should appear and when that is closed he should be able to play the next level.
I really appreciate your help!
A number of issues:
Don't call interstitial.show() from onAdLoaded. Call show() when the user presses the play button for your next level (but only if an ad is available).
Get rid of public static Activity instance; Never hold a static reference to an Activity. You will just leak context everywhere.
Instead of calling admob.loadAd() from onLevelUp() call it as soon as you create your Activity (it takes times to load an ad from the network). NB you don't need to call it from runOnUIThread()
Call admob.loadAd() again after each time you show the ad to the user.
I have this code in my Android application:
private void showMyViews() {
mAnimation.cancel();
mAnimation.reset();
mAnimateionView.clearAnimation();
mAnimationView.setVisibility(View.GONE);
mOtherViewToHide.setVisibility(View.GONE);
mFirstViewToShow.setVisibility(View.VISIBLE);
mSecondViewToShow.setVisibility(View.VISIBLE);
}
But sometimes mSecondViewToShow appears a little bit before mFirstViewToShow. How could I easily force these Views to appear at the same time?
Some of the code is:
public class mFragment extends Fragment implements OnClickListener, com.squareup.picasso.Callback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mFragment, null);
mFirstViewToShow = (RelativeLayout) view
.findViewById(R.id.mFirstViewToShow);
mSecondViewToShow = (RelativeLayout) view
.findViewById(R.id.mSecondViewToShow);
...
...
...
if (isConnected()) {
animateMagnifier();
updateUserLocation();
} else {
}
}
private void animateMagnifier() {
Thread mThread = new Thread(new Runnable() {
#Override
public void run() {
AppLog.Log(TAG, "ver si la lupa sirve");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mAnimationView.setVisibility(View.VISIBLE);
animeMagnifier = AnimationUtils
.loadAnimation(getActivity(),
R.anim.translate_center_amim);
mAnimationView.startAnimation(animeMagnifier);
// Code use to repeat the animation
// See
// http://stackoverflow.com/questions/4480652/android-animation-does-not-repeat
animeMagnifier
.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(
Animation animation) {
}
#Override
public void onAnimationRepeat(
Animation animation) {
}
#Override
public void onAnimationEnd(
Animation animation) {
animeMagnifier = AnimationUtils
.loadAnimation(
getActivity(),
R.anim.translate_center_amim);
animeMagnifier
.setAnimationListener(this);
mAnimationView
.startAnimation(animeMagnifier);
}
});
}
});
}
}
});
mThread.start();
try {
mThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void updateUserLocation() {
...
...
...
sendDataToServer();
}
private void sendDataToServer() {
...
...
...
findPerson();
}
private void findPerson() {
new BackGroundTaskForFindPerson().execute();
}
private class BackGroundTaskForFindMatch extends
AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
findPeopleResponse = mServices.makeHttpRequest(
Constant.find_people, Constant.methodeName,
findPeopleValuePairList);
Gson gson = new Gson();
...
...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
if (success) {
if (mFindPeople.getErrNum() == 2) {
// no one found
mFirstViewToShow.setVisibility(View.GONE);
mSecondViewToShow.setVisibility(View.GONE);
messageTextView.setText(R.string.no_one_near);
} else if (mFindPeople.getErrNum == 3) {
...
} else {
....
}
} else {
messageTextView.setText(R.string.no_one_new);
}
} catch (Exception e) {
....
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Set them to INVISIBLE instead of GONE that way they will be attached to your layout but hidden.
At the moment they must be added to your view hierarchy before they are revealed, that's probably what's causing your delay.
Hello i have make one radio app in that streaming is done from web
my source code is
when user click on button following code will be executed
if (!NotifyService.iSserviceRunning) {
new PlayRadio().execute("");
}
// AYSNC class for start Service and create progressbar
class PlayRadio extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return "";
}
#Override
protected void onPostExecute(String result) {
try {
startService(new Intent(RadioActivity.this, NotifyService.class));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = ProgressDialog.show(RadioActivity.this, "Tuning...", "Please Wait...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Now service class will be
public class NotifyService extends Service {
private static String RADIO_STATION_URL;
public static MediaPlayer player;
public static boolean iSserviceRunning = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
RADIO_STATION_URL = getResources().getString(R.string.streamurl);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
initializeMediaPlayer();
startPlaying();
iSserviceRunning = true;
}
#Override
public void onDestroy() {
super.onDestroy();
nm.cancel(R.string.service_started);
stopPlaying();
initializeMediaPlayer();
iSserviceRunning = false;
}
private void startPlaying() {
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
new PrepareTask().execute();
}
private void stopPlaying() {
if (player.isPlaying()) {
player.pause();
player.release();
}
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class PrepareTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(Integer result) {
if(RadioActivity.PD!=null){
if(RadioActivity.PD.isShowing()){
RadioActivity.PD.dismiss();
}
}
}
#Override
protected Integer doInBackground(Integer... arg0) {
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
is there any wrong i am doing becuase my client said that application is taking tooo much time for loading.. he told me that he has many such application which is loading fastly then my app
can any body suggest me is any wrong i have done in my code so it's taking much time?