[英]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.