Android 从非活动类开始一个新的活动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12664463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start a new Activity from non Activity class
提问by Nadeem
I want to start a new activity in non-Activity class that implements a DialogListener
following is my code:
我想在非 Activity 类中启动一个新活动,该活动实现DialogListener
以下是我的代码:
public class FacebookLoginDialog implements DialogListener {
@Override
public void onComplete(Bundle values) {
HomeActivity.showInLog(values.toString());
Intent i1 = new Intent (this, SearchActivity.class);
startActivity(i1);
}
@Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
@Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
@Override
public void onCancel() {
// TODO Auto-generated method stub
}
}
I can't start the new activity using intent in onComplete
method, please help.
我无法使用onComplete
方法中的意图启动新活动,请帮助。
Thanks
谢谢
回答by Malcolm
This doesn't work because you need a Context
in order to start a new activity. You can reorganize your class into something like this:
这不起作用,因为您需要 aContext
才能开始新活动。您可以将类重新组织成这样:
public class FacebookLoginDialog implements DialogListener {
private final Context context;
public FacebookLoginDialog(Context context) {
this.context = context;
}
@Override
public void onComplete(Bundle values) {
HomeActivity.showInLog(values.toString());
Intent i1 = new Intent (context, SearchActivity.class);
context.startActivity(i1);
}
//Other methods...
}
Then it will work.
然后它会起作用。
回答by Peter Moskala
Pass context as constructor parameter and then try this
将上下文作为构造函数参数传递,然后试试这个
Intent i = new Intent(this, SearchActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
回答by passionatedevops
use starActivity from non-activity class:
使用非活动类中的 starActivity:
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "YOUR STRING");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share via...");
context.startActivity(Intent.createChooser(intent, "Share"));