【发布时间】:2014-09-25 06:54:51
【问题描述】:
我是 Parse 的新手,并且制作了一个接收推送通知的应用程序。我有一个 json 有效负载,我将其发送到包含 URL 的应用程序。当设备收到推送通知时,会出现一个带有“取消”和“确定”按钮的警报对话框。如果用户按下“确定”,则加载网页。
当应用程序在设备上打开时,这可以正常工作,但当应用程序在设备上未打开时会失败。通知仍然出现,当它在后台时,用户可以单击它打开应用程序,但屏幕上不会出现对话框。如果应用程序完全关闭,那么我会看到一个弹出窗口告诉我应用程序已崩溃,但随后应用程序将加载但屏幕上不会显示任何对话框。这是我的接收器的样子:
public class MyCustomReceiver extends BroadcastReceiver {
private static final String TAG = "MyCustomReceiver";
public static final String ACTION = "custom_action_name";
@Override
public void onReceive(Context context, Intent intent) {
try {
...
...
Iterator itr = json.keys();
while (itr.hasNext()) {
String key = (String) itr.next();
...
if (key.equals("targetUrl")){
MainActivity.showdialog(json.getString(key));
}
...
}
String message = json.getString("alert");
} catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
}
所以当迭代器点击targetUrl键时,会调用showdialog()方法并传入url。
这是我的 showdialog 方法,在我的 MainActivity 类中找到:
public static void showdialog(final String url){
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Title");
alert.setMessage("Message");
alert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
}
});
alert.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.show();
}
再次 - 当应用程序打开时这工作正常,但如果应用程序关闭则失败。如何让用户通过通知打开应用并看到此对话框?
如果应用程序已关闭并且我尝试通过推送通知打开,这是错误堆栈:
FATAL EXCEPTION: main
Process: ././., PID: 30566
java.lang.RuntimeException: Unable to start receiver ././.MyCustomReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2856)
at android.app.ActivityThread.access$1700(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:360)
at ././.MainActivity.showdialog(MainActivity.java:140)
at ././.MyCustomReceiver.onReceive(MyCustomReceiver.java:34)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2845)
【问题讨论】: