Need help with really small app - Java for Android App Development

I have the Android SDK and Eclipse downloaded and I can get it work properly. However, there doesn't seem to be any commands anywhere, like, am I supposed to know all of the JAVA commands by memory to use this tool???
I only want a very simple app that does this:
- When screen is off, turn WIFI off
- When screen is on, Turn WIFI on
That's it. I don't need any fancy menu or anything, it can run in the background for what I care, it's just that Stamina mode doesn't work with these roms and bootloaders and whatever, so I need this app to save me some power.
I reckon it'd be pretty easy for anyone who knows java, so maybe I could get someone to post a code for me?
Thanks in advance

You don't need to know everything by memory but you do need to know the basics.
For example, you need to know the difference between an Activity and a Service and determine which one you would want to use.
For your app, you would need a Service and a BroadcastReceiver.
Your BroadcastReceiver would capture the intents of the screen turning on and off:
http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
You would then call your service from your broadcastreceiver to do the work of turning off your wifi:
http://stackoverflow.com/questions/8863509/how-to-programmatically-turn-off-wifi-on-android-device
Be sure to add the proper permissions in your manifest file that allows you to read and change wifi state.

Ok, so now I know how the code should be, but there's just one more thing.
How in the world can anyone program a user interface with text only??? This program is certainly not easy to use, I don't even know where to put the code with all of those different folders.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Do I even need all of those commands/folders? I tried deleting all that stuff and putting in the code but I got lots of errors obviously.
So if you would please tell me:
- Where to put the code
- How to make an interface like this one with radio buttons or something, a switch might be easier
I don't want anything fancy, just a super basic app
I suppose the code would look like this:
Code:
package selecm.wwf; //your package name
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
WifiManager wm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
public class ScreenReceiver extends BroadcastReceiver {
// THANKS JASON
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wm.setWifiEnabled(false)
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wm.setWifiEnabled(true)
wasScreenOn = true;
}
}
}
And then make these in the manifest.xml file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Am I right?

Your user interface is located in the "res/layout" folder. It is most likely called activity_main.xml.
Also, I would recommend keeping your BroadcastReceiver separate from your activity. It makes things cleaner to debug and easier to build on.

After doing some playing and spending more time on this then I planned, using a service does not work reliable with the broadcast receiver. I am not sure how logical google was with the thought process of requiring some intents that can only be registered in code. With that limitation, your activity would need to be running to receive the intent from the screen being turned off or on.

Related

[Help] How launch an Activity or dialog from background

