当我的应用程序正在运行或被最小化时,它运行正常。 但是,当应用关闭时,它无法正常工作。
我希望它即使在关闭时也可以工作.....请为此提出建议。
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();
}
}
权限 - >
<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"/>
接收者 - &gt;
<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>