[5/03] WPA-Enterprise WORKING for UT, UNSW, Georgia Tech - G1 Android Development

At this time, my courseload is way too high for me to do this. I also formatted and lost my sourcecode so I would have to write it from scratch. Sorry!
http://www.4shared.com/file/103246844/247a67c/WPA_Enterprise.html
Look below for instructions to request your school
Root, of course, is required.
The only other things this program needs is for the user to input their username and password as well as copy the security certificate to their SDcard as well as copying the security file to the SDcard. The program takes care of the rest.
I can modify my program to allow other people to connect to WPA Enterprise places in their area. If there is interest in this, let me know and I would be happy to upload versions of my program that allows others to connect.
Donations are always enjoyed
For UT Students:
1. Copy cacerts.pem to your SDCard. Make sure its named cacerts.pem NOT cacerts.pem or anything else similar. The program is CASE SENSITIVE. Make sure to UNMOUNT your sdcard from the computer
2. Run the program and click always to the superuser prompt (if you have it installed)
3. Input your information.
4. Click Save
5. Click Install
6. Click Reboot
If you ever need to revert, just open the program and click undo!
For UNSW Students:
1. Run the program and click always to the superuser prompt (if you have it installed)
3. Input your password (leave username blank)
4. Click Save
5. Click Install
6. Click Reboot
If you ever need to revert, just open the program and click undo!
For Georgia Tech Students
1. Copy Equifax_Secure_CA.pem to your SDCard. Make sure its named Equifax_Secure_CA.pem. The program is CASE SENSITIVE. Make sure to UNMOUNT your sdcard from the computer
2. Run the program and click always to the superuser prompt (if you have it installed)
3. Input your information.
4. Click Save
5. Click Install
6. Click Reboot
If you ever need to revert, just open the program and click undo!
If anyone else wants it, link me to a page like this one and it will give me an example config.
Enjoy!

persiansown said:
I'm putting the finishing touches on my program that allows students that go to the University of Texas to connect to the WPA-Enterprise network here.
Root, of course, is required.
The only other things this program needs is for the user to input their username and password as well as copy the security certificate to their SDcard. The program takes care of the rest.
I can modify my program to allow other people to connect to WPA Enterprise places in their area. If there is interest in this, let me know and I would be happy to upload versions of my program that allows others to connect.
BTW, It definitely does work, I was able to connect to restricted.utexas.edu on my phone and browse the web through it.
Click to expand...
Click to collapse
Thats good news - I am interested - if this works, i'd be finally able to use it on my uni network.
btw - im on adb 1.5 official.

For those who are in a hurry:
http://forum.xda-developers.com/archive/index.php/t-450915.html

Cool Hook EM

Sorry I haven't uploaded the APK yet. I've been really busy with school and the like.
I need to put in a couple more lines so no one screws up their wifi. Expect it soon though

Fellow longhorn says "thanks in advance"

Sounds good, can finally connect to wifi @ my university

Program Released!

need a config pls
thanks alot for this.
here's a link for my uni : http://www.port.ac.uk/special/is/mobilemedia/broadband/wirelessoncampus/ -> its got the config details.
my uni operates on both wpa/wpa2 and the auth is peap, mschapv2
the cer certificate is on the windows xp part on the above link.
ive converted my .cer to .pem through openssl, so atleast one step is complete.
any help pls? thanks.

grippa said:
thanks alot for this.
here's a link for my uni : http://www.port.ac.uk/special/is/mobilemedia/broadband/wirelessoncampus/ -> its got the config details.
my uni operates on both wpa/wpa2 and the auth is peap, mschapv2
the cer certificate is on the windows xp part on the above link.
ive converted my .cer to .pem through openssl, so atleast one step is complete.
any help pls? thanks.
Click to expand...
Click to collapse
I can try that. Im not sure, but Ill try to wing it for you. Ill send you a PM when its uploaded.

If you could try to do the same for these settings that would be awesome =]
http://www.it.unsw.edu.au/services/uniwide/mobile_devices.html

