Android本地推送

推送基本接口

//获取app图标
int iconResId = 0;
if(applicationInfo!=null){
    iconResId = applicationInfo.icon;
}
if(iconResId == 0){
    iconResId=R.drawable.icon;
}
//获取推送大图标
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), iconResId);
//构建打开界面
Intent intent1 = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, id, intent1, PendingIntent.FLAG_ONE_SHOT);
//构建推送对象         
Notification.Builder builder =new Notification.Builder(context);
builder.setSmallIcon(iconResId);
builder.setLargeIcon(bitmap);
builder.setTicker(datas[0]);
builder.setContentTitle(datas[0]);
builder.setContentText(datas[1]);
builder.setContentIntent(pendingIntent);
//设置默认声音
builder.setDefaults(Notification.DEFAULT_SOUND);
//设置点击自动清除状态栏显示
builder.setAutoCancel(true);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(id, builder.build());

与Alarm服务结合,定时推送消息

首先需要创建一个Alarm广播的接受者,当接收到消息的时候,发送通知

package com.example.alarmtest1;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver  {
    private NotificationManager m_notificationMgr = null;

    @SuppressLint("NewApi")
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "定时时间到了", Toast.LENGTH_SHORT).show();

        m_notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (intent.getAction().equals(GlobalValues.TIMER_ACTION_REPEATING)) {
            Log.e("alarm_receiver", "周期闹钟");
        } else if (intent.getAction().equals(GlobalValues.TIMER_ACTION)) {

            int id = intent.getIntExtra("id", -1);
            Log.e("alarm_receiver", "定时闹钟"+id);
            SharedPreferences sharedPreferences = context.getSharedPreferences("LocalNotification", Context.MODE_PRIVATE);
            String message = sharedPreferences.getString("message_"+id, "XXXX,通知");
            String[] datas = message.split(",");
            Intent intent1 = new Intent(context, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, id, intent1, PendingIntent.FLAG_ONE_SHOT);
            ApplicationInfo applicationInfo = null;
            try {
                applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 128);
            } catch (NameNotFoundException e) {
            }
            int iconResId = 0;
            if(applicationInfo!=null){
                iconResId = applicationInfo.icon;
            }
            if(iconResId == 0){
                iconResId=R.drawable.icon;
            }
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), iconResId);
           int i= Notification.DEFAULT_SOUND;
           Notification.Builder builder =new Notification.Builder(context);
           builder.setSmallIcon(iconResId);
           builder.setLargeIcon(bitmap);
           builder.setTicker(datas[0]);
           builder.setContentTitle(datas[0]);
           builder.setContentText(datas[1]);
           builder.setContentIntent(pendingIntent);
           builder.setDefaults(Notification.DEFAULT_SOUND);
           builder.setAutoCancel(true);
//            Notification notify = new Notification.Builder(context)
//                    .setSmallIcon(iconResId) // 设置状态栏中的小图片,尺寸一般建议在24×24
//                    .setLargeIcon(bitmap) // 这里也可以设置大图标
//                    .setTicker("XXXX") // 设置显示的提示文字
//                    .setContentTitle(datas[0]) // 设置显示的标题
//                    .setContentText(datas[1]) // 消息的详细内容
//                    .setContentIntent(pendingIntent) // 关联PendingIntent
//                    .setDefaults(Notification.DEFAULT_SOUND)
//                    .setNumber(1) // 在TextView的右方显示的数字,可以在外部定义一个变量,点击累加setNumber(count),这时显示的和
//                    .getNotification(); // 需要注意build()是在API level16及之后增加的,在API11中可以使用getNotificatin()来
//            
//            notify.flags |= Notification.FLAG_AUTO_CANCEL;

            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//            manager.notify(id, notify);
            manager.notify(id, builder.build());
            bitmap.recycle(); //回收bitmap
            LocalNotificationManager.getInstance().removeNotifiDate(id, context);
        }
    }
}

AndroidManifest配置

 <receiver android:name=".AlarmReceiver" >
            <intent-filter>
                <action android:name="com.e_eduspace.TIMER_ACTION_REPEATING" />
                <action android:name="com.e_eduspace.TIMER_ACTION1" />
            </intent-filter>
        </receiver>

创建通知创建、取消的管理类

package com.example.alarmtest1;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;

public class LocalNotificationManager {
     String NotifyKey="timeList";
     String TAG="LocalNotificationManager";
     private static LocalNotificationManager instance;

