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.
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()?
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);
}
}
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 am trying to receive and send messages using Smack API but not been able to do it in a separate class due to some threads issue may be. But when now i ported all the code in MainActivity i wont be able to make a connection with server.Below is my MainActivity.class.
public class chatActivity extends AppCompatActivity {
private static final String DOMAIN = "192.168.0.109";
private static final String HOST = "192.168.0.109";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
ChatManager chatManager;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context context;
private MultiUserChat multiUserChat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
init("user123","user123");
}
});
t.start();
}
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.context = context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
System.out.println("Hellooooooooo11111");
login();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// // TODO Auto-generated method stub
//new MainActivity().updateText(context);
}
});
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
// joinChatRoom();
// sendMsg();
chat_created = false;
//sendMessage("body","jid");
//sendMsg();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
// sendMsg();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
public void login() {
try {
connection.login(userName, passWord);
// sendMsg();
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
}
My Question is how can I use smack API, I am not getting it at all that how to handle this network operations in main class.
I did try to run it in Asynch too.
Okay I found the solution i forgot to add the following method in my main class.
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
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?