smurphete said:
If you could try to do the same for these settings that would be awesome =]
http://www.it.unsw.edu.au/services/uniwide/mobile_devices.html
Click to expand...
Click to collapse
We've got the same settings here for WPA-Enterprise, only the SSID is "OpenWLAN". (WPA-TKIP / WPA2-AES (Enterprise) & EAP (PEAP and MS-CHAPv2))
Do you think there is a way to do this?

Please post the source. I suggest that other UT students refrain from using this application until then, due to the ridiculously high abuse potential of an app that elevates to root, and even worse, one that you enter EID + password in.
The normal restrictions on network access can be sidestepped. Your EID and password could easily be harvested. Don't run apps like this until the source is available and someone reputable looks at it.
I posted UT Austin specific instructions back in November. If you want access at UT but don't like to gamble, feel free to give them a try. They're a bit dated with respect to gaining root.
http://forum.xda-developers.com/showthread.php?t=450915
I'll add also that the instructions will probably work at any location using WPA Enterprise auth - anything that wpa_supplicant supports. There are several examples in my thread of people getting it to work at their school/workplace. You can either create the configuration file yourself by looking at the Windows/Mac/whatever instructions made available to you, or you may try contacting the local IT dept.

package com.test.login;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class Login extends Activity {
// Declare our Views, so we can access them later
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnInstall;
private Button btnUndo;
private Button btnRestart;
private String username;
private String password;
private String securityfilename = "cacerts.pem";
private boolean copied = false;
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
command("cp /data/misc/wifi/wpa_supplicant.conf /sdcard/wpa_supplicant.conf");
command("cp /data/misc/wifi/wpa_supplicant.conf /sdcard/wpa_supplicant.conf.bac");
super.onCreate(savedInstanceState);
// Set Activity Layout
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.username);
etPassword = (EditText)findViewById(R.id.password);
btnLogin = (Button)findViewById(R.id.login_button);
btnInstall = (Button)findViewById(R.id.install_button);
btnRestart = (Button)findViewById(R.id.restart_button);
btnUndo = (Button)findViewById(R.id.undo_button);
// Spinner array
final Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.locations, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
action("WARNING!","If you have superuser installed, you MUST click ALWAYS before continuing.\n \nOtherwise I'm not sure what may happen\n\nMake sure your Security Certificate is on your SDcard");
// Set Click Listener
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Check Login
username = etUsername.getText().toString();
password = etPassword.getText().toString();
action("Step 1 Complete","Input Successful\nIf phone is in landscape, change to portrait and click again ");
String place = (String) s.getSelectedItem();
inputvalues (username, password, place);
}
});
btnInstall.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
command ("cp /sdcard/" + securityfilename + " /data/misc/wifi/" + securityfilename);
command ("cp /sdcard/wpa_supplicant.conf" + " /data/misc/wifi/wpa_supplicant.conf");
command ("chmod 666 /data/misc/wifi/wpa_supplicant.conf");
command ("chmod 444 /data/misc/wifi/cacerts.pem");
copied = true;
try {
Thread.sleep(2500);
}
catch(InterruptedException e) {}
action("Step 2 Complete","Config Saved Successfly");
}
});
btnRestart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(copied)
command ("reboot");
}
});
btnUndo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
command ("cp /sdcard/wpa_supplicant.conf.bac" + " /data/misc/wifi/wpa_supplicant.conf");
}
});
}
public void command (String inputcommand)
{
Process process = null;
DataOutputStream os = null;
try
{
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(inputcommand);
os.flush();
os.close();
}
catch (Exception e)
{
return;
}
finally
{
try
{
if (os !=null)
{
os.close();
}
}
catch (Exception e) {}
}
}
public void inputvalues (String usrname, String pswrd, String location)
{
if (location=="University of Texas at Austin");
{
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter("/sdcard/wpa_supplicant.conf", true));
writer.newLine();
writer.write("fast_reauth=0");
writer.newLine();
writer.write("network={");
writer.newLine();
writer.write("\t ssid=\"restricted.utexas.edu\"");
writer.newLine();
writer.write("\t key_mgmt=WPA-EAP");
writer.newLine();
writer.write("\t eap=TTLS");
writer.newLine();
writer.write("\t ca_cert=\"/data/misc/wifi/" + securityfilename + "\"");
writer.newLine();
writer.write("subject_match=\"CN=restricted.utexas.edu\"");
writer.newLine();
writer.write("\t anonymous_identity=\"anonymous\"");
writer.newLine();
writer.write("\t identity=\"" + usrname + "\"");
writer.newLine();
writer.write("\t password=\"" + pswrd + "\"");
writer.newLine();
writer.write("\t phase2=\"auth=MSCHAPV2\"");
writer.newLine();
writer.write("}");
writer.newLine();
writer.newLine();
writer.flush();
writer.close();
}
catch(FileNotFoundException ex){}
catch(IOException ioe){}
}
}
public void action (String step, String title)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(step);
alert.setMessage(title);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//cancel
}
});
alert.show();
}
}
Click to expand...
Click to collapse
Here is my source. There is an XML portion that takes care of the interface.
To be truthful, I'm kind of embarrassed of the code because I haven't touched Java since highschool. There is nothing wrong with this application, and nothing nefarious. To be honest, I wouldn't know how to do something like that if I wanted since I would have to delve into the commands.
If you have any suggestions for my code, I would be happy to hear them.
I took up this application as a side product just to see if my knowledge of linux was strong enough (I used linux on my netbook for a while before switching to windows 7) and once I got it working I wanted to share it with the community that has given me so much on both my current phone and previous ones.
Anyway, to all the people in this thread who are requesting stuff:
My birthday is today and my girlfriend came up to UT to celebrate with me. She won't be leaving until Sunday so.... I won't be working on it until Sunday. Bear with me though, I will get it up for you guys if I can (again, I pretty much suck. But now that the framework is down, I think I know what to do)
Smurfette, I took a look there and I'm pretty sure I can do it for you

