类中的getSystemService
这个方法获取NotificationManagement,再实例化Notification,最后再用NotificationManagement发送出去即可。注:获取Notification对象时,android api 11之后已经不推荐使用 notification.setLatestEventInfo()
方法了,推荐使用 Notification.Builder
来实例化Notification。样例代码如下: package com.yeetrack.broadcast;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.graphics.Color;public class MainActivity extends Activity { private Button button1; private Button button2; private Notification notification; private NotificationManager notificationManager; private static final int ID = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button)findViewById(R.id.button1Id); button2 = (Button)findViewById(R.id.button2Id); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notification = new Notification(); notification.icon = R.drawable.ic_launcher; notification.tickerText = "我的通知"; notification.when = System.currentTimeMillis(); OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { switch( v.getId()) { case R.id.button1Id: Intent intent = new Intent(MainActivity.this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0); long[] vibrate = {0,100,200,300}; Notification.Builder builder = new Notification.Builder(MainActivity.this) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ic_launcher) .setTicker("我的消息") .setWhen(System.currentTimeMillis()) .setContentTitle("标题") .setContentText("内容") .setSound(Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/sound.mp3")) .setVibrate(vibrate) .setLights(Color.RED, 500, 500); notification = builder.build(); notificationManager.notify(ID, notification); break; case R.id.button2Id: notificationManager.cancel(ID); break; } } }; button1.setOnClickListener(onClickListener); button2.setOnClickListener(onClickListener);}}