Android-在活动的静态内部类中制作toast或dialog
在我的静态内部类中获取应用程序上下文时遇到问题:Android-在活动的静态内部类中制作toast或dialog,android,android-context,Android,Android Context,在我的静态内部类中获取应用程序上下文时遇到问题: public class MainActivity extends Activity { ..... .... public static class SMSAlertHandler extends BroadcastReceiver { @Override public void onReceive(Context context,
public class MainActivity extends Activity {
.....
....
public static class SMSAlertHandler extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
....
....
Toast.makeText(context, "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
}
}
如果我给出上下文,它就是给出异常
无法添加窗口-标记null不适用于应用程序
如果我将getApplicationContext()
,也会显示错误
无法对非静态方法进行静态引用
从类型ContextWrapper获取getApplicationContext()
是的,静态方法不能使用对非静态字段的引用。您接收到的上下文不允许进行UI操作,您可以查看一下,其中显示了您可以对接收到的每个上下文执行哪些操作 您可以在活动中设置接收器,如下所示:
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("YourAction");
registerReceiver(receiver, filter);
// or LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter); if you are using LocalBroadcast system
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "message", LENGHT_LONG).show();
}
}
第二种方法(我不确定是否有效,因为我还没有测试),但在resume中,您可以从应用程序类获得上下文:
您可以创建一个应用程序类来获取上下文,例如:
public class App extends android.app.Application {
private static android.app.Application application;
public static Context getContext() {
return application.getApplicationContext();
}
public void onCreate() {
super.onCreate();
application = this;
}
}
然后您可以在接收机内部使用:
public static class SMSAlertHandler extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(App.getContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
}
}
请记住将应用程序类添加到AndroidManifext.xml中
<application
android:name=".App"
... >
您有应用程序类吗?(扩展应用程序)?有没有办法将这个BroadcastReceiver作为一个单独的类而不是内部类?我的回答对您有帮助吗?