Georgia Institute of Technology Pilot WPA Program
http://www.lawn.gatech.edu/help/gtwpa/
These are the instructions about signing on to WPA at my university. I will look at modifying the source myself, but I don't have time either at the moment. Just curious--how many other GT students are using XDA-developers to mod their Dream??

So far I am sure I can do it for ellingthepirate and smurphete. I found example configurations for those two. I'm not sure about N23 or the guy on the other page yet. Again, I won't be able to update the app until sunday night (central time) at the earliest.

Will this eventually work with the *.cer certificates?

Hi Persiansown,
I am working on something similar. Can you tell me how did you get permission to create/modify wpa_supplicant.conf programatically?
THANK YOU SO MUCH!!

zhang42 said:
Hi Persiansown,
I am working on something similar. Can you tell me how did you get permission to create/modify wpa_supplicant.conf programatically?
THANK YOU SO MUCH!!
Click to expand...
Click to collapse
Never mind! I've figured it out!

Updated for University of South Wales and Georgia Tech

Related

MapActivity, Buttons and OnClickListener

Hi all,
could you give me some help please? I have written a simple MapActivity that contains a mapview (defined in the xml file); it also contains a Button.
If the Button has no OnClickListener associated then the project runs fine (the mapview is of course empty).
If I add an OnclickListener the application simply Force closes.
Has anyone tried this? I was actually following the example in a book but I guess something has changed in the SDK since it was written?
I m using SDK 1.1 (for the moment).
If you have (recently) written something similar, could you give me some pointers please?
thanks
N
"could you give me some pointers please?"
Might be a nullpointer indeed. Check your LogCat (Eclipse: Window, show view, other, logcat), this will probably give you some nice hints.
LOL
ehhehe
havent checked the log yet, will do and then report back here.
if anyone else has other suggestions please dont hesitate!
thanks
N
LogCat
Vlemmix said:
"could you give me some pointers please?"
Might be a nullpointer indeed. Check your LogCat (Eclipse: Window, show view, other, logcat), this will probably give you some nice hints.
Click to expand...
Click to collapse
Vlemmix,
I checked the LogCat and seems too be a nullpointer indeed, but I cannot identify the mistake in the code.
This is the java source for the class. could you please have a look ?
If I un-comment the commented lines, I get a force close. Leave them uncommented and everything works (no click event on the button tho).
package com.chipset.testgps;
import com.google.android.maps.MapView;
import android.widget.Button;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
public class main extends MapActivity {
@Override
public boolean isRouteDisplayed(){
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button but = (Button) findViewById(R.id.gpsButton);
// but.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v){
//
// }
// });
final MapView map = (MapView) findViewById(R.id.myMap);
setContentView(R.layout.main);
}
}
Any help please??
thanks
N
1)
First do the setContentView, after that the Button is findable. The system could not find your Button now, so that's why it is a null. Your MapView map also would be a null in your code.
2)
If you define an object within {} it is only available within that {}
You probably going to need the Object "but" later, so make it a private variable of the class.
3)
Classname should start with a capital.
4) Visit anddev.org or some site like that for coding problems, xda seems to be more focused on system/firmware issues, not application code.
So, this should work:
public class MainActivity extends MapActivity {
final Button but;
final MapView map;
@Override
public boolean isRouteDisplayed() {
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but = (Button) findViewById(R.id.gpsButton);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
}
});
map = (MapView) findViewById(R.id.myMap);
}
}
Right
Hi Vlemmix.
Thanks very much for your help. I can understand what you are telling me, but if its so:
1) with the listener's lines commented, my code does show both the button and the mapview.. shouldnt it force close anyways if the problem is the setcontentView?
2) yeah agree with you on this one, though since I couldnt get even this simplest code to work, I didnt really want to overcomplicate it for now.
3) this is not a requirement is it? I mean its a coding convention, a good one yes, but not mandatory..?
4) Will do thanks, I m trying to get my bearings with all the dev websites etc.
PS about the API Key.. is this strictly required for developing on localhost (testing on the emu)? I find the info a bit confusing to be honest..
I will give your mods a shot this evening and will post here later tonight.
For the moment a big thank you for showing me my (silly) mistakes (I kinda miss .NET at times.. I wouldnt have messed up that bad with it..).
thanks!
N
Quick reply:
1) You can only find a view when the content is set. No content: nothin' to find!
3) Just do it! ;-)
API key, localhost? I don't understand your question... I'm on SDK1.1, did some work on the emulator, now most on the G1, no big difference. Don't know about keys. You probably need a key for generation an apk for the market though.
ApiKey
Vlemmix said:
Quick reply:
1) You can only find a view when the content is set. No content: nothin' to find!
3) Just do it! ;-)
API key, localhost? I don't understand your question... I'm on SDK1.1, did some work on the emulator, now most on the G1, no big difference. Don't know about keys. You probably need a key for generation an apk for the market though.
Click to expand...
Click to collapse
Will try and let you know mate!
The API Key you need to put in the xml for the MapView. apparently google has made this a requirement instead of the bogus key. I just dont understand if this is true also for the apps you test on the emu or only the ones that go 'live'..
Vlemmix
HI there,
just wanted to let you know that moving the setcontentview worked a treat!
Im so very embarassed now
thanks again for your help mate, I owe you one.
N
You're welcome, no problem!

