我在Long []中存储了许多值,用于android中的振动方法,
int dot = 100;
int dash = 220;
int short_gap = 200;
int medium_gap = 700;
vibIndicator = (TextView)findViewById(R.id.TextView01);
vibPattern = new long[] {0, dash, short_gap, dot, short_gap, dot, short_gap, dot, medium_gap};
for (int i = 0; i < vibPattern.length; i++)
{
if (vibPattern[i] == 100)
{
vibIndicator.setBackgroundResource(R.color.White);
}
else if(vibPattern[i] == 220)
{
vibIndicator.setBackgroundResource(R.color.Red);
}
try
{
Thread.sleep(vibPattern[i]);
}
catch (InterruptedException e)
{
//
}
}
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(vibPattern, -1);
当它变成短划线或点
时,我需要相应地更改textview的背景颜色应用程序会挂起一段时间(我假设它处于睡眠状态)并且仅在恢复时显示最后的背景颜色
答案 0 :(得分:1)
Thread.sleep()
无法保证睡眠时间,您需要自己编程,例如:
private void sleep(long ms) {
long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < ms) {
try {
Thread.sleep(ms - (System.currentTimeMillis() - start));
} catch (InterruptedException e) {
}
}
}
答案 1 :(得分:1)
好吧,我想学习如何使用振动器并快速编写这个程序,它可以满足您的需求。必须在AndroidManifest中设置振动器权限:
<uses-permission android:name="android.permission.VIBRATE"/>
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.widget.TextView;
import android.widget.Toast;
public class Launch extends Activity {
int dot = 100;
int dash = 220;
int short_gap = 200;
int medium_gap = 700;
int i = 0;
long[] vibPattern = new long[] {0, dash, short_gap, dot, short_gap, dot, short_gap, dot, medium_gap};
TextView vibIndicator;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vibIndicator = (TextView)findViewById(R.id.textView1);
simpleTimer();
}
public void simpleTimer(){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (vibPattern[i] == dot){
vibIndicator.setBackgroundColor(Color.WHITE);
vibratePhone(vibPattern[i]);
}else if(vibPattern[i] == dash){
vibIndicator.setBackgroundColor(Color.RED);
vibratePhone(vibPattern[i]);
}else{
vibIndicator.setBackgroundColor(Color.TRANSPARENT);
}
i++;
if (i< vibPattern.length){
simpleTimer();
}else{
Toast.makeText(Launch.this, "Finished", Toast.LENGTH_LONG).show();
}
}
}, vibPattern[i]);
}
public void vibratePhone(long timeLength){
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
try{
vibrator.vibrate(timeLength);
}catch(Exception e){
}
}
}
答案 2 :(得分:1)
在开始振动模式之前,您正在迭代所有GUI更新。因此,在进行振动模式时,它只会显示最后的状态。
之前我没有使用Android,所以我假设vibrate()
阻止,直到模式完成。如果您仍想使用该方法,则需要异步执行此操作,以便更新循环并行运行。另一种选择是以更细的粒度控制振动器而不使用模式方法。这样,在每次迭代时,您可以决定是否需要打开或关闭振动器以及这对GUI更新意味着什么。