我有一个Android应用程序,我需要在他运行特定活动时对用户进行通知,发生了什么事。
通知不会为我完成工作,因为我需要通过Dialog通知用户,将数据发送到服务器并启动另一个活动......我的意思是,我知道当这个消息发送时,用户将使用该应用程序并查看属于我要发送消息的acrivity的屏幕。
该消息应由GCM服务触发。 我已经完成了接收消息的所有事情,目前我的GcmIntentService正常工作(this链接后)。
现在,我试图通过在其中定义一个Handler来向活动发送一条消息:
public Handler _handler = new Handler() {
@Override
public void handleMessage(Message msg) {
我在这里有两个问题:
1)我真的不知道这个Handler是否会在实际运行活动中被触发
2)在这个“handleMessage”事件中,我没有运行活动的上下文,所以我不能,例如,上升一个AlertDialog(我得到NullPointerException)
我怎样才能做到这一点?我是否应该重新考虑服务和活动之间的沟通?
谢谢!
答案 0 :(得分:0)
在android中通知用户的标准方法:This
检查代码:
public void sendNotification(String msg) {
mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, returnClass), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context)
.setSmallIcon(R.drawable.notification)
.setContentTitle(
context.getResources().getString(R.string.app_name))
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
对于你的问题2-
在此" handleMessage"事件我没有运行活动的上下文,所以我不能上升一个AlertDialog(我得到NullPointerException)
您可以将其用作上下文的参考(GcmService.this)
希望有帮助