val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE ) as NotificationManager
记一下,学习kotlin 遇到的坑。 getSystemService(Context.ALARM_SERVICE)不报错,这个报类型不对。
百度 搜到 weixin_30856965 的博客
getSystemService这个方法基于context,只有存在TextView控件的窗体中这个方法才会被激活~
于是:
1. 给BasicInfo 添加一个带参数Context的构造函数:
public BasicInfo (Context context)
{
this.context = context;
}
2. getPhoneNumber()函数里面改成:
context.getSystemService(Context.TELEPHONY_SERVIC);
3. 在调用类里面 BasicInfo bi = new BasicInfo(this);
bi.getPhoneNumber();
转载于:https://www.cnblogs.com/gaoshen/p/5784788.html
getSystemService的方法必须在Activity类中才能调用啊,亲~
你要想在你的MyClickListener3 调用,可以把相应的activity的上下文传进去:
class MyClickListener3 implements View.OnClickListener{
private Context mContext;
public MyClickListener3(Context context) {
mContext = context;
}
public void notification(){NotificationManager mynotification=(NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Activity中使用的方法:
MyClickListener3 myClickListener3 = new MyClickListener3(MyActivity.this);
mybuttion.setOnclickListener(myClickListener3);
经过测试
getSystemService 在自定义的类 AlarmReceiver 中会出错。
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
val mNotificationManager = getSystemService(p0?.NOTIFICATION_SERVICE )
}
}
正确的不再报错的代码。
class AlarmReceiver (ct1: Context ): BroadcastReceiver() {
private val context :Context = ct1
override fun onReceive(p0: Context?, p1: Intent?) {
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE )
}
}