实现简单的Notification,点击之后跳转到应用界面

NotificationService类

public class NotificationService extends Service {
    private Notification notification;
    private PendingIntent pit;
    private NotificationManager notificationManager;
    public NotificationService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Intent it = new Intent(this, MainActivity.class);
//        it.putExtra("NotificationService","SUCCESS");
        pit = PendingIntent.getActivity(this, 0, it, 0);
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder mBuilder=new Notification.Builder(this);
        mBuilder.setSmallIcon(R.drawable.ic_launcher_background)//设置小图标
                .setContentTitle("预警信息")//标题
                .setContentText("1111")
                .setWhen(System.currentTimeMillis())           //设置通知时间
                .setAutoCancel(true)                           //设置点击后取消Notification
                .setContentIntent(pit);
        notification = mBuilder.build();
        notificationManager.notify(1,notification);
    }
}

 

MainActivity类

public class MainActivity extends AppCompatActivity {

    private AlarmManager manager;//实现定时
    private PendingIntent pi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager= (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, NotificationService.class);
        pi = PendingIntent.getService(this, 0, intent, 0);
        // 设置AlarmManager启动与时间间隔(低于一分钟会以一分钟计算)
        manager.setRepeating(AlarmManager.RTC_WAKEUP, AlarmManager.RTC,300000L, pi);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值