Hello, I'm starting with Android and I'm trying to program a timer which launch an application or an AlertDialog, even if the application is in background. I know it is very invasive for the user but is necesary cause it show an important alarm that must be handled instantly.
Thats the code I used, but only works if MainActivity is the current activity =(
Code:
Timer time=new Timer();
teme.schedule(new TimerTask() {
public void run() {
Intent dialog = new Intent(MainActivity.this., Alarm.class);
dialog.setFlags(Intent.FLAG_FROM_BACKGROUND);
startActivity(dialog);
}
}, delay);
Can someone help me please?
Going to have to run it as a Service
You have MainActivity.this is why MainActivity has to be running.
When you start an activity, update the reference, and then call:
[whateverActivityIsRunning].this
Aditionally, you may try launching another thread under your process, this however will not work if your app was force closed by system or user.
Code:
private void dodelayed(int delay, Intent someintent){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override public void run(){
//If that dialog is custom class then someintent.setclass(this,classname.class);
startActivity(someintent);
}
},delay);
}
Thanks guys, starting the activity from a service works nice for my target.
Now i'm trying a new thing:
I start the service in my app, then i open another app, Angry Birds for example xD. The startActivity tiggers and my app comes to front with a Activity that shows a message and a button.
I want a button click hide the Activity and move Andry Birds back to front.
How could I do it? Thanks!
finish();
With finish() I go to the last Activity of my app before it went to background =(
Do you know what that last activity is? You could set a variable in it to call from your other activity telling it to also finish.
You could also try something like this:
http://developer.android.com/guide/topics/manifest/activity-element.html#reparent
The "Love & Hate" of Android OS.
finish(); will only pop the last Activity on it's OWN thread and not Angry Birds as it is running on it's own thread (well VM actually).
The OS was designed this way; they didn't want any old application dumping something else that was running...makes sense to me.
I don't know what you're doing, but it sounds like it's working OK to me. Say I'm in the middle of creating a text, your timer goes off (for whatever reason I don't know), I respond to it and go about my texting. I would be more than upset if your timed event blew me out of my texting!!! Your app would be in the trash bin pretty quickly.
Might need a little more info on what you're trying to do...
My app wont be comercial. It reads from a bluetooth device checking for alarms, if any, gives the user some time for cancell it, else its sent to the main server.
I want do something like whatsapp application. where, if you activate the emergent notifications. when you receive an message a alertdialog is shown. But you can cancell it and continue with your stuff
See that screenshot:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
for such notifications, first create an activity with normal textview and buttons and remember to use layout_width and height as wrap_content, then in your application manifest use the following
Code:
<activity android:name="activity"
android:label="Title"
android:theme="@android:style/Theme.Dialog">
now when you call this activity from a service, a dialog box such as in the picture above depending on your layout xml will be shown. and when you call finish() through a button on this dialog, the focus will be passed to angry birds since this activity was launched from a parent with no UI.
Exactly what i was looking for. Thanks!
dont waste posts, hit the thanks button!
Sorry, you are limited to five thanks per day
have to wait =)
Dont worry I gave him one for ya

[Q]Showing preference screen activity

Hey guys,
I'm still learning to make android apps and now I'm writing small apps...Today I wrote a small app to test the scrolable tabs+ swipe created with blank activity.I need to show show contents of a PreferenceScreen xml.So I created a xml and added a new class:
Code:
public class About extends PreferenceActivity{
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.info);
addPreferencesFromResource(R.layout.info);
}
}
And then found that the below code is responsible for the screens and so done this:
Code:
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.example.testy","com.example.testy.About"));
startActivity(intent);
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Now the thing is that,I need the app to show the contents of xml directly on section1 instead of opening an activity above.Also noted that,when I go to section2,The activity is opened once and when back to section1,twice.
I need to show completely different contents on section1 and section2 also that the contents should be directly on sections instead of opening a new activity over the main one.Sorry for confusing you.All the xml I use are in preferences.Thank you
Regards,
Vijai
vijai2011 said:
Hey guys,
I'm still learning to make android apps and now I'm writing small apps...Today I wrote a small app to test the scrolable tabs+ swipe created with blank activity.I need to show show contents of a PreferenceScreen xml.So I created a xml and added a new class:
Code:
public class About extends PreferenceActivity{
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.info);
addPreferencesFromResource(R.layout.info);
}
}
And then found that the below code is responsible for the screens and so done this:
Code:
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.example.testy","com.example.testy.About"));
startActivity(intent);
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Now the thing is that,I need the app to show the contents of xml directly on section1 instead of opening an activity above.Also noted that,when I go to section2,The activity is opened once and when back to section1,twice.
I need to show completely different contents on section1 and section2 also that the contents should be directly on sections instead of opening a new activity over the main one.Sorry for confusing you.All the xml I use are in preferences.Thank you
Regards,
Vijai
Click to expand...
Click to collapse
Change your activity into a FragmentActivity. Then you will be able to add a PreferenceFragment. However, you will need to show the content of your screen in a Fragment instead of the "normal" way of doing it in the onCreate method. Add a Fragment there and if you want to show the preferences, add a new one on the top. It will not open a new Activity but just a new Fragment in the Activity.
nikwen said:
Change your activity into a FragmentActivity. Then you will be able to add a PreferenceFragment. However, you will need to show the content of your screen in a Fragment instead of the "normal" way of doing it in the onCreate method. Add a Fragment there and if you want to show the preferences, add a new one on the top. It will not open a new Activity but just a new Fragment in the Activity.
Click to expand...
Click to collapse
Wait...I dont understand this:
However, you will need to show the content of your screen in a Fragment instead of the "normal" way of doing it in the onCreate method. Add a Fragment there and if you want to show the preferences, add a new one on the top. It will not open a new Activity but just a new Fragment in the Activity.
Click to expand...
Click to collapse
.However I changed my activity to fragment activity from the link you gave
vijai2011 said:
Wait...I dont understand this:.However I changed my activity to fragment activity from the link you gave
Click to expand...
Click to collapse
Yes, change it to a FragmentActivity. It will act like the container of your Fragments. Then you will set the content by adding new Fragments on the top of each other.
Check this: http://developer.android.com/guide/components/fragments.html
Here´s a full example showing how to implement Tabbed Preferences Screen (with no swipe for now). I hope it helps you!!
Entire ICS source code attached!
Screenshots:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}

