简体   繁体   中英

How to show a notification even app is not running

i'm beginner in android.i create a service to show a notification when onCreat on mainActivity called

    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);
    }

}

here is my service class

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);
 }

but i want if my app is not running i can show this service for example if my phone time is bigger than 9 i show this notification only one time in a day.any ideas ? thanks in advance

Notifications are running on background and application running is not needed. While application is not running, notifications also work and this is the main mission of them. I suggest you Vogella's tutorial and documentation:

http://www.vogella.com/tutorials/AndroidNotifications/article.html

http://developer.android.com/guide/topics/ui/notifiers/notifications.html

  1. You don't want to show notifications while your app is running. That is just annoying and has (usually) no point. There are of course exceptions.

  2. If you want to show a notification at a specific time, you should consider to use the AlarmManager .

  3. If you want to trigger the notification from a server or wherever else, use Google Cloud Messaging .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM