New to Android, Will this loop upon startup?
I'm new to android dev and I was wondering if, upon startup, will the following code start looping, check the result of connect, vibrate if 1, and then sleep for 5 minutes?
/** Called when the activity is first created. */
boolean flag = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
while(flag) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
String foundblock = connect("blahblahblah"); //will return either 0 or 1
if (foundblock == "1") {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long milliseconds = 10;
开发者_如何转开发 v.vibrate(milliseconds);
flag = false;
}
}
}, 300000);
}
Yeah, it'll loop. Don't expect the android process manager to keep it alive for too long though. It will also result in a ton of runnables being posted, as itll run through the while loop over and over.
This code will be forcefully terminated due to onCreate() not returning within an acceptable time limit. You can start a thread from onCreate() but you can't hang out forever.
Lose the while loop, and just postDelayed(). Your runnable can loop within it (as long as you give yourself a way to be told to terminate it!).
You might change the variable foundblock
(and the return of your connect()
function) to boolean or at least an int, since String is overkill for what you're describing and since string checks for equality are not performed with the ==
operator.
It will crash as the onCreate has a time limit. If you put the loop in a seperate thread then it will stop the application from crashing. example:
Thread myThread = new Thread(){
public void run(){
while(flag) {
int foundblock = connect("blahblahblah"); //will return either 0 or 1
if (foundblock == 1) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long milliseconds = 10;
v.vibrate(milliseconds);
flag = false;
}
}
}
};
myThread.start();
This definately works, rather than then putting this thread to sleep, just restart it after the time you want to wait has passed by calling myThread.start() again.
精彩评论