Android 本地推送消息到通知栏 NotificationManager 、注册Android Service
Android Service ,在退出程序之后 ,仍然留在后台作为服务项做一些事情,比如说监听用户输入之类的。。。。
这里用来做后台的消息推送,像游戏中的广告可以这么做。
Android工程里面有两个Activity、一个Service重写。
MainActivity 是进入游戏的界面。
SecondActivity 是打开通知,点击推送的消息打开的Activity 。
push_service 是重写的Service 。
MainActivity
package com.example.androidnotification;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.Handler;import android.os.IBinder;import android.util.Log;public class push_service extends Service {@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate(){super.onCreate();Log.i("push_service", "push_service onCreate");}@SuppressWarnings("deprecation")@Overridepublic void onStart(Intent intent,int startId){super.onStart(intent, startId);Log.i("push_service", "push_service start");new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {for (int i = 0; i <100; i++) {Thread.sleep(3000);Log.i("push_service", "push_service foreach");//获取到通知管理器NotificationManager mNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);//定义内容int notificationIcon=R.drawable.icon;CharSequence notificationTitle="测试通知栏--title";long when = System.currentTimeMillis();Notification notification=new Notification(notificationIcon, notificationTitle, when);notification.defaults=Notification.DEFAULT_ALL;Intent intent=new Intent(getApplicationContext(),SecondActivity.class);PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);notification.setLatestEventInfo(getApplicationContext(),"测试展开title", "测试展开内容",pendingIntent);if(notification!=null){Log.e("notifacation", "notifacation is ok");mNotificationManager.notify(1000+i, notification);}}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();}@Overridepublic void onDestroy(){super.onDestroy();Log.i("push_service", "push_service destroy");}}
嗯,把发送通知的代码复制到这里循环几百次。。用来测试退出程序后服务是不是还在跑着。