【问题标题】:android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activityandroid.util.AndroidRuntimeException:从 Activity 外部调用 startActivity()
【发布时间】:2018-06-01 05:47:14
【问题描述】:

检查下面我的代码,。这段代码在我的适配器中。但问题是我的手机完全支持应用和共享,但低版本的手机不支持点击共享时强制关闭。

 share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String shareBody = "\t\t DIL KI BAAT \n\n" +sayari[position].toString().trim()+"\n\n\n"+ "https://play.google.com/store/apps/details?id="
                    + appPackageName;

            Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
            sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
            context.startActivity(Intent.createChooser(sharingIntent, context.getResources()
                    .getString(R.string.app_name)));
        }
    });

【问题讨论】:

  • 发布您的适配器代码
  • 我的错误是这样的 android.util.AndroidRuntimeException:从 Activity 上下文之外调用 startActivity() 需要 FLAG_ACTIVITY_NEW_TASK 标志。这真的是你想要的吗?
  • @sasikumar 但是 letest 手机已经在这个代码中工作了,不能在低版本的小型安卓手机上工作?
  • Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag您没有尝试在 google 中搜索此错误消息,是吗?

标签: java android android-studio onclick


【解决方案1】:

在调用 startActivity 之前执行此操作

sharingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 。如果您不使用活动上下文,这是必需的。

【讨论】:

    【解决方案2】:

    你需要添加这个标志不是为了分享意图,而是为了你开始活动的意图:

    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    sharingIntent.setType("text/plain");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    
    Intent startIntent = Intent.createChooser(sharingIntent, context.getResources().getString(R.string.app_name));
    startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(startIntent);
    

    【讨论】:

      【解决方案3】:

      解决此问题的最佳方法是从适配器父活动开始活动。使用上下文对象或使用接口,将它们作为参数传递给适配器的构造函数。使用传递的引用在您的活动中调用方法。这是一个例子:

      创建接口:

      public interface ActivityInteractor{
          public void showDetails();
      }
      

      让你的 Activity 实现它:

      public class MyActivity extends Activity implements ActivityInteractor{
          public void showDetails(){
              //do stuff
          }
      }
      

      然后将您的活动传递给 ListAdater:

      公共 MyAdapter 扩展 BaseAdater{ 私有 ActivityInteractor 监听器;

      public MyAdapter(ActivityInteractor listener){
          this.listener = listener;
      }
      

      } 在适配器中的某个地方,当您需要调用该 Activity 方法时:

      listener.showDetails();
      

      【讨论】:

      • 完成,谢谢
      猜你喜欢
      • 1970-01-01
      • 2011-04-11
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      相关资源
      最近更新 更多