在broadcastReceiver中调用Main活动方法

时间:2016-07-29 16:53:44

标签: android

  

我希望在新的特定短信出现时显示从我的应用生成的通知。   所以通知生成方法是我的主要活动。当收到新的收入消息时,我必须生成通知。   这是我的BroadcastReceiver类。

公共类BroadCastReceiver扩展BroadcastReceiver {//私有AudioManager myAudioManager;

public MainActivity mainactivity = null;

public BroadCastReceiver() {
}

public void setMainactivityHandler(MainActivity mainn){
   this.mainactivity = mainn;
}



@Override
public void onReceive(Context context, Intent intent) {



    if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED") )
    {
        Toast.makeText(context, "SMS_RECEIVED", Toast.LENGTH_LONG).show();
        System.out.println("received sms");

        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Log.i("cs.fsu", "smsReceiver : Reading Bundle");

            Object[] pdus = (Object[])bundle.get("pdus");
            SmsMessage sms = SmsMessage.createFromPdu((byte[])pdus[0]);

            if(sms.getMessageBody().contains("aa")) {
                abortBroadcast();
                System.out.println("received correct");
                Log.e("tag", "corecttttttttttttttttttttttttttttttttttttttttttt");
                Toast toast = Toast.makeText(context, "BLOCKED Received SMS: ", Toast.LENGTH_LONG);
                toast.show();
                mainactivity.showNotification();
                abortBroadcast();






            }}
    }


}

}

  

这是我的主要活动

public class MainActivity extends Activity {

public BroadCastReceiver Br = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Br = new BroadCastReceiver();
    Br.setMainactivityHandler(this);
    IntentFilter callInterceptorIntentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(Br,  callInterceptorIntentFilter);


    // listener handler
    View.OnClickListener handler = new View.OnClickListener(){
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btnShowNotification:
                    showNotification();
                    break;

                case R.id.btnCancelNotification:
                    cancelNotification(0);
                    break;
            }
        }
    };

    // we will set the listeners
    findViewById(R.id.btnShowNotification).setOnClickListener(handler);
    findViewById(R.id.btnCancelNotification).setOnClickListener(handler);

}


public void showNotification(){

    Log.e("","show notification");
    // define sound URI, the sound to be played when there's a notification
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // intent triggered, you can add other intent for other actions
    Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
    PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

    // this is it, we'll build the notification!
    // in the addAction method, if you don't want any icon, just set the first param to 0
    Notification mNotification = new Notification.Builder(this)

            .setContentTitle("New Post!")
            .setContentText("Here's an awesome update for you!")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .setSound(soundUri)

            .addAction(R.drawable.ic_launcher, "View", pIntent)
            .addAction(0, "Remind", pIntent)

            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // If you want to hide the notification after it was selected, do the code below
    // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, mNotification);
}

public void cancelNotification(int notificationId){

    if (Context.NOTIFICATION_SERVICE!=null) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(notificationId);
    }
}

}

  

当新消息出现时会出现此错误

07-29 22:06:59.227  23021-23021/com.example.siluni.myapplication E/tag﹕ corecttttttttttttttttttttttttttttttttttttttttttt

07-29 22:06:59.267 23021-23021 / com.example.siluni.myapplication D / AndroidRuntime:关闭VM 07-29 22:06:59.277 23021-23021 / com.example.siluni.myapplication E / AndroidRuntime:FATAL EXCEPTION:main     处理:com.example.siluni.myapplication,PID:23021     java.lang.RuntimeException:无法启动接收器com.example.siluni.myapplication.BroadCastReceiver:java.lang.NullPointerException:尝试在null上调用虚方法'void com.example.siluni.myapplication.MainActivity.showNotification()'对象参考

1 个答案:

答案 0 :(得分:1)

这是因为当你的广播接收器执行你的MainActivity的方法时,你的活动可能没有运行甚至没有启动,所以会出现这种问题。

如何解决:

  1. 创建一个全局类。
  2. 如果您想要传递上下文,请将showNotification方法设为公共静态。 3.只需从主要活动和广播接收器中调用它。
  3. 如果你不能创建静态方法,那么只需创建该全局类的对象,然后使用object调用该方法。

    告诉我你在实施时是否遇到任何问题。