Android Application crashing on phone call

时间:2018-06-04 16:55:51

标签: java android textview broadcastreceiver android-context

a newbie in java and Android Studio here. I'm trying to set TextView to some value when the phone is detected.My application crushes every time on incoming call, i tried many things but nothing works. Maybe I'm passing context incorectly?

I'm using code posted by Gabe Sechan here: How to detect incoming calls, in an Android device?

MainActivity:

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static Context mContext;
    public static Context getContext() {
        return mContext;
    }
    public void setContext(Context mContext) {
        this.mContext = mContext;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Context c = MainActivity.getContext();
        TextView textView;
        new CallReceiver(c);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=(TextView)findViewById(R.id.textView1);
    }
}

CallReceiver:

import java.util.Date;
import android.content.Context;
import android.widget.TextView;

public class CallReceiver extends PhonecallReceiver {
    Context context;
    TextView textView;
    public CallReceiver(){}
    public CallReceiver(Context context)
    {
        this.context=context;
    }

    @Override
    protected void onIncomingCallReceived(Context ctx, String number, Date start)
    {
        textView=(TextView)((MainActivity)context).findViewById(R.id.textView1);
        textView.setText("SOMETHING");
    }

    @Override
    protected void onIncomingCallAnswered(Context ctx, String number, Date start)
    {
        textView=(TextView)((MainActivity)context).findViewById(R.id.textView1);
        textView.setText("SOMETHING");
    }

    @Override
    protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
    {
        textView=(TextView)((MainActivity)context).findViewById(R.id.textView1);
        textView.setText("SOMETHING");
    }

    @Override
    protected void onOutgoingCallStarted(Context ctx, String number, Date start)
    {
        textView=(TextView)((MainActivity)context).findViewById(R.id.textView1);
        textView.setText("SOMETHING");
    }

    @Override
    protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end)
    {
        textView=(TextView)((MainActivity)context).findViewById(R.id.textView1);
        textView.setText("SOMETHING");
    }

    @Override
    protected void onMissedCall(Context ctx, String number, Date start)
    {
        textView=(TextView)((MainActivity)context).findViewById(R.id.textView1);
        textView.setText("SOMETHING");
    }
}

0 个答案:

没有答案