如何从Android上的Service调用主线程函数?
我有 Main 类,它包含函数 isSyncAllowed 。我启动另一个服务。如何从此服务调用函数isSyncAllowed
? 它说:
无法静态引用 非静态方法 isSyncAllowed(Boolean) 来自类型 主要
如果我将该函数的类型更改为静态并传递上下文,我会遇到 startManagingCursor 不能是静态的问题。
我该如何修复它?
更新。这是SyncService的代码:
public class SyncService extends BroadcastReceiver {
...
public void onReceive(Context context, Intent intent) {
...
Boolean isDownloadAllowed = Kinobaza.isSyncAllowed(true);
}
这是Main的代码:
public class Kinobaza extends ListActivity {
...
public static Boolean isSyncAllowed(Boolean showToasts) {
...
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor); // here is the error
}
}
I have Main class and it contains function isSyncAllowed
. I start another service. How to call function isSyncAllowed
from this service?
It says:
Cannot make a static reference to the
non-static method
isSyncAllowed(Boolean) from the type
Main
If I change type of that function to static
and pass context
, I come to the problem that startManagingCursor can not be static.
How can I fix it?
Upd. Here is the code of SyncService:
public class SyncService extends BroadcastReceiver {
...
public void onReceive(Context context, Intent intent) {
...
Boolean isDownloadAllowed = Kinobaza.isSyncAllowed(true);
}
and here is the code of Main:
public class Kinobaza extends ListActivity {
...
public static Boolean isSyncAllowed(Boolean showToasts) {
...
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor); // here is the error
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能正在执行
Main.isSyncAllowed(...)
而不是main.isSyncAllowed(...)
,其中main
是一个对象类Main
。如果您位于
Main
的实例方法内,则只需执行isSyncAllowed(...)
即可。编辑 - 现在我看到了您的代码,您可能应该通过您提供给服务的
Intent
传递isSyncAllowed
。当您启动服务时:然后在您的服务中您可以检索它:
您的服务不需要在您的活动上调用实例方法。
You are probably doing
Main.isSyncAllowed(...)
instead ofmain.isSyncAllowed(...)
, wheremain
is an object of classMain
.If you are inside an instance method of
Main
, then you can simply doisSyncAllowed(...)
.Edit - now that I see your code, you should probably pass
isSyncAllowed
via theIntent
you give to the service. When you start the service:and then in your service you can retrieve it:
Your service shouldn't need to call instance methods on your activities.