2013-10-08 112 views
-1

我有这个问题,我想开始一个按钮点击一个活动。我已经完成了,但是当我开始新的活动时,我也想同时停止振动器,这样当旧的活动继续时,我想振动器停止。我的代码为:两个动作与一个按钮android

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

重写'onPause()'方法并在那里停止振动器,并且不需要在'onClick()'方法中调用'onPause()'。 – xhamr

+0

Ahh的原因..这是显而易见的..对不起浪费你和别人的时间..我的坏。 – Lasse

回答

3

代码中存在一个小错误。您已在您的onCreate中重新申报vibe
先更换

final Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 

vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 

,并宣布你的全局变量vibefinal

然后你就可以解决你的问题是这样的:

@Override 
public void onClick(View v){ 
    Intent openBoot = new Intent(this, Boot.class); 
    vibe.cancel(); 
    startActivity(openBoot); 
    } 
} 

在这里不需要的super.onPause(),因为startActivity(openBoot)自动暂停您的活动。

+0

谢谢你!这帮助我很多! – Lasse

+1

@Lasse欢迎您:-) –

1
public void onClick(View v){ 
Intent openBoot = new Intent(this, Boot.class); 
startActivity(openBoot); 
//stop your vibrator here. 
super.onPause();