I have a broadcast receiver as below
Test1.java
public class Test1 extends BroadcastReceiver implements Test2.Interfacetest {
private Test2 test2;
@Override
public void onReceive(Context context, Intent intent) {
test2 = new Test2(context);
}
@Override
public void interfaceTestMethod() {
//code
}
/*
Remaining code
*/
}
And have another class
Test2.java
public class Test2 {
private Interfacetest InterfacetestCommander;
public interface Interfacetest {
void interfaceTestMethod();
}
public Test2(Context context) {
InterfacetestCommander = (Interfacetest) context;
InterfacetestCommander.interfaceTestMethod();
}
/*
Remaining code
*/
}
When i try to initialise interface using broadcast receiver context, it gives following error
Process: in.ijasnahamed.interfaceTester, PID: 4452
java.lang.RuntimeException: Unable to start receiver in.ijasnahamed.interfaceTester.Test1: java.lang.ClassCastException: android.app.Application cannot be cast to in.ijasnahamed.interfaceTester.Test2$interfaceTestMethod
I need to know can an interface be initialized using broadcast receiver context? If yes, please tell me how?
N.B : My real code is little bit longer. So i just showed revelant code here with some simple classes and method names.
You shouldn't use
test2 = new Test2(context);
Because context is an instance of Context
,but Context
doesn't implement your interface,your Test1 class implement this interface,So you can add a parameter for your Test2 class like this:
public Test2(Context context, Interfacetest interfacetest) {
this.mContext = context; //if you don't need the context,just ignore it
this.InterfacetestCommander = interfacetest
}
and change
test2 = new Test2(context);
to
test2 = new Test2(context,this);