Search code examples
javaandroidkotlinandroid-notificationsandroid-push-notification

Create PendingIntent for notification without specifying activity


Is there any way to create PendingIntent for notification or to show notification from "data" layer.

In that layer I don't have activity class.

So can Intent automatically choose one activity that is marked like "default" or "launcher"?

        <activity
            android:name=".feature.splash.SplashActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Solution

  • You can use PendingIntent.getBroadcast() :

     Intent broadcastIntent = new Intent(mContext, NotificationReceiver.class);
     broadcastIntent.putExtra(Const.NOTIFICATION_ID,"1";
     PendingIntent cancleIntent = PendingIntent.getBroadcast(mContext,
                0, broadcastIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    
    public class NotificationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.hasExtra(Const.NOTIFICATION_ID)) {
            int notificationId = intent.getIntExtra(Const.NOTIFICATION_ID, 0);
    
           // do your logic like cancle notification
             NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                manager.cancel(notificationId);
    
        }
    
    
    }
    }