[Q] How to insert a "run this always" loop

Hi Everyone,
Using the SkeletonApp default code, how would I insert a void or whatever (sorry not knowing the terminology yet) that would run each cycle of the program like a counter or something?
Just keep it simple, just a "run this always" loop while maintaining the button functions would be great.
thanks and hope you all had a happy thanksgiving
So I added this and it does not work, how in the world do I get a counter working ?
Please, Please someone point me in the right direction?
All I want it to do (in the default SkellyApp) is count to 30, then end the proggy. And yes, I did make the mytimer a variable at the top of my proggy.
public int mytimer;
-------- stuff ---------
@Override
public void onResume() {
mytimer = (mytimer + 1);
if (mytimer == 30) finish();
super.onResume();
}
thank you in advance for taking the time to look, and HOPEFULLY answer this for me.

Java homework..

I missed one class of my java programming class, and now i do not know what to do at all. If anyone could do the problems for me, i would be grateful. Before i get bashed for having someone do my homework, i can learn really easy if someone does it for me, and i can work out how they did it through a matter of trial and error.
Thank you.
Everything you need to know about the Java String class is on this page, including a few samples that are very similar to your assignment.
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
I still don't understand it. I can only learn when someone shows me, so unless someone here can do it i guess i have to turn it in as a zero.
Answer to 1. is here 2 and 3 are up to you.
Code:
class StringApp {
public static void main(String[] args) {
String str,str1,str2,str3;
int length;
str="CSE 201";
length=str.length();
str1="ABC";
str2="XYZ";
str3=str1.concat(str2);
}
}
P.S. I've never written a line of Java code before. Luckily it is not that far from C#.
Thank you! Two more problems left.
Awwwwww....... What the hell.....
Answers to 2 and 4:
Code:
class TestApp
{
public static void main(String[] args)
{
String phrase = "To be or not to be";
String anotherPhrase="not";
String longphrase;
String today ="Tuesday,January 18";
int commapos;
System.out.printf("a. %s is %d characters long.\n",phrase, phrase.length());
System.out.printf("b. %d\n",phrase.indexOf(anotherPhrase));
System.out.printf ("c. %s\n",phrase.substring(3, 12));
longphrase=phrase + ", that is the question.";
System.out.printf ("d. %s\n",longphrase);
System.out.printf("e. %d\n",phrase.indexOf("Alien"));
System.out.printf("f. %c\n",phrase.charAt(0));
System.out.printf("g. %c\n",phrase.charAt(phrase.length()-1));
commapos=today.indexOf(",");
System.out.printf("Today is %s. What a great %s!\n",today.substring(commapos+1),today.substring(0,commapos));
}
}
When run produces:-
Code:
a. To be or not to be is 18 characters long.
b. 9
c. be or not
d. To be or not to be, that is the question.
e. -1
f. T
g. e
Today is January 18. What a great Tuesday!
Question 3.
c. str.charAt(0); // str. missing
d. int n=str1.indexOf(str2); // dot missing between str1 and IndexOf()

