android本地定時通知

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   color   使用   sp   

android本地通知略有不同,分為立即觸發和延時觸發

1.即時通知

android預設的Notification為立即觸發

        Intent intent = new Intent(Intent.ACTION_VIEW);        intent.addCategory(Intent.CATEGORY_LAUNCHER);            intent.setClass(_gameActivity, _gameActivity.getClass());            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);            PendingIntent content = PendingIntent.getActivity(context, 0, intent, 0);            final NotificationManager notiMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);            final Notification noti = new Notification(R.drawable.icon, notiResult.getPayload(), System.currentTimeMillis());            String app_name = _gameActivity.getResources().getString(R.string.app_name);            noti.setLatestEventInfo(context, app_name, notiResult.getPayload(), content);            notiMgr.notify(atomicInteger.incrementAndGet(), noti);

2.延時觸發

想讓一定時間後再觸發通知,其實是用系統的AlarmManager來實現的。

具體的AlarmManager解釋參考

http://yuanzhifei89.iteye.com/blog/1131523

http://blog.csdn.net/ryantang03/article/details/9317499

 

添加一個ALARM_SERVICE

/*     * name:通知名字,作為通知id使用     * content:通知內容     * time:倒時時(秒)     * */    public static void addLocalNotication(String name, String content, int time)    {        Calendar cal = Calendar.getInstance();        cal.setTimeInMillis(System.currentTimeMillis());          cal.add(Calendar.SECOND, (int) time);          Activity activity = _gameActivity;        Intent intent = new Intent(activity, NotificationReceiver.class);        intent.setClass(activity, NotificationReceiver.class);          intent.setData(Uri.parse(name));

      intent.putExtra("msg", "play_hskay");

         intent.putExtra("content", content);

             PendingIntent pi = PendingIntent.getBroadcast(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);                     AlarmManager am = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);    }

添加一個系統通知類,用於在倒計時間到時,接收系統輪詢通知

import java.util.List;import java.util.concurrent.atomic.AtomicInteger;import android.app.ActivityManager;import android.app.ActivityManager.RunningAppProcessInfo;import android.app.ActivityManager.RunningTaskInfo;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.BroadcastReceiver;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.pm.PackageInfo;import android.content.pm.ResolveInfo;import android.content.pm.PackageManager.NameNotFoundException;import android.util.Log;import android.widget.Toast;public class NotificationReceiver extends BroadcastReceiver{    public NotificationReceiver(){}            @Override    public void onReceive(Context context, Intent itent) {        //Toast.makeText(context, "鬧鈴響了, 可以做點事情了~~", Toast.LENGTH_LONG).show();          String msg = itent.getStringExtra("msg");        String content = itent.getStringExtra("content");      //判斷應用是否在前台運行         if (isTopActivity(context)) {            return;        }       //推送一條通知        shownotification(context,content);        return;    }            public void shownotification(Context context, String msg)      {          NotificationManager barmanager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);          Notification notice = new Notification(R.drawable.icon,msg,System.currentTimeMillis());          notice.flags=Notification.FLAG_AUTO_CANCEL;                  Intent appIntent = new Intent(Intent.ACTION_MAIN);          appIntent.addCategory(Intent.CATEGORY_LAUNCHER);          appIntent.setComponent(new ComponentName(context.getPackageName(), context.getPackageName() + "." + "Splash"));           //設定啟動模式          appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,                appIntent, PendingIntent.FLAG_UPDATE_CURRENT);        String app_name = context.getResources().getString(R.string.app_name);        notice.setLatestEventInfo(context, app_name, msg, contentIntent);        AtomicInteger atomicInteger = new AtomicInteger(1);        barmanager.notify(0, notice);    }         protected static boolean isTopActivity(Context activity){        String packageName = activity.getPackageName();        ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);        List<RunningTaskInfo>  tasksInfo = activityManager.getRunningTasks(1);          if(tasksInfo.size() > 0){              Log.d("test","---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());            //應用程式位於堆棧的頂層              if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){                  return true;              }          }          return false;    }}

 

<receiver android:name=".NotificationReceiver"             android:permission="com.google.android.c2dm.permission.SEND">            <intent-filter>                <action android:name="play_hskay" />            </intent-filter>        </receiver>

 

android本地定時通知

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.