-1

我有这个问题,我想在单击按钮时启动一个活动。我已经完成了,但是当我开始新的活动时,我也想同时停止振动器,这样当旧的活动继续时,我希望振动器停止。我有的代码:

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();
  }
}
4

2 回答 2

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)自动暂停您的活动。

于 2013-10-08T12:32:55.720 回答
1
public void onClick(View v){
Intent openBoot = new Intent(this, Boot.class);
startActivity(openBoot);
//stop your vibrator here.
super.onPause();
于 2013-10-08T12:34:01.893 回答