在我的应用程序中,我有一个expandablelistview,当我点击特定的孩子时,我想打开从互联网上下载的PDF。当我点击它时,应用程序崩溃,Android Studio上的Android Monitor上出现此错误:
从Activity上下文外部调用startActivity()需要FLAG_ACTIVITY_NEW_TASK标志。这真的是你想要的吗?
当我尝试添加标志()或setflag()时,它告诉我一些静态上下文。
ContextGetter类:
public class ContextGetter extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
下载程序类:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OpenPDF(我语言中的AbrirPDF)类:
public class AbrirPDF {
public static void showPdf() {
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"lightflow/Read.pdf");
PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
ContextGetter.getAppContext().startActivity(intent);
}
}
活动Java代码的一部分:
private void registerClick() {
expListView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if ((groupPosition == 0) && (childPosition == 0)) {
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("MY_URL", file);
AbrirPDF.showPdf();
} else {
}
return false;
}
});
}
答案 0 :(得分:2)
由于您正在使用应用程序上下文,因此必须在意图
上设置此标志intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
如果您不想使用该标记并继续使用当前任务,则需要在Activity
方法中添加showPdf()
参数,并使用该参数来启动下一个活动。
public static void showPdf(Activity activity) {
...
activity.startActivity(intent);
}
然后,您可以使用以下命令从onChildClick
处理程序中调用它:
AbrirPDF.showPdf(MyActivityClassName.this);