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