我有倒数计时器,倒计时用户设定的当前时间。虽然,我希望能够访问其他应用程序,或者只是在倒数计时器运行时转到设备的主屏幕,并继续使用倒计时中剩余的计时器更新文本视图。有没有办法做到这一点?我尝试实现下面的服务,但我不知道这是否是完成此任务的正确方法,因为我收到了错误。
% git add [a-j]*
% git st
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: a.rb
new file: b.rb
Untracked files:
(use "git add <file>..." to include in what will be committed)
y.rb
z.rb
答案 0 :(得分:4)
您需要使用服务和广播接收器。 我为你创建了一些example for broadcast receiver。
检查一下,如果您有任何问题,请告诉我。
创建服务:TimerService.java
C:\wamp\www\myfirstgit
在MainActivity.java中
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Initialize and start the counter
countDown = new HokusFocusCountDownTimer(timeDifference, 1000);
countDown.start();
return super.onStartCommand(intent, flags, startId);
}
希望我的回答对您有所帮助
答案 1 :(得分:1)
实际上您需要Alarm Manager + Broadcast Receiver
当您的广播接收器等待警报管理器信号时,您的警报管理器是倒计时的一员。
修改强>
完整的代码可以在GUI updater repo中下载。
示例代码段
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.github.ecobin.gui_refresh_by_time" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".UpdateService"
android:enabled="true"
android:exported="true" >
</service>
</application>
</manifest>
MainActivity
public class MainActivity extends Activity {
public static final String[] WORD_BANK = {"Hello World!", "Ice cream", "Soda", "Cake", "Apple"};
public static final int TIMER = 10; // 10 seconds timer.
public TextView textView;
IntentFilter fil;
BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello_world);
fil = new IntentFilter("mybroadcast");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(">>>>>>>>>>>", "Updating UI!");
updateGUI();
}
};
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent in = new Intent(this, UpdateService.class);
PendingIntent pending = PendingIntent.getService(this, 1234, in, 0);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000 * TIMER, 1000 * TIMER, pending);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, fil);
}
// MORE CODE HERE......
public void updateGUI() {
int randomNumber = (int) (Math.random() * WORD_BANK.length);
textView.setText(WORD_BANK[randomNumber]);
}
}