这是我第一次尝试创建Android应用。我正在尝试创建一个可以在后台计算的服务,我希望服务将时间广播给接收者。但是看起来接收器没有收到任何东西,所以我不确定我的服务是否已经开始。
这是我尝试启动服务并创建接收器的代码:
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
这是我的服务类:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction("EXAMPLE_BROADCAST");
clock = (TextView) findViewById(R.id.textClock);
timeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
setClock(intent.getLongExtra("counter", 0));
}
};
registerReceiver(timeReceiver,filter);
startService(new Intent(this, CounterService.class));
}
public void setClock(long time){
clock.setText(String.valueOf(time));
}
}
感谢任何帮助,谢谢。
答案 0 :(得分:0)
您需要注册接收器。
在您的活动的onStart
方法
IntentFilter filter = new IntentFilter();
filter.addAction("YOUR_ACTION");
registerReceiver(timeReceiver, filter)
在您的活动的onStop
方法
unregisterReceiver(timeReceiver)
在发送广播之前,请将您的操作添加到Intent
timeBroadcaster.setAction("YOUR_ACTION");
答案 1 :(得分:0)
Runnable 不会自行执行,您需要将其提供给线程。
Runnable counter = new Runnable() {
@Override
public void run() {
isActive = ((PowerManager) getSystemService(Context.POWER_SERVICE)).isInteractive();
if(isActive) {
timeInMilliseconds += 1000;
handler.postDelayed(this, 1000);
}
else {
if(timeInMilliseconds > 5000) {
timeInMilliseconds = 0;
}
handler.postDelayed(this, 1000);
}
timeBroadcaster.putExtra("counter", timeInMilliseconds);
sendBroadcast(timeBroadcaster);
}
};
Thread thread = new Thread(counter);
thread.start();
还在清单中注册您的服务:
<!--Register service-->
<service android:name="yourpackage.CounterService" />