在没有GCM / Firebase的情况下关闭应用时运行Android通知

时间:2017-03-25 16:38:51

标签: android service push-notification background-process android-intentservice

我正在开发一个我希望显示推送通知的应用。请注意,由于我的客户要求不使用任何第三方服务,因此使用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设置中转到我的正在运行的应用程序,我将能够看到此服务正在运行。但我无法找到任何此类服务。

现在问题是当我关闭我的应用程序时,通知也会消失。我希望它一直持续到用户采取任何行动。

除此之外,即使应用程序未启动,我也希望此服务从手机启动开始。

1 个答案:

答案 0 :(得分:0)

1)向清单添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2)在清单中添加一个接收器以便在启动时运行:

<receiver android:name="com.example.MyBroadcastReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>  
</receiver>

在MyBroadcastReceiver.java中:

package com.example;

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, MyService.class);
        context.startService(startServiceIntent);
    }
}
相关问题