[Q] Need help to populate a listview from external source

I'm pretty new to java and somewhat new to android and I've been looking everywhere for the past 3 or 4 days but cant seem to find the answer to my question. I'm making an app that is pretty simple and has only one real main function and that is to pull movie names, release dates, and the movie's format (dvd, blu-ray etc) into the app automatically from a very simple file that I will host on my server.
Now I I'm currently able to input the needed information manually via a base-adapter and a strings file within each months activity but I want to have the ability to push the information remotely which will then give my app (and myself) the ability to update the information as well as to place it into the 3 line listview format that I've already established.
Now I've been reading about Simple:XML, gson, SAX, etc but seeing as the information is just 3 small lines of text (again just the movie name, date and format which doesn't use much space and will be using the same string format for all 12 months) my question is what would be the best route as to the format of the file (i.e. xml, json, plain text, etc) and how would I go about getting this information into my app on the fly? I've included some code snippets below in the hopes they will make my question a little more clear.
I've posted this on several other forums and android dev sites and nobody seems to be able to give me some guidance or simply will not reply at all. I cannot continue on my app until I'm able to figure this out and seeing as it is completed aside from this problem it is becoming a very frustrating experience. I'm hopeful that someone here will be able to give my some help out. Thank you in advance.
The string for each result
Code:
public class SearchResults {
private String Name = "";
private String Date = "";
private String Format = "";
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getDate() {
return Date;
}
public void setDate(String Date) {
this.Date = Date;
}
public String getFormat() {
return Format;
}
public void setFormat(String Format) {
this.Format = Format;
}
This below is where the actual list-view is populated and shown. Each new search result creates a three line text-view.
Code:
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1.setName("Movie #1");
sr1.setDate("July 24th");
sr1.setFormat("DVD, Blu-Ray");
results.add(sr1);
sr1 = new SearchResults();
sr1.setName("Movie #2");
sr1.seDate("July 19th");
sr1.setFormat("DVD, Blu-Ray, Digital");
results.add(sr1);
return results;
}
Can anybody help me with this please?

