Call an Android main activity function that is running in a foreground service from a broadcast receiver that was received from an Action Button?

2020-02-15 java android notifications broadcastreceiver foreground-service

I am having a very hard time to communicate from a broadcast receiver to a foreground service main activity. All I want to do is take what I got from the broadcast receiver and call A function that is running in a foreground service. I am trying not to use a static method because I need to call a method that can not be static. And If I try and make an instance of the class I get an error because the class might not be running. Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference Is there another way to do this? Maybe I'm thinking about this in the complete wrong way. I have a Main Class, Service Class, and a broadcast receiver class. Anything would help. Thank you!

AppService.java

    public class AppService extends Service
{

public int onStartCommand(Intent intent,int flags, int startId)
{
     Intent notificationIntent = new Intent(this,MapsActivity.class);
     PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);

     Intent ActionCancelIntent = new Intent(this,ActionCancelReceiver.class);

     PendingIntent CancelIntent = PendingIntent.getBroadcast(this,1,ActionCancelIntent,PendingIntent.FLAG_UPDATE_CURRENT);

     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID)
                .setContentTitle(TopText)
                .setContentText(BottomText)
                .setSmallIcon(R.drawable.ic_map_marker)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setOngoing(true)
                .setColor(Color.GREEN)
                .addAction(R.drawable.ic_map_marker,CancelName,CancelIntent);

        startForeground(1,notificationBuilder.build());

     return START_NOT_STICKY;
}
}

ActionCancelReceiver.java

public class ActionCancelReceiver extends BroadcastReceiver
{

    public String TAG = "MyApp";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.e(TAG, "Clicked Cancel");

        CancelActionButton();

        Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.sendBroadcast(it);
    }

}

MapsActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{

    public static final String TAG = "MyApp";

 public static void CancelActionButton()
{
    Log.d(TAG,"CancelActionMain");
}

This code works and prints out CancelActionMain but I want to put a nonstatic method in CancelActionButton(). How can I do this?

Answers

Related