android中的本地定时推送到通知栏

一、使用系统定义的Notification
以下是使用示例代码:
import android.app.Notification;  
import android.app.NotificationManager; 
import android.app.PendingIntent;  
import android.content.Context;  

public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
    private NotificationManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mian_water);

       //获取到通知管理器  
      manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);  
    }   
  
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_wf_back:
      // 定义Notification的各种属性
      int icon = R.drawable.button_login; //通知图标
      CharSequence tickerText = "Hello"; //状态栏显示的通知文本提示
      long when = System.currentTimeMillis(); //通知产生的时间,会在通知信息里显示
      Notification myNotify = new Notification(icon,tickerText,when);

      Context context = getApplicationContext(); //上下文
      CharSequence contentTitle = "My Notification"; //通知栏标题
      CharSequence contentText = "Hello World!"; //通知栏内容
      Intent notificationIntent = new Intent(this,WaterActivity.class); //点击该通知后要跳转的Activity
      PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
      myNotify.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
      manager.notify(0x00000008, myNotify); 
      //如果想要更新一个通知,只需要在设置好notification之后,再次调用 setLatestEventInfo(),然后重新发送一次通知即可,即再次调用notify()。
      break;  
     }
  }
}        
二、使用自定义的 Notification
要创建一个自定义的Notification,可以使用RemoteViews。
要定义自己的扩展消息,首先 要初始化一个RemoteViews对象,然后将它传递给Notification的contentView字段,再把PendingIntent传递给 contentIntent字段。
以下示例代码是完整步骤:
1、创建一个自 定义的消息布局 my_notification.xml
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="wrap_content"  
    android:background="#ffffff"  
    android:orientation="vertical" >  
  
    <TextView  
        android:id="@+id/text_content"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:textSize="20sp" />  
  
</LinearLayout>  
2、 在程序代码中使用RemoteViews的方法来定义image和text。然后把RemoteViews对象传到contentView字段
 RemoteViews rv = new RemoteViews(getPackageName(),   R.layout.my_notification);  
 rv.setTextViewText(R.id.text_content, "hello wrold!");  
 myNotify.contentView = rv;  
3、 为Notification的contentIntent字段定义一个Intent(注意,使用自定义View不需要 setLatestEventInfo()方法)
 Intent intent = new Intent(Intent.ACTION_MAIN);  
 PendingIntent contentIntent = PendingIntent.getActivity(this, 1,  intent, 1);  
 myNotify.contentIntent = contentIntent;
4、发送通知
manager.notify(0x00000008, myNotify);
5.完整代码
import android.app.Notification;  
import android.app.NotificationManager; 
import android.app.PendingIntent;  
import android.content.Context;  
import android.widget.RemoteViews;  

public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
    private NotificationManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mian_water);

       //获取到通知管理器  
      manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);  
    }   
  
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_wf_back:
            Notification myNotify = new Notification();
        myNotify.icon = R.drawable.button_login;  
            myNotify.tickerText = "TickerText:您有新短消息,请注意查收!";  
            myNotify.when = System.currentTimeMillis();  
            //myNotify.flags = Notification.FLAG_NO_CLEAR;// 不能够自动清除  
            RemoteViews rv = new RemoteViews(getPackageName(),   R.layout.my_notification);  
            rv.setTextViewText(R.id.text_content, "hello wrold!");  
            myNotify.contentView = rv;  
            Intent intent = new Intent(Intent.ACTION_MAIN);  
            PendingIntent contentIntent = PendingIntent.getActivity(this, 1,  intent, 1);  
            myNotify.contentIntent = contentIntent;
       manager.notify(0x00000008, myNotify); 
       //如果想要更新一个通知,只需要在设置好notification之后,再次调用 setLatestEventInfo(),然后重新发送一次通知即可,即再次调用notify()。
       break;  
     }
  }
}  

6.清除

manager.cancel(2);

