android - Run a function over and over again -
I'm new to writing an app for Android. I have had the experience of writing programs in non object-oriented program language, but also want to learn this method of programming.
I would like to start simple and do the following: a button and a vibrator press will be triggered in a specific method until the phone is pressed again
I know if you say Are: vibrator.vibrate (pattern, 0); That this pattern will repeat. But for example I want to turn the screen on and off in that pattern.
What would be the right way to do this?
Thank you very much for your help.
package com.trick-design.simple_prog; Import android App Importroid.os.Bundle; Import android.content.Context; Import Android.os.Vibrator; Import android.view.View; Public square simple_prog activity extends to {private long} pattern = {100, 100, 300, 100, 900, 1050}; Boolean vibrator_on = true; /** Called when the activity is first created. * / @Override Public Zero onCreate (bundled savedInstanceState) {super.onCreate (savedInstanceState); SetContentView (R.layout.main); } @ Override protected void onStart () {super.onstart (); FindViewById (R.id.vibrate_button) .setOnClickListener (vibrate_click_listener); } See. OnClickListener vibrate_click_listener = View new. OnClickListener () {Click on Public Zero (see V) {vibrator Vibrator = (vibrator) getSystemService (reference .dbBRATOR_SERVICE); Vibrator Vibration (pattern, -1); }}; @ Override Protected Zero ontop () {super.onStop (); // Activity is no longer visible (now it is "closed") @ Override Protected Zero at Desto () {Super. Onesteroy (); // activity is going to be deleted}}
In:
You will need to create a class that implements runnablas or extends the thread so that it can be done to prevent hanging in another thread. You can do this with a second class in the same * .java file - it allows the file to access variables from other classes:
Private class VibrateRunner implements Runnable {public Void run () (while (vibration)) {executeVibrate (); }} Execute private zeros () {vibrator.vibrate (pattern, -1); }} Your click listener needs to be smart enough to start / stop threads:
// Thread class variable Create a Thread BgThread = null; OnClick (see V) {// you already started the thread - stop it if (bgThread! = Tap) {vibrate_on = false; BgThread.join (); Return; } // need to turn on thread vibrate_on = true; Runner runner = new vibration (); BgThread = new backgroundread (runner); BgThread.setDaemon (true); // run it in background bgThread.start (); } This should take you in the right direction. Note: I dedicate to deal with a lot of exceptions here - read something on Java threads to feel for it. Eclipse will also help you to produce corrective / catching blocks.
- Donation
Comments
Post a Comment