没有添加额外的震动及声音效果,这里直接实现了通知的功能,看效果吧:
MainActivity.java
package com.example.notification; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { public NotificationManager mNotificationManager; @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.button1); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // 1-获得MotificationManager的引用。 String ns = Context.NOTIFICATION_SERVICE; mNotificationManager = (NotificationManager) getSystemService(ns); // 2-实例化Notification: int icon = R.drawable.new_mail; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); // 3-定义Notification,如显示icon、目标intent等信息 Context context = getApplicationContext(); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(v.getContext(), MessageActivity.class); PendingIntent contentIntent = PendingIntent.getActivity( v.getContext(), 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); // 4-传递给Manager. final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
MessageActivity.java
package com.example.notification; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.os.Bundle; public class MessageActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.cancel(1);//这里实现了,点击消息后,自己主动清除消息的功能。 } }
XML布局文件就不写了。非常easy的~
这里没有实现通知到达时的提示效果,如震动、提示音之类。将在 Android Notification实现推送消息过程中接受到消息端有声音及震动及亮屏提示 文章实现这样的功能
时间: 2024-10-14 16:53:10