我正在尝试构建一个简单的倒计时器应用程序。 MainActivity启动服务(TimerService)。此服务启动CountDownTimer。每次打勾后,我都会发送一个广播来更新我在MainActivity中的视图。查看时间更新到最后一次打勾。当CountDownTimer完成时,我正在使用另一个动作创建一个intent来指示计时器已完成。但是BroadcastReceiver没有收到意图。
这是我的CountDownTimer代码。
@Override
public void onFinish() {
Log.i(TAG, "Timer finished");
Intent notifyMainAct = new Intent(Constants.TIME_OVER);
notifyMainAct.putExtra(Constants.GET_TIMER_VALUE,String.valueOf(0));
sendBroadcast(notifyMainAct);
stopSelf(serviceStartId);
Log.i(TAG, "Stopping service " +serviceStartId);
}
@Override
public void onTick(long millisUntilFinished) {
long minRemaining = millisUntilFinished/60000;
Log.i(TAG, "On Tick: "+String.valueOf(minRemaining));
Intent notifyMainAct = new Intent(Constants.BROADCAST_ACTION);
notifyMainAct.putExtra(Constants.GET_TIMER_VALUE,String.valueOf(minRemaining));
sendBroadcast(notifyMainAct);
}
这是我在MainActivity中的BroadcastReceiver。
private BroadcastReceiver timerCountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "On receiving intent");
String action = intent.getAction();
Log.i(TAG, action);
if(action.equalsIgnoreCase(Constants.BROADCAST_ACTION)) {
String timerCount = intent.getExtras().getString(Constants.GET_TIMER_VALUE);
Log.i(TAG, " Timer count received in Activity "+timerCount);
time_remaining.setText(timerCount);
}
else if(action.equalsIgnoreCase(Constants.TIME_OVER)){
usr_msg.setText("Time OVER");
}
}
};
这是我的manifest.xml。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tony">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".TimerService"
android:enabled="true"
android:exported="false">
</service>
</application>
答案 0 :(得分:0)
这是一件小事。我在onResume()方法中注册BroadcastReceiver时忘记注册intent操作。
@Override
public void onResume(){
super.onResume();
IntentFilter receiverFilter = new IntentFilter();
receiverFilter.addAction(Constants.BROADCAST_ACTION);
receiverFilter.addAction(Constants.TIME_OVER_ACTION);
registerReceiver(timerCountReceiver, receiverFilter);
}