【发布时间】:2017-03-25 16:38:51
【问题描述】:
我正在开发一个要显示推送通知的应用程序。请注意,由于我的客户要求不使用任何第三方服务,因此使用 GCM/Firebase 是不可能的。
我可以使用以下代码成功显示来自服务的通知。
public class SendNotificationService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
CharSequence title = "Notification Title";
CharSequence message = "This is a test notification.";
Drawable drawable= ContextCompat.getDrawable(this,R.drawable.brand_icon_color);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.brand_icon_small_color)
.setLargeIcon(bitmap)
.setAutoCancel(true)
.setContentTitle(title)
.setOngoing(false);
mBuilder.setContentText(message);
mBuilder.setTicker(message);
mBuilder.setWhen(System.currentTimeMillis());
NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
mBuilder.setContentIntent(pendingIntent);
notificationManager.notify(0, mBuilder.build());
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
}
}
我正在通过我的 AsyncTask onPostExecute 方法启动此服务。
Intent intentService = new Intent(context, SendNotificationService.class);
context.startService(intentService);
我根据一些教程创建了这个,发现如果我在 Android 设置中转到我的正在运行的应用程序,我将能够看到这个服务正在运行。但我找不到任何此类服务。
现在的问题是当我关闭我的应用程序时,通知也会消失。我希望它一直存在,直到用户采取任何行动。
除此之外,我希望此服务在手机启动时启动,即使应用程序未启动。
【问题讨论】:
-
检查一下以在启动时运行您的服务:stackoverflow.com/questions/2784441/…
-
“我想显示推送通知”——您的代码中没有任何内容与此有关。 “当我关闭我的应用程序时”——请详细说明您的意思。
-
在代码中我可以显示通知。如果我能够在后台运行此服务,如何推送此通知不是挑战。关闭应用程序的意思是当我简单地从最近的应用程序中滑动应用程序或点击 X 以关闭它时,通知会从通知栏中消失。
-
实施@zed解决方案后,我可以在App的权限中看到“启动时运行”。但是启动时没有任何运行。为了简单起见,我现在只是在 onStartCommand 上显示一条 Toast 消息。
-
不清楚你的意思。您需要实现一个推送通知系统。您的服务必须通过 websocket 连接到您的服务器,然后您的服务器可以开始向连接的客户端(服务)推送消息。
标签: android service push-notification background-process android-intentservice