参数属性:

        // 定义Notification的各种属性   
        Notification notification =new Notification(R.drawable.icon,   
                "测试", System.currentTimeMillis()); 
        //FLAG_AUTO_CANCEL   该通知能被状态栏的清除按钮给清除掉
        //FLAG_NO_CLEAR      该通知不能被状态栏的清除按钮给清除掉
        //FLAG_ONGOING_EVENT 通知放置在正在运行
        //FLAG_INSISTENT     是否一直进行,比如音乐一直播放,知道用户响应
        notification.flags |= Notification.FLAG_ONGOING_EVENT; 
        // 将此通知放到通知栏的"Ongoing"即"正在运行"组中   
        notification.flags |= Notification.FLAG_NO_CLEAR; 
        // 表明在点击了通知栏中的"清除通知"后,此通知不清除,经常与FLAG_ONGOING_EVENT一起使用   
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;   
        //DEFAULT_ALL     使用所有默认值,比如声音,震动,闪屏等等
        //DEFAULT_LIGHTS  使用默认闪光提示
        //DEFAULT_SOUNDS  使用默认提示声音
        //DEFAULT_VIBRATE 使用默认手机震动,需加上<uses-permission android:name="android.permission.VIBRATE" />权限
        notification.defaults = Notification.DEFAULT_LIGHTS; 
        //叠加效果常量
        //notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;
        notification.ledARGB = Color.BLUE;   
        notification.ledOnMS =5000; //闪光时间,毫秒
          
        // 设置通知的事件消息   
        CharSequence contentTitle ="标题"; // 通知栏标题   
        CharSequence contentText ="内容"; // 通知栏内容   

        //如果需要跳转到指定的Activity,则需要设置PendingIntent 

        Intent notificationIntent =new Intent(A.this, B.class); 
        // 点击该通知后要跳转的Activity  
 
        notificationIntent.putExtra("date","需要传递的参数"); 

       // FLAG_UPDATE_CURRENT 更新数据,如果有多个PendingIntent,且requestCode相同,则会替换为最新extra数据
       //如果需要通过不同的extra数据,进行处理,就需要requestCode不相同
        int requestCode = new Random().nextInt();
        PendingIntent contentItent = PendingIntent.getActivity(this, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);   
      
        notification.setLatestEventInfo(this, contentTitle, contentText, contentItent);   
        
        // 把Notification传递给NotificationManager   
        notificationManager.notify(0, notification);

注意:

new Intent(this,this.getClass())保证了点击通知栏里的通知可以回到该Activity

但是,假如该Activity还在后台运行,并没有运行,通知事件响应后,系统会自动结束该Activity,然后再重新启动Activity,这不是我们要的。

解决方法为:在manifest.xml文件中找到该Activity,添加属性android:launchMode="singleTask“。这个属性很明显,就是只允许有一个该Activity运行,如果正在运行,则只能切换到当前运行的Activity,而不能重新启动Activity。

三、创建定时器
源代码如下:
import java.util.Timer;  
import java.util.TimerTask;    

public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
    private Timer mTimer = null;  
    private TimerTask mTimerTask = null;  
    private int isPause = 0; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mian_water);
    }   
  
    private void startMyTimer(){  
        if (mTimer == null) {  
            mTimer = new Timer();  
        }  
  
        if (mTimerTask == null) {  
            mTimerTask = new TimerTask() {  
                @Override  
                public void run() {  
                    do {  
                       try { 
                            if(isPause == 0) isPause = 1;
                            else isPause = 0;
                            
                            Message message = new Message();
                            message.what = isPause;
                            handler.sendMessage(message);
                            
                        } catch (IllegalStateException e) {  
                        }     
                    } while (false);  
                }  
            };  
        }  
  
        if(mTimer != null && mTimerTask != null )  
            mTimer.schedule(mTimerTask, 0, 500);  
  
    }  
  
    private void stopMyTimer(){  
          
        if (mTimer != null) {  
            mTimer.cancel();  
            mTimer = null;  
        }  
  
        if (mTimerTask != null) {  
            mTimerTask.cancel();  
            mTimerTask = null;  
        }     
    }  
}   
原文地址:https://www.cnblogs.com/cslunatic/p/5623837.html