Application for notify when your flat is power-less

Hi everyone
I was searching one app for android, but i cannot find any like that.
Basically i need to understand when my flat went down on electricity
beacuse i have food in the fridge, fish in the acquarium or whatever you may have.
I was thinking i could leave a currently unused phone on charge in the wall socket.
When electricity goes off the phone stop charging and it can notify me with email.
Do you think something like that exist?
A general event driven notifier that support email would be fine.
Is there anything like that? on the market even a paid app?
Best regards, Andrea
You could try using Tasker for it.
"To err is human, to forgive is divine"
Sent from my SGS II
Tasker do half of the job...
it detects what i need, it compose the email...
but it cannot send it!!!
It can open a web url directly, so i can program a simple php script to send an email.
But if i could do without a webserver helping me it would be better.
I think that SMS notification will be more reliable in this case. Anyway all that you need is a very simple app, probably no more than several lines of code. If you are still interested in this I can help you to write one (if you have at least basic programming knowledge) or write one for you.
qubas said:
I think that SMS notification will be more reliable in this case. Anyway all that you need is a very simple app, probably no more than several lines of code. If you are still interested in this I can help you to write one (if you have at least basic programming knowledge) or write one for you.
Click to expand...
Click to collapse
solved with tasker. i make it open weburl, on web url i made application that send email.
cause tasker compose but cannot send.
i have programming knowledge,i would like to start,i just don t like java
maybe just a problem of mine
do you have some empty app franework to look at?
asturur said:
solved with tasker. i make it open weburl, on web url i made application that send email.
cause tasker compose but cannot send.
i have programming knowledge,i would like to start,i just don t like java
maybe just a problem of mine
do you have some empty app franework to look at?
Click to expand...
Click to collapse
There are many tutorials for installing Android Development Tools (ADT) and creating simple "Hello world" app. It probably takes 1 hour to do that. For simple app you don't really have to know Java, copy-paste some code samples from the Internet should do the trick, you just need to have at least some basic programming knowledge.
I still think that sending SMS is the most reliable solution. Using Wifi is a bad idea, because it won't work when there is no AC, unless you have a UPS. With 3G its much better, but still you have to rely on the web service you use to send email.
Anyway, here is my code:
Code:
package com.example.powermonitoring;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String NUMBER = "+48123456789";
private static final int THRESHOLD = 10;
private static final String AC_ONLINE = "AC is back online!";
private static final String AC_OFFLINE = "AC is offline!";
private Handler handler = new Handler();
private int counter;
private boolean lastPowerState;
private boolean powerState;
private Runnable runnable = new Runnable() {
[user=439709]@override[/user]
public void run() {
powerState = isPlugged(MainActivity.this);
if (powerState != lastPowerState) {
counter++;
if (counter == THRESHOLD) {
counter = 0;
lastPowerState = powerState;
String message;
if (powerState) {
message = AC_ONLINE;
} else {
message = AC_OFFLINE;
}
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); //for testing
//SmsManager sms = SmsManager.getDefault();
//sms.sendTextMessage(NUMBER, null, message, null, null);
}
}
handler.postDelayed(this, 1000);
}
};
public static boolean isPlugged(Context context) {
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastPowerState = isPlugged(MainActivity.this);
handler.postDelayed(runnable, 1000);
}
}
You just have to remember about including permission in AndroidManifest.xml :
Code:
<uses-permission
android:name="android.permission.SEND_SMS"
/>

Categories

Resources