通知的安卓代码:
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;
在状态栏不显示此消息:
1.若是真机 看有没有给此应用程序开通 状态栏与通知 (在设置里)权限有没有开通
2.看有没有设置图标setSmallIcon()和setLargeIcon()一个是设置小图标(注意只有使用纯的alpha图层图片设置),第二个是显示大图标,下拉系统状态栏就可以看到设置的大图标
本文介绍了在Android中创建消息通知的代码示例,并针对服务和服务启动方式进行了说明。当通知在状态栏不显示时,提供了两种可能的原因:1) 检查应用程序是否已获得状态栏和通知权限;2) 确保正确设置了setSmallIcon和setLargeIcon,以显示小图标和大图标。
182

被折叠的 条评论
为什么被折叠?



