android定时多次刷新,android-如何取消计时器并更新相同的计时器...

我最近运行了此代码,并且工作正常.这可以使用广播Receiver来实现.您必须实现单独的CustomTimer任务来扩展TimerTask:

Activity mActivity=null;

public MyCustomTimer(Activity mActivity) {

this.mActivity=mActivity;

}

@Override

public void run() {

this.mActivity.runOnUiThread(new Runnable() {

@Override

public void run() {

Toast.makeText(mActivity, "Write you code here",Toast.LENGTH_LONG).show();

Log.d("MyCustomTimer","Call");

}

});

}

之后,您必须在要实现“ vib()”方法的类中实现BroadCast Receive ::

可以说,就我而言(例如)是MainActivity:

public class MainActivity extends Activity {

private MyCustomTimer myCustomTimer = null;

BroadcastReceiver mBr_Start = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals("START_VIBRATION")) {

System.out.println("onreceive :START_VIBRATION");

vib();

}

}

};

BroadcastReceiver mBr_Stop = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals("STOP_VIBRATION")) {

stopVibration();

}

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

IntentFilter mIntentFilter = new IntentFilter();

mIntentFilter.addAction("START_VIBRATION");

registerReceiver(mBr_Start, mIntentFilter);

IntentFilter mIntentFilter2 = new IntentFilter();

mIntentFilter2.addAction("STOP_VIBRATION");

registerReceiver(mBr_Stop, mIntentFilter2);

Button b1 = (Button) findViewById(R.id.button1);

b1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

Intent i = new Intent(MainActivity.this, MySecondActivity.class)

.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(i);

}

});

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_main, menu);

return true;

}

private void vib() {

myCustomTimer = new MyCustomTimer(MainActivity.this);

Timer timer = new Timer();

timer.scheduleAtFixedRate(myCustomTimer, 0, 30000);

}

private void stopVibration() {

Log.d("MainActivity", "Before Cancel");

if (null != myCustomTimer)

myCustomTimer.cancel();

Log.d("MainActivity", "After Cancel");

}

}

现在,您可以通过实现以下几行来开始或停止振动:

开始振动:

Intent i=new Intent("START_VIBRATION");

mActivity.sendBroadcast(i);

停止:

Intent i=new Intent("STOP_VIBRATION");

mActivity.sendBroadcast(i);

注意:

MainActivity的onDestroy()(在您的情况下,在实现Broadcast Receiver的地方,取消注册BroadcastReceiver.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值