Reputation: 79
I read a lot about this problem on Stackoverflow but not of the Helps her works at my problem. My problem is that my app always stops on the phone. I wanna have a switch button and if its turned on, it should vibrate indefinitely every 10 seconds.
package com.example.myapp;
import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
public class MainActivity extends Activity {
private Switch mySwitch;
public // Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySwitch = (Switch) findViewById(R.id.myswitch);
//set the switch to off
mySwitch.setChecked(false);
//attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};
// The '0' here means to repeat indefinitely
// '-1' would play the vibration once
v.vibrate(pattern, 0);
}else{
v.cancel();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Thank for your help!
Upvotes: 1
Views: 1520
Reputation: 58
Your error is at the following line: public // Get instance of Vibrator from current Context Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
The system services are not available to your Activity before the method onCreate() is called. So you have to initialize your vibrator in onCreate() method.
Upvotes: 1
Reputation: 3962
My suggestion is
it should work with screen off.
App Permission:
<uses-permission android:name="android.permission.VIBRATE"/>
Upvotes: 0
Reputation: 13761
You could start a Thread
where you would put something like this in it:
while (true) {
v.vibrate(500); // Half a second
sleep(10000); // Wait 10 seconds
}
But as this will run indefinitely, you'll need also to have some kind of condition or event in your Thread
to stop it under certain circumstances (for example, if an action happens, or if a BroadcastReceiver
signal triggers. More info here.
More info on stopping a Thread
here.
Upvotes: 0