本文介绍了在不使用意图的情况下访问广播收件人中的主要活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我陷入了困境.我有一个广播接收器,它调用类的方法将上下文和构造函数中的主要活动引用一起使用.我不知道如何访问广播接收器中的主要活动.这是我的代码:
I am stuck in a problem. I have a broadcast receiver that calls the method of class takes in context and main activity reference in constructor. I dont know how to access main activity in broadcast receiver.Here is my code:
public void onReceive(@NonNull Context context, @NonNull Intent intent) {
if (context == null) {
throw new IllegalArgumentException();
}
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
Class myclass = new Class(context,mainactivity reference); //dont know how to get main activity here
}
}
}
}
是否有任何方法可以在没有Intent的情况下获得它,或者有其他方法.我正处于学习阶段,将不胜感激.
Is there is any way that I can get it without Intent or there is some other method. I am in learning phase any help will be appreciated.
清单中
<receiver android:name="myreceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
推荐答案
Try this hope it works:
in Main Activity:
public class MainActivity extends Activity {
public static MainActivity getInstance() {
return new MainActivity();
}
}
And in your receiver:
MainActivity reference=MainActivity.getInstance();
这篇关于在不使用意图的情况下访问广播收件人中的主要活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!