簡體   English   中英

android.util.AndroidRuntimeException:從Activity外部調用startActivity()

[英]android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity

檢查下面我的代碼。 此代碼在我的適配器中。 但問題是我的手機完全支持應用程序並可以共享,但較低版本的手機不支持其在單擊共享時被強制關閉。

 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)));
        }
    });

在調用startActivity之前執行此操作

sharingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 如果您不使用活動上下文,則必須這樣做。

您不需要為共享意圖添加此標志,而是為意圖使用以下目的開始活動:

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);

擺脫此問題的最佳方法是從適配器的父活動開始活動。 使用上下文對象或使用接口,將它們作為參數傳遞給適配器的構造函數。 使用傳遞的引用在您的活動中調用方法。 這是一個例子:

創建一個接口:

public interface ActivityInteractor{
    public void showDetails();
}

讓您的活動實現它:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM