无法再次向发件人发送通知以便在android中进行确认

时间:2016-01-22 20:04:47

标签: android google-cloud-messaging android-notifications

我是android的新手,我正在开发一个android项目,其中发送通知是该项目的功能。当用户收到通知时,每个工作正常的通知已成功发送和接收它打开一个对话框。在对话框中,当用户接受它时,有两个选项接受或拒绝,它将确认发送给用户,但是在接收方设备而不是发送方设备上接收确认。我认为这是一个注册问题

查看我的代码

主要活动

public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {

private GoogleCloudMessaging gcm;
static String regid;
CheckBox isdriver;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
String user_name = "";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String TAG = "MainActivity";
String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";
static Utils utils;
private Context context = MainActivity.this;
private ProgressDialog pb;
private EditText username;
String sender_regid;
private ArrayList<PeopleObject> peopleObjList;
ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {

    BookingActivity book = new BookingActivity();
    registerReceiver(book.broadcastReceiver, new IntentFilter(
            "CHAT_MESSAGE_RECEIVED"));
    super.onCreate(savedInstanceState);
    utils = new Utils(this);
    startRegistration();
    isdriver = (CheckBox) findViewById(R.id.isDriver);
    list = new ListView(this);

    if (utils.getFromPreferences(Utils.UserName).isEmpty()) {
        setContentView(R.layout.activity_main);

    } else {

        setPeopleList();

    }

}

void setPeopleList() {


    setSupportProgressBarIndeterminate(true);
    setContentView(list);
    getPeopleList();

    list.setOnItemClickListener(this);

}

private void registerInBackground() {

    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                msg = "Device registered, registration ID=" + regid;
                utils.saveregid("regid_sender",regid);

            } catch (IOException ex) {
                msg = ex.getMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            Log.i(TAG, "onPostExecute : " + msg);

            if (!msg.equalsIgnoreCase("SERVICE_NOT_AVAILABLE")) {

                Message msgObj = handler.obtainMessage();
                Bundle b = new Bundle();
                b.putString("server_response", msg);
                msgObj.setData(b);
                handler.sendMessage(msgObj);

            } else {

                utils.showToast("Error : " + msg
                        + "\nPlease check your internet connection");

                hidePB();

            }
        }

        // Define the Handler that receives messages from the thread and
        // update the progress
        private final Handler handler = new Handler() {

            public void handleMessage(Message msg) {

                String aResponse = msg.getData().getString(
                        "server_response");

                if ((null != aResponse)) {

                    Log.i(TAG, "    sendRegistrationIdToBackend();");

                    sendRegistrationIdToBackend();

                } else {

                }

            }
        };
    }.execute(null, null, null);
}

/**
 * Sends the registration ID to your server over HTTP, so it can use
 * GCM/HTTP or CCS to send messages to your app. Not needed for this demo
 * since the device sends upstream messages to a server that echoes back the
 * message using the 'from' address in the message.
 */
public void sendRegistrationIdToBackend() {

    Log.i(TAG, "sendRegistrationIdToBackend");

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                httpclient = new DefaultHttpClient();

                // yahan reg id ki server webserivcice dalegi

                httppost = new HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/save_reg_id.php");
                nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("username",
                        user_name));
                nameValuePairs.add(new BasicNameValuePair("reg_id", regid));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                final String response = httpclient.execute(httppost,
                        responseHandler);
                Log.i(TAG, "Response : " + response);

                if (response != null) {

                    if (response
                            .equalsIgnoreCase("Username already registered")) {

                        utils.showToast("Username already registered");
                        utils.savePreferences("regid_sender",regid);

                        hidePB();



                    } else {
                        if (response
                                .equalsIgnoreCase("New Device Registered successfully")) {

                            utils.savePreferences(Utils.UserName, user_name);
                            // Persist the regID - no need to register
                            // again.
                            utils.savePreferences("regid_sender", regid);



                            utils.showToast("Device registration successful");

                            runOnUiThread(new Runnable() {
                                public void run() {

                                    setPeopleList();
                                }
                            });

                        }
                    }


                }

            } catch (Exception e) {

                hidePB();
                Log.d(TAG, "Exception : " + e.getMessage());
            }
        }
    };

    thread.start();

}

