通知的安卓代码:
public class MyService extends Service { … public void onCreate() { super.onCreate(); Log.d(“Myservice”, "onCreate execute "); Intent intent = new Intent(this,MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this,0,intent,0); Notification notification =new NotificationCompat.Builder(this) .setContentTitle(“This is content title”) .setContentTitle(“This is content text”) .setTicker(“You have import thing to do it”) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)) .setContentIntent(pi) .build(); startForeground(1,notification); } }
这是安卓的服务中的代码,在活动MainActivity内要启动MyService:
case R.id.button2: Intent intent = new Intent(this, MyService.class); startService(intent); break;
或者直接按钮的点击事件中显示通知:
case R.id.show: Intent intent1 = new Intent(this,MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this,0,intent1,0); NotificationManager manager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification = null; notification =new NotificationCompat.Builder(this) .setContentTitle(“This is content title”) .setContentTitle(“This is content text”) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)) .setContentIntent(pi) .build(); manager.notify(2,notification); break;