java - 从从操作按钮接收的广播接收器调用在前台服务中运行的 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() 中放置一个非静态方法。我怎样才能做到这一点?
解决方案
推荐阅读
- three.js - A-Frame:无法成功设置场景子对象的世界位置
- android - 如何为 Exoplayer 调整 Firebase 存储 URL?
- javascript - 如何使火箭/月球绕地球轨道运行three.js
- javascript - 如何处理点击 Bulma 的下拉组件?
- ansible - 当列表中有多个字符串时,Ansible 字典不起作用
- java - Tomcat server reaching a websocket limit of 2000 connections
- php - 通过 PHP API 和 meertensm/amazon-mws 包更新亚马逊 MWS 上的产品
- javascript - 如何转换不确定数量的输入字符串?
- pyspark - 随机森林允许的最大深度是多少?我正在使用 Spark ML
- r - 从栅格中提取值并附加到现有数据框