【发布时间】:2017-12-09 07:50:54
【问题描述】:
所以我想制作这个接收 SMS 文本的应用程序,当它接收到 SMS 文本时,它会显示一个通知,当用户单击它时,会弹出一个带有 SMS 消息的新活动。因此,如果它像用于接收 SMS 文本的 BroadcastReceiver 类那样完成,并且它显示一个通知,一切都很好而且花花公子。
public class SMSReceiver extends BroadcastReceiver {
static final int notificationId = 1;
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
newNotification(context, phoneNumber, message);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void newNotification(Context context, String title, String text) {
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(context, NotificationActivity.class);
notifyIntent.putExtra("SMSText", text);
notifyIntent.setAction(text);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentIntent(contentIntent)
.setContentText(text)
.setContentTitle(title)
.setTicker(text)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notifyMgr.notify(notificationId, notification);
}
}
唯一的问题是当我点击通知时。第一次完美运行时,会弹出 NotificationActivity 类,显示 SMS 消息。但在那之后,信息永远不会更新。我假设应用程序意识到它已经打开了 NotificationActivity,所以它不会打开另一个。即使我在创建新通知时正确添加了标志FLAG_ACTIVITY_NEW_TASK。这也是我的 NotificationActivity 类
public class NotificationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
newString = null;
} else {
newString = extras.getString("SMSText");
}
} else {
newString = (String) savedInstanceState.getSerializable("SMSText");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(newString);
}
}
我也有一个启动器活动,MainActivity,但觉得没有必要展示,因为它所做的只是注册 SMSReceiver。任何帮助将不胜感激,谢谢!
【问题讨论】:
-
查看我的更新答案
标签: android android-intent android-activity android-notifications