Java 如何从其他类访问它
好的,我在基础知识上有点结巴。我在类中有一个在通知栏中显示通知的方法。我试图使它静态,但如果我使它静态,一些功能将无法工作 如果我在x.class中有以下函数,我如何从y.class访问它?因为我尝试了静态和对象,但都失败了Java 如何从其他类访问它,java,android,Java,Android,好的,我在基础知识上有点结巴。我在类中有一个在通知栏中显示通知的方法。我试图使它静态,但如果我使它静态,一些功能将无法工作 如果我在x.class中有以下函数,我如何从y.class访问它?因为我尝试了静态和对象,但都失败了 void notify(String i) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (Notificat
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);
}
您需要创建一个实例,或者使该方法成为静态的 静态方法无法访问实例方法,除非存在实例 静态方法不能使用
this
关键字,因为没有可引用的实例
在这种情况下,为使用
this
getApplicationContext()的位置传递一个替换项就足够了;我也不能使用它…如果我将它设置为静态,那么您需要的任何实例化变量都可以通过方法的参数传入。如果您需要上下文
,请将您的方法更改为void notify(String i,Context Context)
它与参数一起工作…太愚蠢了,我根本没有想到。谢谢@user1015311没问题:)如果我们每犯一个愚蠢的错误都有五分钱,我们就不必为了犯那些愚蠢的错误而如此努力;)