2011-11-09 70 views
0

好吧,我有点基础知识。我有一个方法在类中显示通知栏中的通知。我试图让它变成静态的,但如果我将它变成静态的,一些函数将不起作用。如何从不同的类访问

所以,如果我在x.class中有以下功能,我怎样才能从y.class访问它?因为我用静态和对象尝试过,但都失败了。

void notify(String i) { 

     String ns = Context.NOTIFICATION_SERVICE; 
     NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 


     int icon = R.drawable.icon;  // icon from resources 
     CharSequence tickerText = "gogu la telefon";    // ticker-text 
     long when = System.currentTimeMillis();   // notification time 
     Context context = getApplicationContext();  // application Context 
     CharSequence contentTitle = "My notification"; // message title 
     CharSequence contentText = "Hello World!";  // message text 



     Intent notificationIntent = new Intent(this, MilkyWaySearcherActivity.class); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

     // the next two lines initialize the Notification, using the configurations above 
     Notification notification = new Notification(icon, tickerText, when); 
     notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
     notification.ledARGB = 0xff00ff00; 
     notification.ledOnMS = 300; 
     notification.ledOffMS = 1000; 
     notification.flags |= Notification.FLAG_SHOW_LIGHTS; 

     mNotificationManager.notify(BIND_AUTO_CREATE, notification); 
    } 

回答

2

您可能需要创建一个实例或使该方法为静态。

静态方法无法访问实例方法,除非有实例。

静态方法不能使用this关键字,因为没有实例可以引用。

在这种情况下,可能已经足够让您替换使用this的地方。

+0

getApplicationContext();我也不能使用这个...如果我把它做成静态的 – user1015311

+0

你需要的任何实例化变量都可以通过方法的参数传入。如果你需要一个'Context',把你的方法改为'void notify(String i,Context context)' –

+0

它与参数一起工作......太愚蠢了,我没有想到。谢谢! – user1015311

相关问题