void getPeopleList() {

    hidePB();
    showPB("Getting People to Chat...");

    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {

            String response = "";

            try {

                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/get_people_list.php");
                nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("username",
                        utils.getFromPreferences(Utils.UserName)));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                response = httpclient.execute(httppost, responseHandler);
                Log.i(TAG, "USER :" + utils.getFromPreferences(Utils.UserName));
                Log.i(TAG, "Response : " + response);

            } catch (Exception ex) {

                Log.d(TAG, "Error : " + ex.getMessage());

                runOnUiThread(new Runnable() {
                    public void run() {
                        utils.showToast("Server Not responding, Please check whether your server is running or not");
                    }
                });

            }

            return response;
        }

        @Override
        protected void onPostExecute(String response) {

            if (!response.equalsIgnoreCase("No People")) {
                peopleObjList = new ArrayList<PeopleObject>();
                // parse JSON here

                try {
                    JSONArray jArray = new JSONArray(response);

                    for (int j = 0; j < jArray.length(); j++) {

                        JSONObject jsonObj = jArray.getJSONObject(j);
                        String username = jsonObj.getString("username");
                        String reg_id = jsonObj.getString("reg_id");

                        PeopleObject p = new PeopleObject();
                        p.setPersonName(username);
                        p.setRegId(reg_id);
                        peopleObjList.add(p);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (peopleObjList.size() > 0) {

                    Message msgObj = handler.obtainMessage();
                    Bundle b = new Bundle();
                    b.putSerializable("people_list",
                            (Serializable) peopleObjList);
                    msgObj.setData(b);
                    handler.sendMessage(msgObj);

                }
            } else {
                hidePB();
                utils.showToast("No People registered for Chat...");
            }

        }

        // Define the Handler that receives messages from the thread and
        // update the progress
        private final Handler handler = new Handler() {

            public void handleMessage(Message msg) {

                @SuppressWarnings("unchecked")
                ArrayList<PeopleObject> peopleList = (ArrayList<PeopleObject>) msg
                        .getData().getSerializable("people_list");

                if (peopleList.size() > 0) {

                    ArrayAdapter<PeopleObject> adapter = new ListAdapter(
                            MainActivity.this, peopleList);
                    list.setAdapter(adapter);

                } else {

                }

                hidePB();
            }
        };
    }.execute(null, null, null);
}

void startRegistration() {

    if (checkPlayServices()) {
        // If this check succeeds, proceed with normal processing.
        // Otherwise, prompt user to get valid Play Services APK.
        Log.i(TAG, "Google Play Services OK");
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = utils.getRegistrationId();
        utils.saveregid("regid_sender",regid);
        /*if(isdriver.isChecked()){
            utils.savePreferences(user_name, regid);
            Log.d(TAG,utils.getFromPreferences(user_name));
        }*/
        System.out.println(regid);
        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.i(TAG, "Reg ID Not Empty");
        }
    } else {
        Log.i(TAG, "No valid Google Play Services APK found.");
    }

}

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            Log.i(TAG, "No Google Play Services...Get it from the store.");
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.i(TAG, "This device is not supported.");
            finish();
        }
        return false;
    }
    return true;
}

void showPB(final String message) {

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            pb = new ProgressDialog(MainActivity.this);
            pb.setMessage(message);
            pb.show();
        }
    });

}

void hidePB() {

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (pb != null && pb.isShowing())
                pb.dismiss();
        }
    });

}

public void onClick(View view) {

    if (view.getId() == R.id.btnsave) {
        username = (EditText) findViewById(R.id.username);
        user_name = username.getText().toString().trim();
        utils.savePreferences("username",user_name);
        if (user_name.length() > 0) {

            Log.d(TAG, "startRegistration");

            showPB("Registering the device");

            startRegistration();

        } else {

            Log.d(TAG, "Username empty");

        }
    }
}
}

预订活动

public class BookingActivity extends ActionBarActivity {

HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
Utils utils;
Intent i;
static String TAG = "GCM DEMO";
String user_name;
String regid;

String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_booking);

    i = getIntent();

    registerReceiver(broadcastReceiver, new IntentFilter(
            "CHAT_MESSAGE_RECEIVED"));
}

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle b = intent.getExtras();

        String message = b.getString("message");

        //Log.i(TAG, " Received in Activity " + message + ", NAME = "
          //      + i.getStringExtra("username"));


    }
};

public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(broadcastReceiver);
}