     public static LocalNotificationManager getInstance(){
         if(instance==null){
             instance=new LocalNotificationManager();
         }
         return instance;
     }
     /**
      * 设置推送时间
      * @param id 推送id
      * @param afterSeconds 多少秒后开始发送推送消息
      * @param title 推送标题
      * @param content 推送内容
      * @param context
      */
     public void SetAlarmNotification(int id,int afterSeconds,String title,String content,Context context){
         AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         Intent myIntent = new Intent();
         myIntent.setAction(GlobalValues.TIMER_ACTION);
         myIntent.putExtra("id", id); 
         SharedPreferences sharedPreferences = context.getSharedPreferences("LocalNotification", Context.MODE_PRIVATE);
         SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
         editor.putString("message_"+id, String.format("%s,%s", title,content));
         editor.commit();

         PendingIntent sender = PendingIntent.getBroadcast(context, id, myIntent,PendingIntent.FLAG_ONE_SHOT);
         long notifyTime = System.currentTimeMillis() + afterSeconds * 1000;
         alarm.set(AlarmManager.RTC_WAKEUP,notifyTime , sender);
         addNotifiDate(id,notifyTime,context);
     }

     public void UpdateAlarmNotification(int id,long notifyTime,Context context){
             AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
             Intent myIntent = new Intent();
             myIntent.setAction(GlobalValues.TIMER_ACTION);
             myIntent.putExtra("id", id);
             PendingIntent sender = PendingIntent.getBroadcast(context, id, myIntent,PendingIntent.FLAG_ONE_SHOT);
             alarm.set(AlarmManager.RTC_WAKEUP, notifyTime, sender);
             addNotifiDate(id,notifyTime,context);
    }

     /**
      * 取消推送
      * @param id
      * @param context
      */
     public void CancelLocalNotification(int id,Context context){
         CancelLocalNotification(id,context,true);
     }

     public void CancelLocalNotification(int id,Context context,boolean isClearCache){
         AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         Intent myIntent = new Intent();
         myIntent.setAction(GlobalValues.TIMER_ACTION);
         myIntent.putExtra("id", id);
         if(isClearCache){
             SharedPreferences sharedPreferences = context.getSharedPreferences("LocalNotification", Context.MODE_PRIVATE);
             SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
             editor.remove("message_"+id);
             editor.commit(); 
         }
         PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);
         alarm.cancel(sender);
         removeNotifiDate(id,context);
     }


     /**
      * 杀进程的时候,推送相关的服务都会终止,因此需要在进入游戏的时候,刷新之前保存的推送内容
      * 每次启动,刷新本地定时通知内容
      */
     public void updateNotifiDate(Context context){
         Map<Integer, String > map = getLocalNofyTimeData(context);
         Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
         long curTime = System.currentTimeMillis();
         ArrayList<Integer> removeKeyList=new ArrayList<Integer>();
         while(it.hasNext()){

             Map.Entry<Integer, String> en = it.next();
             Integer id = en.getKey();
             long notifyTime = Long.parseLong(en.getValue());
             CancelLocalNotification(id,context,false);
             if(notifyTime<curTime){
                 removeKeyList.add(id);
                 Log.i(TAG, "过期key is "+id+",value is"+notifyTime);
                 continue;
             }
             UpdateAlarmNotification(id,notifyTime,context);

         }
         Log.i(TAG, "curTime is "+curTime);
         //删除过期的key
         if(removeKeyList.size()>0){
             for(int i=0;i<removeKeyList.size();i++){
                 map.remove(removeKeyList.get(i));
                 Log.i(TAG, "过期key is "+removeKeyList.get(i));
             }

             resaveLocalNofyTimeData(map,context);
         }


     }


     public void addNotifiDate(int id,long notifyTime,Context context){
         Map<Integer, String > map = getLocalNofyTimeData(context);
         map.put(id, notifyTime+"");
         resaveLocalNofyTimeData(map,context);
     }

     public void removeNotifiDate(int id,Context context){
         Map<Integer, String > map = getLocalNofyTimeData(context);
         if(map.containsKey(id)){
             map.remove(id);
         }
         resaveLocalNofyTimeData(map,context);
     }


     public Map<Integer, String > getLocalNofyTimeData(Context context){
        Map<Integer, String > map = new HashMap<Integer, String >();
        SharedPreferences sharedPreferences = context.getSharedPreferences("LocalNotification", Context.MODE_PRIVATE);
         String times="";
         if(sharedPreferences.contains(NotifyKey)){
             times=sharedPreferences.getString(NotifyKey, "");
         }
         if(times.length()>0){
             String[] arr = times.split(",");
             for(int i=0;i<arr.length;i++){
                String[] items = arr[i].split("_");
                if(items.length==2){
                    int id = Integer.parseInt(items[0]);
                    String time=items[1];
                    map.put(id, time);
                }
             }
         }

         return map;
    }

     public void resaveLocalNofyTimeData(Map<Integer, String > map,Context context){
         SharedPreferences sharedPreferences = context.getSharedPreferences("LocalNotification", Context.MODE_PRIVATE);
         SharedPreferences.Editor editor = sharedPreferences.edit();
         Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
         StringBuilder sb=new StringBuilder();
         int index=0;
         while(it.hasNext()){
             Map.Entry<Integer, String> en = it.next();
             Integer key = en.getKey();
             String value = en.getValue(); 
             if(index>0){
                 sb.append(String.format(",%d_%s", key,value));
             }else{
                 sb.append(String.format("%d_%s", key,value));
             }
             index++;
         }
         editor.putString(NotifyKey, sb.toString());
         Log.i(TAG, "notifyData is "+sb.toString());
         editor.commit();
     }


}