[Tutorial] Use OkHttp to make Network Requests on Android

Hello,
I create that thread to present you a tutorial learning you to use OkHttp to make Network Requests on Android. Note that you can enjoy this tutorial in video on Youtube :
Created by Square, OkHttp is an open source project designed to be an efficient HTTP and HTTP/2 client. It lets you to make fast requests and save bandwith. It offers some great features out of the box like to share a socket for all HTTP/2 requests to the same host, a connection pooling mechanism when HTTP/2 is not available, transparent GZIP feature to reduce download sizes and a caching mechanism for responses. Besides, OkHttp has a great mechanism to manage common connection problems. And now, it supports also WebSocket.
OkHttp offers a request / response API that makes developers life easier. It supports synchronous and asynchronous calls. Even better, OkHttp is also available for Java projects with Java 7 as requirement.
First you need to add the following dependency to your build.gradle file :
Code:
compile 'com.squareup.okhttp3:okhttp:3.5.0'
For our example, we are going to consume a simple JSON Rest Web Service from the SSaurel’s Website : http://www.ssaurel.com/tmp/todos . So, we are going to create a simple layout with a Button to start the network request and a TextView to display the date got from the Web Service :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.okhttptut.MainActivity">
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:text="Get WebService"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result ..."
android:layout_centerHorizontal="true"
android:textSize="17sp"
android:layout_below="@id/getBtn"
android:layout_marginTop="20dp"/>
</RelativeLayout>
Now, it’s time to write the Java code to make the Network Request by using the OkHttp API. First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class. Next step is to pass the request in parameter of the newcall method of the OkHttpClient instance created. OkHttp supports asynchronous and synchronous calls. Here, we are going to use asynchronous request so we call the enqueue method. It takes a Callback object in parameter which has two methods : onFailure and onResponse. Note that these methods are executed in a separate thread. So, if you want to update your User Interface with data got from the Network inside this method, you must embed this in a runOnUiThread call to ensure the update will be made on the UI Thread.
The Java code to consume the JSON Web Service with OkHttp will have the following form :
Code:
package com.ssaurel.okhttptut;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getWebservice();
}
});
client = new OkHttpClient();
}
private void getWebservice() {
final Request request = new Request.Builder().url("http://www.ssaurel.com/tmp/todos").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText("Failure !");
}
});
}
@Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error during get body");
}
}
});
}
});
}
}
Now, you can try your application and you should obtain the following result by clicking on the Get WebService button :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Don't hesitate to give it a try to this tutorial and give me your feedbacks. To discover more tutorial on Android development, you can read my blog : https://www.ssaurel.com/blog
Thanks.
Sylvain

[Tutorial] Learn to create a Flip Coin Application on Android

