繁体   English   中英

Android:如何告诉我的活动从服务中开始新的活动?

[英]Android: how do I tell my activity to start new activity from my service?

我提供的一项服务是从互联网上下载图像。 完成此操作后,我想在具有对话框主题的自定义活动中显示此图像。 但是我只想在应用程序正在运行时使用此弹出窗口,否则我只想创建一个通知。

但是,当我尝试从服务中启动活动时遇到异常,我觉得这可能不是正确的方法吗?

它说:

 android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

所以我的问题是,通过设置该标志是否是实现此目的的正确方法,或者我应该如何将已下载的图像从服务中获取到活动中。 我可以以某种方式告诉活动从我的服务类别中开始新活动吗?

我认为使用广播接收器是更好的选择。

在服务中添加以下方法,并在图像下载完成时调用此方法。

private void updateMyActivity(Context context) {
     if(MainActivity.activityStatusFlag){
        //update the activity if activityStatusFlag=true;
        Intent intent = new Intent("mUpdateActivity");
        context.sendBroadcast(intent);        
     }else{
         //display notification if activityStatusFlag=false;
     }
}

在活动中添加以下代码。

public class MainActivity extends Activity{
    public static boolean activityStatusFlag= false; 
        //define this variable to check if activity is running or not.

     @Override
     protected void onResume() {
        super.onResume();   
        activityStatusFlag = true;
        this.getApplicationContext().
        registerReceiver(mMessageReceiver,new IntentFilter("mUpdateActivity"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        activityStatusFlag = false;  
        this.getApplicationContext().unregisterReceiver(mMessageReceiver);
    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                //Display Popup or update Activity
        }
    };
}

暂无
暂无

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

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