0

I have notification, and on click notification should be put values using intent. This value should be receive in BroadcastReceiver in other Activity. Any help how it fix? Below there is my code:

public void showNotification(){
        Intent intent = new Intent(MainActivity.ACTION_NEW_MSG);
        intent.putExtra(MainActivity.MSG_FIELD, "TEST VALUES");
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        ComponentName cn = new ComponentName(getApplicationContext(), MainActivity.class);
        intent.setComponent(cn);
        sendBroadcast(intent);
        contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);


     notification = new NotificationCompat.Builder(getApplicationContext())
                    .setCategory(Notification.CATEGORY_PROMO)
                    .setContentTitle("TEST VALUE")
                    .setContentText("Please click for")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setAutoCancel(false)
                    .setVisibility(1)
                    .setSubText("Time left: " + millisUntilFinished/1000)
                    .addAction(android.R.drawable.ic_menu_view, "View details", contentIntent)
                    .setContentIntent(contentIntent)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setVibrate(new long[]{0}).build();
            notificationManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            int notification_id = 666;
            notificationManager.notify(notification_id, notification);
        }

And below MainActivity:

    private void initReceiver() {
    myReceiver = new MyReceiver();
    IntentFilter filter = new IntentFilter(ACTION_NEW_MSG);
    registerReceiver(myReceiver, filter);
}

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_NEW_MSG)) {
            String message = intent.getStringExtra(MSG_FIELD);
            Toast.makeText(getApplicationContext(),message, Toast.LENGTH_LONG).show();
            Log.e("TESTING", "TESTING");
        }
    }
}
user5523912
  • 1
  • 1
  • 3

1 Answers1

0

Why don't you use a service instead of a reciever ? You can create the intent like this : Intent i = new Intent(MainActivity.this, MyService.class); You can put extras and actions in the intent. In the Service class just override this function :

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        if (intent != null) {
            final String action = intent.getAction();
        }
    }
Quentin Menini
  • 160
  • 1
  • 1
  • 12