gpt4 book ai didi

java - 从其他类(扩展广播接收器)调用 MainActivity 方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:46 25 4
gpt4 key购买 nike

我正在尝试从其他类 (PhoneStateReceiver) 调用 MainActivity 的方法 display_notification。

但是出现了这个错误:

java.lang.RuntimeException: Unable to start receiver com.weekendproject.roshu.spamblocker.PhoneStateReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

MainActivity 中专门针对这一行错误指出

Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);

但是我尝试将 getApplicationContext() 更改为 "this""getActivity()",但它不起作用

这是完整代码

MainActivity.java

public class MainActivity extends ActionBarActivity {

public void display_notification(String incoming_number) {

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_action)
.setContentTitle("SpamBlocker alert !!")
.setContentText("SpamBlocker blocked number : " + incoming_number);

// **Error occured in following line**
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Random r = new Random();
int rand = r.nextInt(1000);
mNotificationManager.notify(rand, mBuilder.build());
}
}

PhoneStateReceiver.java

public class PhoneStateReceiver extends BroadcastReceiver {

MainActivity mActivity;

@Override
public void onReceive(Context context, Intent intent) {
mActivity = new MainActivity();
mActivity.display_notification(incomingNumber); // call main activity methods

}
}

最佳答案

使用这个:

    Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

关于java - 从其他类(扩展广播接收器)调用 MainActivity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com