When my app is running or is minimized, it is working fine. but when app is closed it doesn't work.
I want it to work even when it is closed.....please suggest help for this.
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver{
String str = "hello";
MainActivity main = new MainActivity();
@Override
public void onReceive(Context context, Intent intent) {
sendToMain(context,intent);
}
public void sendToMain(Context context,Intent intent){
Toast.makeText(context,"from receiver : "+str, Toast.LENGTH_SHORT).show();
Intent i = new Intent(context,MainActivity.class);
i.putExtra("msg",str);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TOP|intent.FLAG_ACTIVITY_NO_HISTORY| Intent.FLAG_ACTIVITY_SINGLE_TOP|intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.startActivity(i);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onNewIntent(Intent intent) {
Bundle extras = intent.getExtras();
sms = extras.getString("msg");
Toast.makeText(MainActivity.this, "from main activity :"+sms, Toast.LENGTH_SHORT).show();
}
}
Permissions ->
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Receiver -->
<receiver android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>