编辑 1
我需要从 BroadcastReceiver 调用一个方法,并且该方法存在于下面提到的 Activity 类中。
我尝试了这段代码,并得到了NULL_POINTER_EXCEPTION
创建 MainActivity 类的引用的位置。
纠正我我做错了什么?
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void myTesting(){
Toast.makeText(MainActivity.this, "Welcome to Activity", Toast.LENGTH_SHORT).show();
}
}
广播接收器.java
public class BootCompeteReceiver extends BroadcastReceiver {
public Context mContext;
private MainActivity mainActivity;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
try {
mainActivity = new MainActivity();
mainActivity.myTesting();
} catch (Exception e) {
Toast.makeText(context, ""+e, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}