我有这个问题,我想在按钮点击时启动一个活动。我已经完成了,但是当我开始新的活动时,我也希望同时停止振动器,以便当旧的活动继续时,因为我希望振动器停止。我的代码:
package com.edae;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Btcom extends Activity implements OnClickListener {
private Button bokay;
Vibrator vibe;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_btcom);
bokay = (Button) this.findViewById(R.id.okay);
bokay.setOnClickListener(this);
final Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
int dot = 2000;
long patten[] = {0, dot };
vibe.vibrate(patten, -1);
}
@Override
public void onClick(View v){
Intent openBoot = new Intent(this, Boot.class);
startActivity(openBoot);
super.onPause();
}
}
答案 0 :(得分:3)
您的代码中存在一个小错误。您已在vibe
中重新声明onCreate
首先替换
final Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
带
vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
并声明您的全局变量vibe
final
。
然后你可以像这样解决你的问题:
@Override
public void onClick(View v){
Intent openBoot = new Intent(this, Boot.class);
vibe.cancel();
startActivity(openBoot);
}
}
此处不需要super.onPause()
,因为startActivity(openBoot)
会自动暂停您的活动。
答案 1 :(得分:1)
public void onClick(View v){
Intent openBoot = new Intent(this, Boot.class);
startActivity(openBoot);
//stop your vibrator here.
super.onPause();