您可以做什么使 TimerReceiver 扩展 BroadCastRecevier 并能够接收这些意图接收:
在Manifest文件中定义它 以接收以下Intents:
<receiver android:name=".TimerReceiver" exported="false" >
<intent-filter >
<action android:name="com.yourpackagename.starttimer"/>
<action android:name="com.yourpackagename.endtimer"/>
<action android:name="com.yourpackagename.restarttimer"/>
</intent-filter>
</receiver>
在应用程序中编写广播接收器需要什么
public class TimerReceiver extends BroadcastReceiver {
public static final String START_TIMER = "com.tcs.starttimer";
public static final String END_SESSION = "com.tcs.endsession";
public static final String RESTART_SESSION="com.tcs.restartsession";
private int sessionTimer=10*60*1000; //your time of counter in miliseconds
private int tickTime=1000; //tick time to decrease the counter in one milisecond
@Override
public void onReceive(Context contextdata, Intent intent) {
String actionString=intent.getAction();
if(actionString.equals(TimerReceiver .START_TIMER)){
timerStart();
}
} else if(actionString.equals(TimerReceiver .END_SESSION)){
//write what you want on ending the session
}
}
void timerStart(){
try{
cTimer.cancel();
}catch(Exception e){
}
cTimer=new CountDownTimer(sessionTimer,tickTime) {
@Override
public void onTick(long millisUntilFinished) {
counter++;
}
@Override
public void onFinish() {
//Log.d("counter","finish.counter: "+counter);
int timeout=(sessionTimer/1000)-(tickTime/1000);
if(counter==timeout){
Toast.makeText(context, "Session Timeout",Toast.LENGTH_LONG).show();
context.sendBroadcast(new Intent(END_SESSION));
}
}
}.start();
}
}
如果需要,您可以再添加一项操作,例如重新启动计时器。
点击按钮,您的 Activity 需要做什么:
context.sendBroadcast(new Intent((TimerReceiver .START_TIMER));
在我的情况下,我正在增加你也可以反过来做。享受为我工作,希望对您有所帮助。