Search code examples
androidsmsbroadcastreceiver

Why didn`t it work the imported function in SMSReceived from MainActivity?


Can you tell me please why didn't it work the imported function in SMSReceived from MainActivity.

package com.example.smarthome;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {
    MainActivity MainActivityObject=new MainActivity();
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle != null){
            Toast.makeText(context, "NewSMS", Toast.LENGTH_LONG).show();
            MainActivityObject.AfisareStareLed();
            }
}
}

The function from MainActivity is:

protected void AfisareStareLed() {
    TextView view = new TextView(this);
    Uri uriSMSURI = Uri.parse("content://sms/inbox");
    Cursor cursor = getContentResolver().query(uriSMSURI, null, null, null, null);
    while (cursor.moveToNext()){ 
        if(cursor.getString(2).equals(number) && cursor.getString(8).equals("0")){
            if(cursor.getString(13).endsWith("aprins") || cursor.getString(13).endsWith("stins")){
                TextView textStareLed = (TextView) findViewById(R.id.textStareLed);
                textStareLed.setText(cursor.getString(13));
                break;
            }
        }
      }
      markMessageRead();    
}

P.S. I want to make a function which should modify a TextView when I receive an SMS.


Solution

  • You cannot create an instance of an Activity yourself, like you are doing in onReceive():

    MainActivity MainActivityObject=new MainActivity();
    

    Only the Android framework can create an instance of an Activity correctly, as it needs to have the Context set up properly and the Android framework does this.

    In your Activity you can create an instance of your BroadcastReceiver (you can use an inner class of your Activity) and register that using registerReceiver(). Then, in onReceive() you will have access to methods of the Activity and you can call one to update the UI.