首页 > 解决方案 > 从从操作按钮接收的广播接收器调用在前台服务中运行的 Android 主要活动功能?

问题描述

我很难从广播接收器与前台服务主要活动进行通信。我想要做的就是从广播接收器中获取并调用在前台服务中运行的函数。我试图不使用静态方法,因为我需要调用一个不能是静态的方法。如果我尝试创建一个类的实例,我会收到一个错误,因为该类可能没有运行。Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference还有另一种方法可以做到这一点吗?也许我正在以完全错误的方式思考这个问题。我有一个主类、服务类和一个广播接收器类。任何事情都会有所帮助。谢谢!

应用服务.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");
}

此代码有效并打印出 CancelActionMain,但我想在 CancelActionButton() 中放置一个非静态方法。我怎样才能做到这一点?

标签: javaandroidnotificationsbroadcastreceiverforeground-service

解决方案


推荐阅读