Hello,
When you start to learn Android Development, it can be interesting to make some little and fun applications. It’s good to motivate yourself and it is also a great way to discover some specific part of the Android SDK. Today, I propose you to create a Flip Coin Application on Android to help you to discover how to use the Animation API.
Note that you can discover this tutorial directly in video on Youtube :
To create a Flip Coin Application, the first thing is to have two images for the head and the tail of the coin. We will use a Minnesota Quarter Coin here :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The second step is to define an ImageView and a Button in the layout of the Main Activity :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.coinflip.MainActivity">
<ImageView
android:id="@+id/coin"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/heads"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/coin"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="Flip"/>
</RelativeLayout>
Now, we can write the Java code. The most interesting part of our application is implemented in the flipCoin() method. We create two animations :
- A Fade Out animation to let the coin disappear when the user will click on the button to flip the coin
- A Fade In animation to let the coin appear after we flip the coin randomly
The Fade Out and Fade In animations are created via the AlphaAnimation class on Android. We are going to animate the alpha property from 1 to 0 for the Fade Out effect and then from 0 to 1 for the Fade In effect.
We add an AnimationListener on the Fade Out animation to be sure to flip the coin and to start the Fade In animation just when the Fade Out effect will be ended.
The code for the Main Activity will have the following form :
Code:
package com.ssaurel.coinflip;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final Random RANDOM = new Random();
private ImageView coin;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coin = (ImageView) findViewById(R.id.coin);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
flipCoin();
}
});
}
private void flipCoin() {
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setFillAfter(true);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
coin.setImageResource(RANDOM.nextFloat() > 0.5f ? R.drawable.tails : R.drawable.heads);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(3000);
fadeIn.setFillAfter(true);
coin.startAnimation(fadeIn);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
coin.startAnimation(fadeOut);
}
}
Now, you can run the application and enjoy the final result :
Don't hesitate to give it a try and give your feedbacks.
Thanks.
Sylvain
nice

[Tutorial] Learn to create the game "Spin The Bottle" for Android

Hello,
I create that thread to present you a tutorial learning you to create the game "Spin The Bottle" for Android. It is also a good way to discover how to use Android Animations API.
What is better that creating some funny games to learn the basics of Android development ? Today, you’re going to discover more on the Android Animation API by creating the game “Spin The Bottle”.
Note that you can discover this tutorial in video on Youtube too :
Spin the bottle is a party game in which several players sit/stand/kneel in a circle. A bottle is placed on the floor in the center of the circle. A player spins the bottle, and must kiss the person to whom the bottle points when it stops spinning.
With our application, it is not necessary any more to have a real bottle, you will just need a smartphone. And it’s great because everyone has always a smartphone on him nowadays.
First step is to find two specific images : one for the floor which will be defined as background of the game and an other for the bottle which will be rotated during the game.
We have chosen to use these both images :
Floor image for the background
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Bottle image
Now, we need to define the layout of our game “Spin The Bottle”. We have a Relative Layout with the floor image as background and we add a bottle in the center of this layout :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background">
<ImageView
android:id="@+id/bottle"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/beer_bottle"
android:layout_centerInParent="true" />
</RelativeLayout>
The next step is to write the Java code of the Main Activity. First, we get references for the views. Then, we install a click listener on the main layout of the Main Activity. Thus, the user will just have to touch the screen to spin the bottle and to start the game.
The core of the game is in the spinTheBottle() method. We are going to define a RotateAnimation from start angle to end angle centered on the center of the bottle. The end angle will be defined randomly to simulate really the game “Spin The Bottle”. We should store the last end angle value to restart the bottle in the same position for the next turn of the game.
The Code of the Main Activity will have the following form :
Code:
package com.ssaurel.spinthebottle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final Random RANDOM = new Random();
private View main;
private ImageView bottle;
private int lastAngle = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = findViewById(R.id.root);
bottle = (ImageView) findViewById(R.id.bottle);
main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
spinTheBottle();
}
});
Toast.makeText(this, R.string.touch_to_spin, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_spin :
spinTheBottle();
break;
case R.id.action_zero :
resetTheBottle();
break;
}
return super.onOptionsItemSelected(item);
}
private void spinTheBottle() {
int angle = RANDOM.nextInt(3600 - 360) + 360;
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, angle, pivotX, pivotY);
lastAngle = angle;
animRotate.setDuration(2500);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
private void resetTheBottle() {
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, 0, pivotX, pivotY);
lastAngle = -1;
animRotate.setDuration(2000);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
}
You can run the application and play your game :
To go further, you can download the game “Spin The Bottle” created in this tutorial on the Google Play Store :
https://play.google.com/store/apps/details?id=com.ssaurel.spinthebottle

Categories

Resources