一些全局变量

package com.example.alarmtest1;

public class GlobalValues {
     // 周期性的闹钟
    public final static String TIMER_ACTION_REPEATING = "com.e_eduspace.TIMER_ACTION_REPEATING";
    // 定时闹钟
    public final static String TIMER_ACTION = "com.e_eduspace.TIMER_ACTION1";
}

测试

package com.example.alarmtest1;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    int index=0;

    private LocalNotificationManager localNotificationManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localNotificationManager=new LocalNotificationManager();
        updateNotifiDate();
    }

    public void OnClick(View v){
        Toast.makeText(getApplicationContext(), "sjskjs", Toast.LENGTH_SHORT).show();
        SetAlarmNotification(index++,6,"this is a test title","this is content"+index);
    }



 public void SetAlarmNotification(int id ,int afterSeconds,String title,String content){
     localNotificationManager.SetAlarmNotification(id, afterSeconds, title, content, getApplicationContext());
 }

// public void UpdateAlarmNotification(int id,long notifyTime){
//   localNotificationManager.UpdateAlarmNotification(id, notifyTime, getApplicationContext());
//}

 public void CancelLocalNotification(int id){
     localNotificationManager.CancelLocalNotification(id, getApplicationContext());
 }


 /**
  * 每次启动,刷新本地定时通知内容
  */
 void updateNotifiDate(){
     localNotificationManager.updateNotifiDate(getApplicationContext());
 }

// void addNotifiDate(int id,long notifyTime){
//   localNotificationManager.addNotifiDate(id, notifyTime, getApplicationContext());
// }
// 
// void removeNotifiDate(int id){
//   localNotificationManager.removeNotifiDate(id, getApplicationContext());
// }


// Map<Integer, String > getLocalNofyTimeData(){
//  return localNotificationManager.getLocalNofyTimeData(getApplicationContext());
//}
// 
// void resaveLocalNofyTimeData(Map<Integer, String > map){
//   localNotificationManager.resaveLocalNofyTimeData(map, getApplicationContext());
// }


 //--------设置声音
 private static Uri getSoundUri(String soundName)
 {
   if ((soundName == null) || (soundName.equals(""))) {
     return Uri.EMPTY;
   }

    File soundFile = new File(soundName);
   if (!soundFile.exists()) {
     return Uri.EMPTY;
   }
   return Uri.fromFile(soundFile);
 }

}

多消息推送主要事项

1 注册广播
PendingIntent sender = PendingIntent.getBroadcast(context, id, myIntent,PendingIntent.FLAG_ONE_SHOT);
第二个参数设置为推送消息id,相同的id推送结果会被覆盖

2、notifcation要显示多条,那么NotificationManager.notify( id, notify); 中的要保持不一样;
如果id值一样,那么就把之前的notify覆盖更新为当期最新的;

3、点击notification 进入到activity, 使用到pendingIntent类方法,PengdingIntent.getActivity()的第二个参数,即请求参数,
实际上是通过该参数来区别不同的Intent的,如果id相同,就会覆盖掉之前的Intent了,

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯过客TYGK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值