我一直在寻找并尝试不同的解决方案,但我似乎无法让它发挥作用。
我有一个带有列表和“添加”按钮的MainActivity。当我点击添加按钮时,我打开一个DialogFragment。在对话框中,用户输入数据并按“添加”,我想要一个通知,上面写着“xxxx已添加到列表中”,但它从未显示过。
我有一个AddDialog的单独类,如下所示:
public class AddDialogFragment extends DialogFragment {
Button btnAdd;
Button btnCancel;
TextView etNewSerial, etNewBrand, etNewModel;
String newSerial, newBrand, newModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.dialog_add, container, false);
getDialog().setTitle("Add new serial!");
btnAdd = (Button) rootView.findViewById(R.id.btnAddNew);
etNewSerial = (TextView) rootView.findViewById(R.id.etNewSerial);
etNewBrand = (TextView) rootView.findViewById(R.id.etNewBrand);
etNewModel = (TextView) rootView.findViewById(R.id.etNewModel);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
newSerial = etNewSerial.getText().toString();
newBrand = etNewBrand.getText().toString();
newModel = etNewModel.getText().toString();
String url = "MY_VOLLEY_URL"
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
int icon = 0;
CharSequence notiText = "Item Added!";
long notiTime = System.currentTimeMillis();
CharSequence notiTitle = "Item Added!";//Titel
CharSequence notiContent = newSerial + " added!";
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notBuilder = new NotificationCompat.Builder(getActivity());
notBuilder.setSmallIcon(icon)
.setTicker(notiText)
.setWhen(notiTime)
.setAutoCancel(true)
.setContentText(notiContent)
.setContentTitle(notiTitle)
.setContentIntent(pendingIntent);
Notification notification = notBuilder.build();
NotificationManager myNotificationManager = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationManager.notify(1, notification);
getDialog().dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(request);
}
});
return rootView;
}
}
但通知从未显示过。我一直试图用不同的上下文方法替换“getActivity()”,但似乎并不重要。有没有人有一些提示可以做到这一点?
答案 0 :(得分:0)
我想知道您收到此错误是因为您正在将0
作为resourceId
传递给小图标(setSmallIcon
)。也许,NotificationManager
忽略了此通知,因为它无法正确构建(没有0
作为ID的资源。
所以,试着改变一下:
notBuilder.setSmallIcon(icon)
....
要:
notBuilder.setSmallIcon(android.R.color.transparent)
....
我使用android.R.color.transparent
作为示例,因为您对展示任何图标都不感兴趣。但你可以换成任何颜色/可绘制等......