I want to do the exact same thing mentioned in the question in the following link Call an activity method from a BroadcastReceiver class. But solution given there is not working for me and I can't comment there as I don't have enough reputation. I did everything mentioned in the solution but my broadcast receiver is not working with that code.
I just want to call the method in the activity on receiving the broadcast request without creating an instance of the activity. Can it be done?
EDIT: Now I am adding the code.
Here is my MainActivity class
public class MainActivity extends Activity {
public static final String TAG="App1";
private ActionReceiver receiver = null;
//private YourBroadcastReceiverClassName yourBR = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// receiver= new ActionReceiver();
//IntentFilter filter = new IntentFilter();
//filter.addAction("com.example.app1.printSomething");
// printSomething();
}
public void printSomething(){
Toast.makeText(this,"Hello World",Toast.LENGTH_LONG);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my ActionReceiver class which is BroadcastReceiver
public class ActionReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if("com.example.app1.printSomething".equalsIgnoreCase(intent.getAction()))
Toast.makeText(context,"Hello World", Toast.LENGTH_LONG).show();
}
}
This is my
AndroidManifest.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.app1.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ActionReceiver">
<intent-filter>
<action android:name="com.example.app1.printSomething"/>
</intent-filter>
</receiver>
</application>
</manifest>
Now, I want to call printSomething()
Method written in MainActivity
from onReceive()
in ActionReceiver
class. But I don't want to launch MainActivity
for that. Can it be done?