public void onClick(final View view) {

    if (view == findViewById(R.id.booking)) {

        sendMessage();

       // startActivity(new Intent(BookingActivity.this,NotificationDailog.class));
        //clearMessageTextBox();

    }

}

public void sendMessage() {

    final String messageToSend = "Driver you are now booked by: "+i.getStringExtra("username");

    if (messageToSend.length() > 0) {

        Log.i(TAG, "sendMessage");

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    httpclient = new DefaultHttpClient();
                    httppost = new
                            HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/gcm_engine.php");
                    nameValuePairs = new ArrayList<NameValuePair>(1);
                    nameValuePairs.add(new BasicNameValuePair("message",
                            messageToSend));
                    nameValuePairs.add(new BasicNameValuePair(
                            "registrationIDs", i.getStringExtra("regid")));
                    nameValuePairs.add(new BasicNameValuePair("apiKey",
                            API_KEY));
                    httppost.setEntity(new UrlEncodedFormEntity(
                            nameValuePairs));
                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    final String response = httpclient.execute(httppost,
                            responseHandler);
                    Log.i(TAG, "Response : " + response);
                    if (response.trim().isEmpty()) {
                        Log.d(TAG, "Message Not Sent");
                    }

                } catch (Exception e) {
                    Log.d(TAG, "Exception : " + e.getMessage());
                }
            }
        };

        thread.start();

    }

}
}

通知对话活动

public class NotificationDailog extends ActionBarActivity {


private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String SENDER_ID = "224163385438";
String API_KEY = "AIzaSyCL3REK_ONEgLdhcP8giso_5P6xWE3gUvA";
private String regid;
private DefaultHttpClient httpclient;
private ArrayList<NameValuePair> nameValuePairs;
private HttpPost httppost;
private String TAG = "GCM Demo";
private Utils utils;
private GoogleCloudMessaging gcm;
private Context context = this;
private ProgressDialog pb;
private String regid_sender;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    utils = new Utils(this);
    regid_sender = utils.getregid("regid_sender");
    //regid_sender = BookingActivity.getregid();
    setContentView(R.layout.activity_notification_dailog);
    BookingActivity booking = new BookingActivity();
    registerReceiver(booking.broadcastReceiver, new IntentFilter(
            "CHAT_MESSAGE_RECEIVED"));
}


public void Accept(View view) {


    //startRegistration();
    //getPeopleList();
    sendMessage();
    finish();
}

public void sendMessage() {

    final String messageToSend = "Driver Accepted your request";

    if (messageToSend.length() > 0) {

        Log.i(TAG, "sendMessage");

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    httpclient = new DefaultHttpClient();
                    httppost = new
                            HttpPost("http://www.test5.luminativesolutions.com/cabbooking/ws/gcmdemo/gcm_engine.php");
                    nameValuePairs = new ArrayList<NameValuePair>(1);
                    nameValuePairs.add(new BasicNameValuePair("message",
                            messageToSend));
                    nameValuePairs.add(new BasicNameValuePair(
                            "registrationIDs", regid_sender));
                    nameValuePairs.add(new BasicNameValuePair("apiKey",
                            API_KEY));

                    httppost.setEntity(new UrlEncodedFormEntity(
                            nameValuePairs));
                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    final String response = httpclient.execute(httppost,
                            responseHandler);
                    Log.i(TAG, "Response : " + response);
                    if (response.trim().isEmpty()) {
                        Log.d(TAG, "Message Not Sent");
                    }

                } catch (Exception e) {
                    Log.d(TAG, "Exception : " + e.getMessage());
                }
            }
        };

        thread.start();

    }
}

void showPB(final String message) {

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            pb = new ProgressDialog(NotificationDailog.this);
            pb.setMessage(message);
            pb.show();
        }
    });

}

void hidePB() {

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (pb != null && pb.isShowing())
                pb.dismiss();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_notification_dailog, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

1 个答案:

答案 0 :(得分:0)

您从GCM服务获得的确认仅告知您GCM服务已收到该消息,无论其是否已交付给应用程序。即使安装了应用程序的设备已关闭,您也可以获得它。

如果要在将消息发送到应用程序时收到确认,则必须在收到消息时从应用程序中调用服务器。您可以在邮件中包含一些唯一标识符,并将该标识符从您的应用程序发送到您的服务器以确认交付。

这是与确认相关的堆栈溢出票证:Client(android application) acks for sent gcm messages