首先layout代码部分很简单,直接写一个小按钮就行了,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/send_notice" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Send Notice"/> </LinearLayout>
接下来就可以来实现点击发送一条消息通知的功能了,再Main_Activity活动中代码如下:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sendNotice = (Button) findViewById(R.id.send_notice); sendNotice.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.send_notice: NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification notification = newNotification.Builder(this) .setContentTitle("标题") .setContentText("内容") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.logo) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo)) .build(); manager.notify(1, notification); break; default: break; } }
}
可是书上这个代码写完以后this的地方会报错,Notification.Builder也会被划线,上网查找了资料发现有效的解决方法,方法如下:
关于this的解决方案:
原来是我们在定义MainActivity类时只继承AppCompatActivity还不够,需要再使用接口OnClickListener。就是不使用匿名内部类,可以直接让当前类实现OnClickListener接口即可。
关于Notification.Builder的解决方法:
书上那种NotificationCompat.Builder(Context context)方法过期了,官方文档建议我们使用新的的构造方法来替代原先过期的构造方法以便在android 8.0上运行出结果。
注:新方法需要适配SDKVersion 26 以上,提前要在build.gradle文件中将minSdkVersion 改为26
全部修改过后的代码如下(加粗部分为修改处):
public class MainActivity extends AppCompatActivity implements View.OnClickListener { String id = "channel_1"; int importance =NotificationManager.IMPORTANCE_HIGH; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sendNotice = (Button) findViewById(R.id.send_notice); sendNotice.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.send_notice: NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationChannel mChannel = new NotificationChannel(id,"test",importance); manager.createNotificationChannel(mChannel); Notification notification = new Notification.Builder(this) .setContentTitle("标题") .setContentText("内容") .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.logo) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo)) .build(); manager.notify(1, notification); break; default: break; } }
}
参考链接:https://blog.csdn.net/weixin_42146999/article/details/80994176
https://www.jianshu.com/p/29dc79d3b1b9
以上仅供参考,欢迎大家留言讨论