import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.IBinder;
import android.util.Log;
public class PushService extends Service {
static Timer timer=new Timer();
//清除通知
public static void cleanAllNotification() {
NotificationManager mn= (NotificationManager) MainActivity.getContext().getSystemService(NOTIFICATION_SERVICE);
mn.cancelAll();
timer.cancel();
timer = null;
}
//添加通知
public static void addNotification(int delayTime,String tickerText,String contentTitle,String contentText)
{
if (null == timer ) {
timer = new Timer();
}
Intent intent = new Intent(MainActivity.getContext(), PushService.class);
intent.putExtra("delayTime", delayTime);
intent.putExtra("tickerText", tickerText);
intent.putExtra("contentTitle", contentTitle);
intent.putExtra("contentText", contentText);
MainActivity.getContext().startService(intent);
}
public void onCreate() {
Log.e("addNotification", "===========create=======");
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(final Intent intent, int flags, int startId) {
long period = 5*1000; //24小时一个周期
int delay=intent.getIntExtra("delayTime",0);
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
NotificationManager mn= (NotificationManager) PushService.this.getSystemService(NOTIFICATION_SERVICE);
String id = "channel_1"; //自定义设置通道ID属性
String description = "123";//自定义设置通道描述属性
int importance = NotificationManager.IMPORTANCE_HIGH;//通知栏管理重要提示消息声音设定
NotificationChannel mChannel = new NotificationChannel(id, "123", importance);//建立通知栏通道类(需要有ID,重要属性)
mChannel.setDescription(description); // 配置通知渠道的属性
mChannel.enableLights(true);// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.setLightColor(Color.RED);//设置闪灯颜色为红色
mChannel.enableVibration(true); // 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mn.createNotificationChannel(mChannel);////最后在notificationmanager中创建该通知渠道
Notification notification = new Notification.Builder(PushService.this, id)//创建Notification对象。
.setContentTitle("付款通知") //设置通知标题
.setSmallIcon(R.drawable.ic_launcher_background)//设置通知小图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background))//设置通知大图标
.setContentText("您已付款元")//设置通知内容
.setAutoCancel(true)//设置自动删除通知
.build();//运行
mn.notify((int) System.currentTimeMillis(),notification); //通知栏保留多条通知
}
},delay, period);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy(){
Log.e("addNotification", "===========destroy=======");
super.onDestroy();
}
}