我是Gcm新手,我想使用gcm向我的应用程序的空间用户发送通知,但通知仅在我自己的设备中发送
这是我的代码
MainActivity.java
public class MainActivity extends ActionBarActivity {
private GoogleCloudMessaging gcm;
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";
Utils utils;
private Context context = MainActivity.this;
private ProgressDialog pb;
private EditText username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
utils = new Utils(this);
isdriver = (CheckBox) findViewById(R.id.isDriver);
}
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;
} 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");
hidePB();
} else {
if (response
.equalsIgnoreCase("New Device Registered successfully")) {
utils.savePreferences(Utils.UserName, user_name);
// Persist the regID - no need to register
// again.
utils.storeRegistrationId(regid);
utils.showToast("Device registration successful");
}
}
}
} catch (Exception e) {
hidePB();
Log.d(TAG, "Exception : " + e.getMessage());
}
}
};
thread.start();
}
public void onClick(View view) {
if (view.getId() == R.id.btnsave) {
username = (EditText) findViewById(R.id.username);
user_name = username.getText().toString().trim();
if (user_name.length() > 0) {
Log.d(TAG, "startRegistration");
showPB("Registering the device");
startRegistration();
/*if(isdriver.isChecked()){
Log.i(TAG,"Driver reg id");
Log.d(TAG, utils.getFromPreferences(user_name));
}*/
Intent i = new Intent(MainActivity.this,BookingActivity.class);
i.putExtra("username",user_name);
i.putExtra("regid",regid);
startActivity(i);
} else {
Log.d(TAG, "Username empty");
}
}
}
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();
/*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();
}
});
}
@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_main, 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);
}
}
BookingActivity.java
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 onClick(final View view) {
if (view == findViewById(R.id.booking)) {
sendMessage();
//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();
}
}
@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_booking, 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);
}
}
Utils.java
public class Utils {
static Context context;
public static final String TAG = "Utils";
public static final String UserName = "UserName";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
public Utils(Context context) {
Utils.context = context;
}
public SharedPreferences getGCMPreferences() {
return context.getSharedPreferences(((ActionBarActivity) context)
.getClass().getSimpleName(), Context.MODE_PRIVATE);
}
public void savePreferences(String key, String value) {
final SharedPreferences prefs = getGCMPreferences();
Log.i(TAG, key + " : " + value);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public String getFromPreferences(String key) {
final SharedPreferences prefs = getGCMPreferences();
String value = prefs.getString(key, "");
if (value.isEmpty()) {
Log.i(TAG, key + " not found.");
return "";
}
return value;
}
String getRegistrationId() {
final SharedPreferences prefs = getGCMPreferences();
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
Integer.MIN_VALUE);
int currentVersion = getAppVersion();
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
static int getAppVersion() {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
public void storeRegistrationId(String regId) {
final SharedPreferences prefs = getGCMPreferences();
int appVersion = Utils.getAppVersion();
Log.i(TAG, "Saving regId on app version " + appVersion);
Log.i(TAG, "Reg ID : " + regId);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public String getCurrentIPAddress() {
return "http://192.168.0.101/";
}
public void showToast(final String txt) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, txt, Toast.LENGTH_LONG).show();
}
});
}
}
在我的app用户登录为简单用户或登录为驱动程序如果用户登录并注册gcm并按下预订按钮通知发送给特定驱动程序
答案 0 :(得分:1)
这只是因为您正在调用自己的设备ID以获得通知,请检查后端,所有注册用户必须拥有自己的设备ID。确保在新注册发生时生成的设备ID不同。