吐司Java_如何在计时器内显示吐司?

我想制作一个可以在计时器中显示Toast的简单项目 . Timer将使用服务启动 . 然后,Timer在服务启动时启动,在服务停止时停止 .

1级

package com.example.connect;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.widget.Button;

public class MainActivity extends Activity {

Button button1,button2;

private Handler mHandler = new Handler();

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

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

button2=(Button)findViewById(R.id.button2);

}

public void Start(View v)

{

startService(new Intent(MainActivity.this , Connect_service.class));

}

public void Stop(View v)

{

stopService(new Intent(MainActivity.this , Connect_service.class));

}

}

2级

package com.example.connect;

import java.util.Timer;

import java.util.TimerTask;

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;

public class Connect_service extends Service{

Timer timer = new Timer();

TimerTask updateProfile = new CustomTimerTask(Connect_service.this);

public void onCreate() {

super.onCreate();

Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();

timer.scheduleAtFixedRate(updateProfile, 0, 5000);

}

@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();

timer.cancel();

}

@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

return null;

}

}

3级

package com.example.connect;

import java.util.TimerTask;

import android.content.Context;

import android.os.Handler;

import android.widget.Toast;

public class CustomTimerTask extends TimerTask {

private Context context;

private Handler mHandler = new Handler();

public CustomTimerTask(Context con) {

this.context = con;

}

@Override

public void run() {

new Thread(new Runnable() {

public void run() {

mHandler.post(new Runnable() {

public void run() {

Toast.makeText(context, "In Timer", Toast.LENGTH_SHORT).show();

}

});

}

}).start();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值