简体   繁体   中英

Running Android App in background or as a constant notification

I'm learning how to make apps for android and I have started by creating one which makes my phone scream when its dropped.

I got it working to where the phone screams when dropped, but now I need to make it so that the phone screams when dropped even when the app is closed, and to show a notification in the notification bar saying that its running

What should I use to do this? Should I use intentService? Ive been looking all over and I'm not sure where to look. Any guides would be appreciated

You need to make your service run in the foreground. You can achieve this by showing a notification when your service is running.

This is how you need to make your service run as foreground

private void showNotification(String title)
{
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(title);

    startForeground(1000,mBuilder.build());  // 1000 - is Id for the notification
}

You can also set your custom RemoteViews in notification using setContent

You can remove the service from foreground state using stopForeground

check Service Training .

For your use case it's important that it's an foreground service: Documentation Service

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