2015-04-22 47 views
0

我有让我静态内部类中的应用程序方面的问题里面烤面包或对话框:Android的 - 使静态内部类活动

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(),显示错误

无法使静态参考非静态方法 getApplicationContext()从类型ContextWrapper

+0

你有应用程序类? (扩展应用程序)? –

+0

有什么办法可以让这个BroadcastReceiver作为一个单独的类而不是内部类吗? – Santhana

+0

我的回答对你有帮助吗? –

回答

1

叶氏,静态方法不能使用于非静态字段引用。并且您收到接收者的上下文不允许进行UI操作,您可以查看this article,其中显示了您可以对收到的每个上下文执行的操作。

您可以设置接收器的活动,如:

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

而第二种方法(我不知道是否会工作,因为我并没有测试),但在简历你得到的从应用程序类方面:

您可以创建一个应用程序类,以获取上下文,例如:

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

Remeber到App类添加到您的AndroidManifext.xml

<application 
     android:name=".App" 
     ... >