I am working on a game. Its all working well, the only thing I need is for my animation to pause when I press the home or on/off button on my phone. As far as I log correct, the pause script (as found here) works well. It keeps incrementing the time and applies it to the animation. However when I resume my game, the animations all resume on the left side of the screen instead of the position it originally was in when I paused it in. This is my stripped code. I really hope someone can help me.
public class GameView extends Activity{
ImageView peanut;
TranslateAnim movePeanut;
AnimationSet animSet = new AnimationSet(true);
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameviewlayout);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
movePeanut = new TranslateAnim(width,0,0,0);
movePeanut.setDuration(5000);
movePeanut.setRepeatCount(-1);
movePeanut.setRepeatMode(Animation.REVERSE);
animSet.addAnimation(movePeanut);
animSet.setFillAfter(true);
peanut = (ImageView) findViewById(R.id.imgview1);
peanut.startAnimation(animSet);
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
movePeanut.resume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
movePeanut.pause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
public void finish (){
Intent intent = new Intent (GameView.this, MainActivity.class);
startActivity(intent);
}
public class TranslateAnim extends TranslateAnimation{
public TranslateAnim(float fromXDelta, float toXDelta, float fromYDelta,
float toYDelta) {
super(fromXDelta, toXDelta, fromYDelta, toYDelta);
// TODO Auto-generated constructor stub
}
private long mElapsedAtPause=0;
private boolean mPaused=false;
#Override
public boolean getTransformation(long currentTime, Transformation outTransformation) {
if(mPaused && mElapsedAtPause==0) {
mElapsedAtPause=currentTime-getStartTime();
}
if(mPaused)
setStartTime(currentTime-mElapsedAtPause);
boolean returnValue = super.getTransformation(currentTime, outTransformation);
return returnValue;
}
public void pause() {
mElapsedAtPause=0;
mPaused=true;
}
public void resume() {
mPaused=false;
}
}
}
Related
Here is my MainActivity Where I want to send the chosen GIF To the Wallpaper Service class using Uri :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, 0);
}
});
Button btn1;
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0){
Uri uri = data.getData();
Intent i = new Intent(MainActivity.this,one.class);
i.putExtra("ayush",uri.toString());
startActivity(i);
////////////////
}
}
}
And here is my Second Activity where I want to Receive the Gif data and put it on the movie decode stream. Please Suggest me some ways. Please suggest me some ways to do it.
public void onDestroy() {
super.onDestroy();
}
#Override
public Engine onCreateEngine() {
// TODO Auto-generated method stub
try {
//Movie movie=Movie.decodeStream(getResources().getMovie(R.drawable.endless_staircase));
Movie movie = getResources().getMovie(Intent.getIntent(Uri.parse(//I want to use the get intent extra here )));
return new GIFWallpaperEngine(movie);
} catch (Exception e) {
// TODO: handle exception
Log.d("GIF", "Could Not load Asset");
return null;
}
}
private class GIFWallpaperEngine extends Engine {
private final int frameDuration = 20;
private SurfaceHolder holder;
private Movie movie;
private boolean visible;
private Handler handler;
int mWhen;
long mStart;
float mScaleX, mScaleY;
public GIFWallpaperEngine(Movie movie) {
this.movie = movie;
handler = new Handler();
mWhen = -1;
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
// TODO Auto-generated method stub
super.onCreate(surfaceHolder);//tick();
this.holder = surfaceHolder;
}
private void draw() {
tick();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
canvas.save();
canvas.scale(mScaleX, mScaleY);
if (canvas != null) {
movie.draw(canvas, 0, 0);
}
canvas.restore();
// holder.unlockCanvasAndPost(canvas);
//movie.setTime(((int)(SystemClock.uptimeMillis()-SystemClock.uptimeMillis())%(movie.duration())));
//movie.setTime((int)((System.currentTimeMillis()%movie.duration())));
movie.setTime(mWhen);
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawGIF);
if (visible) handler.postDelayed(drawGIF, 1000L / 25L);
}
void tick() {
int dur = movie.duration();
if (mWhen == -1L) {
mWhen = 0;
mStart = SystemClock.uptimeMillis();
} else {
long mDiff = SystemClock.uptimeMillis() - mStart;
mWhen = (int) (mDiff % dur);
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
super.onSurfaceChanged(holder, format, width, height);
mScaleX = width / (1f * movie.width());
mScaleY = height / (1f * movie.height());
draw();
}
private Runnable drawGIF = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
draw();
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
handler.removeCallbacks(drawGIF);
}
public void onVisibilityChanged(boolean visible) {
// TODO Auto-generated method stub
//super.onVisibilityChanged(visible);
this.visible = visible;
if (visible) {
handler.post(drawGIF);
} else {
handler.removeCallbacks(drawGIF);
}
}
}
}
Please Suggest me Some Ways to do it.
This is my library project .
public class myads extends Activity implements AdListener {
public static int num;
public static InterstitialAd interstitialAds;
static AdRequest adr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interstitialAds = new InterstitialAd(this, "ca-app-pub-*************/**********");
interstitialAds.setAdListener(this);
adr=new AdRequest();
interstitialAds.loadAd(adr);
interstitialAds.show();
}
public static void intenr(Context c){
interstitialAds.loadAd(adr);
interstitialAds.show();
Toast.makeText(c, "Sample", Toast.LENGTH_LONG).show();
num=3;
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad arg0) {
// TODO Auto-generated method stub
interstitialAds.show();
}
}
It has unfortunately stopped Error and not working when I call it(this library project) from another project.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myads.intenr(this);
}
If I remove int.load and int.show from library project , It is working and toasting , got passed int. I also added internet permission and google activity tag properly. Thank you for interesting my problem.
It may be useful-
private InterstitialAd interstitial;
private AdRequest adRequestFullScreen;
private LocalBroadcastManager localBroadcastManager;
private NotificationReciever notificationReciever;
private Dialog answerDialog, chatReqDialog, questionDialog;
private boolean isShowAd = true, isRecieverRegistered = false,
isNetDialogShowing = false, isGpsDialogShowing = false;
private String notificationData = "", notificationType;
// Ad
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_fullscreen_ad));
// live
// adRequestFullScreen = new AdRequest.Builder().build();
// test
adRequestFullScreen = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("").build();
loadAd();
public void loadAd() {
interstitial.loadAd(adRequestFullScreen);
}
public void showAd() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public void onDestroy() {
if (isRecieverRegistered) {
unregisterReceiver(internetConnectionReciever);
unregisterReceiver(GpsChangeReceiver);
}
AndyUtils.removeSimpleProgressDialog();
if (isShowAd) {
showAd();
}
Mint.closeSession(getApplicationContext());
stopLocationUpdate();
super.onDestroy();
}
I want to allow the user change the theme from the entire app by clicking a button,
So I want to know if there is a way to change the app theme within java code.
You can use the setTheme() method on a Context.
Be sure to pay attention to the note in the documentation- you need to call setTheme() before you instantiate any Views.
If you change themes while your application is open, you will need to recreate your Activity for the changes to show.
public class ThemeSwitcher extends Activity implements OnClickListener {
private boolean isThemeSwitch = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (isDefault() == false) {// Default theme defined in Style file.
setTheme(android.R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.theme_switcher);
findViewById(R.id.switchTheme).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.switchTheme) {
switchTheme();
isThemeSwitch = true;
finish();
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isThemeSwitch) {
Intent intent = new Intent(this, ThemeSwitcher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
private SharedPreferences getPreference() {
return getSharedPreferences("theme", 0);
}
private void switchTheme() {
if (isDefault()) {
getPreference().edit().putBoolean("theme", false).commit();
}
else {
getPreference().edit().putBoolean("theme", true).commit();
}
}
private boolean isDefault() {
boolean isDef = true;
isDef = getPreference().getBoolean("theme", false);
return isDef;
}
}
I just have added +1 google to my button but it is always gray after initialize() and cannot do anything with that:
My code looks like this:
public class Stars extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private PlusClient mPlusClient;
PlusOneButton mPlusOneButton;
private static final int PLUS_ONE_REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stars);
// g+1------------------------------------------------------
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities(
"http://schemas.google.com/AddActivity",
"http://schemas.google.com/BuyActivity").build();
mPlusOneButton = (PlusOneButton) findViewById(R.id.plus_one_button);
// ---------------------------------------------------------
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
protected void onResume() {
mPlusOneButton.initialize(mPlusClient,
"https://developers.google.com/+", PLUS_ONE_REQUEST_CODE);
super.onResume();
}
public void onConnectionFailed(ConnectionResult status) {
// Nothing to do.
}
public void onDisconnected() {
// Nothing to do.
}
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
}
How to repair that and where are info in my code about that what I registered in google api console?
Try calling .clearScopes() on the builder, rather than setting it up for Sign-In as you have it at the moment. You don't need to connect() or disconnect() it in that case either.
mPlusClient = new PlusClient(this, this, this)
.clearScopes()
.build();
Currently its associated with a PlusClient setup to be used for sign-in, but the user hasn't signed in, hence the greying out.
i uses seekBar to pass value increase/decrease by user... i put the initial value of barValue=50. when user drag seekbar lesser than current value.. the a,b decreases by 0.00001.
Problem i face. its only do the IF condition onced. after seekBar updated.. no changes on a and b.
public static double a,b;
public static int barValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
a= location.getLatitude();
b= location.getLongitude();
bar = (SeekBar)findViewById(R.id.seekBar1); // make seekbar object
bar.setOnSeekBarChangeListener(this); // set seekbar listener.
barValue = 50;
bar.setProgress(barValue);
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (progress > barValue)
{
a += seekBar.getProgress()/10000;
b += seekBar.getProgress()/10000;
getSensorManager().enableMockLocation(a, b);
}
else if(progress < barValue)
{
a -= seekBar.getProgress()/10000;
b -= seekBar.getProgress()/10000;
getSensorManager().enableMockLocation(a, b);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekBar.setSecondaryProgress(seekBar.getProgress());
barValue = seekBar.getProgress();
}