我正在编写一个小的Android应用程序,它在后台执行某些操作(即服务),我希望它在每隔'x'分钟后显示一个toast消息。如何使用广播监听器和告警管理器进行此操作。有人可以写一个示例代码来演示它。
答案 0 :(得分:1)
您可以使用Timer
课程中的TimerTask
和Service
轻松完成此操作。
1。在Service
课程中,首先创建一个从DisplayToastTimerTask
延伸的内部课程TimerTask
,以显示Toast
消息。您必须使用Handler
与Runnable
一起显示Toast
中的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>
希望这会有所帮助〜