从类中调用服务方法 [英] Calling service method from its class
问题描述
我有我instationate我的 ScreenReceiver
类的服务。我怎样才能通知服务,当 OnRecieve
被触发 ScreenReceiver
的方法是什么?我想在更新()
方法时'onRecieve`被trigerred被调用。
StateChecker.java(草案):
公共类StateChecker延伸服务{
// ...
//设置TimeAlarm
TimeAlarm mTimeAlarm =新TimeAlarm();
mTimeAlarm.SetAlarm(this.getApplicationContext(),10); 公共无效更新(){
//更新做某事
}
// ...
}
ScreenReceiver.java(草案):
公共类ScreenReceiver扩展广播接收器{
// ... @覆盖
公共无效的onReceive(上下文的背景下,意图意图){
// ...
电源管理PM =(电源管理)context.getSystemService(Context.POWER_SERVICE);
}
// ...
}
您也许可以做这样的事情:
请一个新的意图
你的服务
从接收
,冒充一个额外的,然后覆盖 onStartCommand()
在服务。检查目的的额外,如果额外的存在,叫更新()
。
此外,如果使用这个
而不是 this.getApplicationContext()
的,它很可能是你的接收
的的onReceive()
上下文
参数将是服务。然后,你可以施放。
例如:
如果(上下文的instanceof StateChecker)
((StateChecker)上下文).update();
I have a service from which I instationate my ScreenReceiver
class. How can I notify service when OnRecieve
method of ScreenReceiver
is triggered? I'd like the update()
method to be called when 'onRecieve` is trigerred.
StateChecker.java (draft):
public class StateChecker extends Service {
//...
// setting TimeAlarm
TimeAlarm mTimeAlarm = new TimeAlarm();
mTimeAlarm.SetAlarm(this.getApplicationContext(),10);
public void update() {
//update sth
}
//...
}
ScreenReceiver.java (draft):
public class ScreenReceiver extends BroadcastReceiver {
//...
@Override
public void onReceive(Context context, Intent intent) {
//...
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
}
//...
}
You can probably do something like this:
Make a new Intent
to your Service
from the Receiver
, passing off an Extra, then override onStartCommand()
in the Service. Check the intent for the Extra, and if the Extra exists, call update()
.
Also, if you use this
instead of this.getApplicationContext()
, it is very likely that your Receiver
's onReceive()
Context
parameter will be the service. Then you can just cast.
Eg
if (context instanceof StateChecker)
((StateChecker) context).update();
这篇关于从类中调用服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!