[英]How to show a notification even app is not running
我是android.i的初学者创建一个服务,在mainActivity上调用onCreat时显示通知
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent a = new Intent(this,myService.class);
startService(a);
}
}
这是我的服务类
public class myService extends Service{
private NotificationManager mManager;
@Override
public void onCreate() {
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
但我想如果我的应用程序没有运行我可以显示此服务,例如,如果我的手机时间大于9我只在一天中显示此通知一次。任何想法? 提前致谢
通知在后台运行,不需要运行应用程序。 虽然应用程序没有运行,但通知也有效,这是他们的主要任务。 我建议您使用Vogella的教程和文档:
http://www.vogella.com/tutorials/AndroidNotifications/article.html
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
您不希望在应用运行时显示通知。 这只是烦人的,并且(通常)没有意义。 当然也有例外。
如果要在特定时间显示通知,则应考虑使用AlarmManager 。
如果要从服务器或其他任何位置触发通知,请使用Google Cloud Messaging 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.