我正在编写一个在后台执行某些操作(即服务)的小型 android 应用程序,我希望它在每隔“x”分钟后显示一条 toast 消息。我该如何使用广播监听器和警报管理器来做这件事。有人可以写一个示例代码来演示它。
问问题
2922 次
1 回答
2
您可以通过在课堂上使用Timer
和轻松做到这一点。TimerTask
Service
1.在您的Service
类中,首先创建一个内部类DisplayToastTimerTask
,扩展 from TimerTask
以显示Toast
消息。您必须使用Handler
withRunnable
来显示Toast
from TimerTask
:
private class DisplayToastTimerTask extends TimerTask {
Handler mHandler = new Handler();
@Override
public void run() {
// Do something....
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Hello world", Toast.LENGTH_SHORT).show();
}
});
}
}
2.用于Timer
安排DisplayToastTimerTask
重复执行的时间间隔为2 min
private static final int TIMER_INTERVAL = 120000; // 2 Minute
private static final int TIMER_DELAY = 0;
// Create new Timer
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
例子:
#. 这是完全的工人阶级Service
:**
//MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
private Timer mTimer;
private Handler mHandler = new Handler();
private static final int TIMER_INTERVAL = 120000; // 2 Minute
private static final int TIMER_DELAY = 0;
@Override
public void onCreate() {
super.onCreate();
if (mTimer != null)
mTimer = null;
// Create new Timer
mTimer = new Timer();
// Required to Schedule DisplayToastTimerTask for repeated execution with an interval of `2 min`
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
// Cancel timer
mTimer.cancel();
}
// Required to do some task
// Here I just display a toast message "Hello world"
private class DisplayToastTimerTask extends TimerTask {
@Override
public void run() {
// Do something....
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Hello world", Toast.LENGTH_SHORT).show();
}
});
}
}
}
#. 你可以从service
下面开始你的喜欢:
Intent intentMyService = new Intent(context, MyService.class);
mContext.startService(intentMyService);
#. 不要忘记将MyService
类声明为AndroidManifest.xml
:
<?xml version="1.0" encoding="utf-8"?>
<manifest>
<application>
<service android:name=".MyService" />
</application>
</manifest>
希望这会有所帮助~
于 2017-06-09T09:31:22.280 回答