繁体   English   中英

一旦应用程序退出,如何从广播接收器调用Activity的方法?

[英]How to the call the methods of an Activity from broadcast receiver once the app is quitted?

我想从广播接收器onReceive方法调用activity方法,一旦触发警报就会调用该方法。

以下是我的Home Activity代码段

 public class HomeActivity extends Activity{
         public static HomeActivity mHomeActivity = null;

         protected void onCreate(Bundle savedInstanceState) {
         }


         public void startLocationReporting(){
           ...........//Logic to start the location reporting
         }

         public void stopLocationReporting(){
           ...........//Logic to stopthe location reporting
         }
    }

以下广播接收器将根据我们配置的警报触发

public class AlarmReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
       // Here context is application context not an HomeActivity instance

       //Below code works fine when the app is in foreground 
       if (HomeActivity.mHomeActivity != null) {
            HomeActivity.mHomeActivity.startLocationReporting();
       }

       //Static references are cleared once the app quits. 
       //How to start location reporting when the app is quitted
    }
}

请帮帮我。

一旦应用程序退出,如何从广播接收器调用Activity的方法?

通过创建扩展Activity类的类的对象来调用类中的方法将导致以下主要问题:

1. token android.os.BinderProxy@43756de8 is not valid; is your activity running? token android.os.BinderProxy@43756de8 is not valid; is your activity running? 当尝试使用未运行的Activity上下文访问任何服务时

2.访问调用方法中的视图时出现NullPointerException

或者其他问题也可能......

尝试使用IntentService实现逻辑:

A.通过传递所有必需参数,使用startLocationReportingstopLocationReporting创建单独的类。 通过执行此操作,您将从Activity或任何其他组件访问这两种方法

B.创建一个IntentService来执行任务,并在调用onReceive方法时启动它。 通过这个应用程序将做长期运行的任务在后台这么叫startLocationReportingstopLocationReporting通过了所有必需的参数在IntentService

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM