Notification和NotificationManager的操作比较简单,一般用来获取系统级的服务 NotificationManager,然后实例化Notification的对象,设置它的属性(比如说图标、时间、标题、内容等),最后通过 NotificationManager发出通知即可。
首先,新建一个Android项目--->取名NotificationDemo
MainActivity.java的代码如下:
- public class MainActivity extends Activity {
- private Button send;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- send = (Button)findViewById(R.id.send);
- send.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- int icon = R.drawable.com_aol_mobile_engadget;
- long when = System.currentTimeMillis();
- //新建一个通知,指定标题和图标
- //param1:图标 param2:标题 param3:通知时间
- Notification notif = new Notification(icon, null, when);
- notif.defaults = notif.DEFAULT_SOUND;
- //当点击信息时,就会向系统发出openintent意图
- PendingIntent pintent = PendingIntent.getActivity(MainActivity.this, 0, null, 0);
- //param4:点击通知时,发出的意图
- notif.setLatestEventInfo(MainActivity.this, "想念", "好久不见,十分想念", pintent);
- //发送通知 param1:要发送通知码 param2:通知
- nm.notify(0, notif);
- }
- });
- }
- }
main.xml的布局
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button
- android:id="@+id/send"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/send"
- />
- </LinearLayout>
strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello">Hello World, MainActivity!</string>
- <string name="app_name">notification应用</string>
- <string name="send">发送通知</string>
- </resources>
AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.gem.activity"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".MainActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- <uses-sdk android:minSdkVersion="8" />
- </manifest>
效果图如下
转载于:https://blog.51cto.com/emilyzhou/685317