1.在xml中定义onclick()
2.在Java文件中
public void showNotification(View view){
// 1.获得通知管理器
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 2.建立一个通知,8.0后需自建通知通道
Notification notification = null;
String id = "mchannel";
String name = "通道1";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mchannel = new NotificationChannel(id,name,NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(mchannel);
notification = new Notification.Builder(this,id)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.drawable.icon))
.setSmallIcon(R.drawable.ic_baseline_event_note_24)
.setStyle(new Notification.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.icon)))
.setContentTitle("好消息")
.setContentText("下周放假不上班")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
// 3.绑定对应的activity
.setContentIntent(PendingIntent.getActivity(this,1,new Intent(this,NotificationResult.class),PendingIntent.FLAG_MUTABLE))
.build();
}
else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN) {
notification = new Notification.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon))
.setSmallIcon(R.drawable.ic_baseline_event_note_24)
.setContentTitle("好消息")
.setContentText("下周放假不上班1")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(this, 1, new Intent(this, NotificationResult.class), PendingIntent.FLAG_CANCEL_CURRENT))
.build();
}
// 4.发出通知
notificationManager.notify(0,notification);
}
}
改进:
public class MainActivity extends AppCompatActivity {
final static String TAG = "HANDLER_TEST";
final static int TEST = 1;
TextView textView = null;
Handler handler = new Handler(){
public void handleMessage(Message message){
switch(message.what){
case TEST:
textView.setText("工作线程,这是一段文本");
break;
}
textView.setText("工作线程,这是一段文本");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.hello);
// textView.setText("hahhahahah");
new ActivityThread().start();
}
class ActivityThread extends Thread{
public void run(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// textView.setText("工作线程,这是一段文本");
Message message = new Message();
message.what = TEST;
handler.sendMessage(new Message());
}
}
}