0
我需要你们所有人的意见。当GCM监听器触发时,只加载回收站视图
情况是,当推送通知GCMListener被触发时,NewBookingActivity会加载。由于我使用的是recyler视图,所以片段和适配器已经实现。 它将出现在回收站视图中,因为预订可能不止一个。
问题是每当触发新的推送通知活动将重叠。我知道这会发生,因为我称之为活动。
我想只创建GCMListener触发时加载的回收视图?
任何帮助表示赞赏和非常感谢。
MyGcmListenerService.java
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
private static final String MyPREFERENCES = "xxxxx";
private static final String JOB_KEY = "xxx";
private String JobStatus;
int countNotification = 0;
/**
* Called when message is received.
*
* @param from SenderID of the sender.
* @param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
sendNotification(message);
}
private void sendNotification(String message) {
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
JobStatus = sharedPreferences.getString(JOB_KEY, "");
if (message.contains("#01") && JobStatus.equalsIgnoreCase("true")){
Intent launch = new Intent(Intent.ACTION_MAIN);
launch.setClass(getApplicationContext(), NewBookingActivity.class);
launch.addCategory(Intent.CATEGORY_LAUNCHER);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
}
}
NewBookingActivity.java
public class NewBookingActivity extends AppCompatActivity {
private static final String TAG = "NewBookingActivity";
@Override
protected void onCreate (Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.list_job);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.red_dark));
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
singleton = VolleySingleton.getInstance();
requestQueue = singleton.getRequestQueue();
//Initializing job list
listJob = new ArrayList<>();
//Enable the activity when lock
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//Calling method to get data to fetch data
getData();
//Alert Sound
SoundNotification();
}
//This method will get data from the web api
private void getData() {
StringRequest jsObjRequest = new StringRequest(Request.Method.POST, sendURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
parseResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError response) {
Log.d(TAG + " Error Response: ", response.toString());
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("imei", imei);
//returning parameter
return params;
}
};
requestQueue.add(jsObjRequest);
}
private void parseResponse(String response){
if(response==null || response.length()==0){
return;
}
try{
JSONObject jObjstats = new JSONObject(response);
status = jObjstats.getString(Keys.EndPoint.KEY_RETURN);
if (!status.equalsIgnoreCase("success")){
reason = jObjstats.getString(Keys.EndPoint.KEY_RETURN);
if (reason.equalsIgnoreCase("No Customers Found")) {
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
Toast.makeText(this, "No booking at current time", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No booking at current time", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "No booking at current time", Toast.LENGTH_SHORT).show();
}
}
else if(status.equalsIgnoreCase("success")){
order = jObjstats.getString(Keys.EndPoint.KEY_ORDER);
JSONArray jArray = new JSONArray(order);
for(int i = 0; i<jArray.length(); i++) {
Job setJob = new Job();
JSONObject json = null;
try {
json = jArray.getJSONObject(i);
setJob.setBookingRef(json.getString("booking_ref"));
setJob.setFromPoint(json.getString("from_point"));
setJob.setDestPoint(json.getString("dest_point"));
} catch (JSONException e) {
Log.i(TAG, "3");
e.printStackTrace();
}
listJob.add(setJob);
}
Log.i(TAG, "4");
//Finally initializing our adapter
adapter = new NewBookingAdapter(listJob, this);
//Adding adapter to recycler view
recyclerView.setAdapter(adapter);
}
}catch(Exception e) {
Log.i(TAG, e.getMessage());
}
}
private void SoundNotification(){
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
catch (Exception e) {
e.printStackTrace();
}
}
NewBookingFragment.java
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
Log.i(TAG, "onCreate");
recyclerView = (RecyclerView) inflater.inflate(R.layout.list_job, container, false);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
myApp = ((MyApplication) getActivity().getApplicationContext());
imei = myApp.getImei();
mainURL = myApp.mainURL;
taskURL = getResources().getString(R.string.task_pending_job);
sendURL = mainURL+taskURL;
singleton = VolleySingleton.getInstance();
requestQueue = singleton.getRequestQueue();
//Initializing job list
listJob = new ArrayList<>();
return recyclerView;
}
}
NewBookingAdapter
public class NewBookingAdapter extends RecyclerView.Adapter<NewBookingAdapter.ViewHolder> {
//Constructor of this class
public NewBookingAdapter(List<Job> Job, Context context){
super();
//Getting all
this.Job = Job;
this.context = context;
}
public class ViewHolder extends RecyclerView.ViewHolder{
//Views
public TextView tvFromPoint, tvDestPoint, tvPickupDate, tvPickupTime, tvServiceType, tvTips;
public FloatingActionButton FABserviceType;
public AppCompatButton btnDecline, btnAccept;
public RelativeLayout mainLayout;
public final View mView;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
FABserviceType = (FloatingActionButton) itemView.findViewById(R.id.serviceType);
tvServiceType = (TextView) itemView.findViewById(R.id.tvServiceType);
tvFromPoint = (TextView) itemView.findViewById(R.id.tvFromPoint);
tvDestPoint = (TextView) itemView.findViewById(R.id.tvDestPoint);
tvPickupDate = (TextView) itemView.findViewById(R.id.tvPickupDate);
tvPickupTime = (TextView) itemView.findViewById(R.id.tvPickupTime);
tvTips = (TextView) itemView.findViewById(R.id.tvTips);
btnAccept = (AppCompatButton) itemView.findViewById(R.id.btnAccept);
btnDecline = (AppCompatButton) itemView.findViewById(R.id.btnDecline);
mainLayout = (RelativeLayout) itemView.findViewById(R.id.mainLayout);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_new_booking, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
singleton = VolleySingleton.getInstance();
requestQueue = singleton.getRequestQueue();
myApp = ((MyApplication) context.getApplicationContext());
imei = myApp.getImei();
mainURL = myApp.mainURL;
taskURL = context.getResources().getString(R.string.task_pickcustomer);
sendURL = mainURL+taskURL;
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
final Job job = Job.get(position);
//Showing data on the views
if(job.getServiceType().equalsIgnoreCase("101") && job.getTaxiTypeID().equalsIgnoreCase("1")){
//--budget icon
holder.FABserviceType.setImageResource(R.drawable.car_budget);
}
else if(job.getServiceType().equalsIgnoreCase("101") && job.getTaxiTypeID().equalsIgnoreCase("0")){
//--teks1m icon
holder.FABserviceType.setImageResource(R.drawable.car_teks1m);
}
holder.tvServiceType.setText(job.getServiceType());
holder.tvFromPoint.setText(job.getFromPoint());
holder.tvDestPoint.setText(job.getDestPoint());
holder.tvPickupDate.setText(job.getPickupDate());
holder.tvPickupTime.setText(job.getPickupTime());
holder.tvTips.setText("Tips : RM "+job.getTips());
holder.btnAccept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ErrDialog(job.getBookingRef(), "Are you sure want to ACCEPT this job ?", "Yes", "No", v, position);
}
});
holder.btnDecline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ErrDialog(job.getBookingRef(), "Are you sure want to DECLINE this job ?", "Yes", "No", v, position);
}
});
}
@Override
public int getItemCount() {
return Job.size();
}
private void AcceptBooking(final String bookingRef, final int position){
StringRequest jsObjRequest = new StringRequest(Request.Method.POST, sendURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
parseResponse(response, position);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "Volley "+error.toString());
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("imei", imei);
params.put("booking_ref", bookingRef);
//returning parameter
return params;
}
};
//requestQueue = Volley.newRequestQueue(context);
requestQueue.add(jsObjRequest);
}
private void parseResponse(String response, int position){
if(response==null || response.length()==0){
return;
}
try {
JSONObject jObjstats = new JSONObject(response);
status = jObjstats.getString(Keys.EndPoint.KEY_RETURN);
if (status.equalsIgnoreCase("error")){
error = jObjstats.getString(Keys.EndPoint.KEY_REASON);
}
if (status.equalsIgnoreCase("success")){ //success == active
Toast.makeText(context, "Congratulations, you get the job \n Please call customer", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
else{
Toast.makeText(context, "Didnt get the job", Toast.LENGTH_LONG).show();
Log.i(TAG, "Didnt get the job:" + status);
removeAt(position);
}
Log.i(TAG, "Login : " +status+ " " +position);
}
catch (Exception ex){
Log.i(TAG, "Catch Error:" +ex);
}
}
public void removeAt(int position) {
if(Job.size() == 1 && position == 0) {
System.exit(0);
}
else {
Job.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, Job.size());
}
}
private void SavePreferences(String key, String value){
sharedPreferences = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
请您详细说明意图,因为我仍然需要致电活动权利? – Nizzam
@SendraFalvia如果已经运行,不需要调用'startActivity()'。你将简单地创建一个intent,把数据放入它并通过'sendBroadcast()'发送这个intent。正如我们在Fragment的课上写了BroadCastReceiver一样,这里会收到广播的意图。然后从意图中提取数据,将其添加到适配器并调用notifyDataSetChanged()。我已经更新了我的答案...检查出来。 –
我没有这么做:( – Nizzam