发件人 ID 用于 c2dm 的注册过程。但没有接收消息或任何注册 ID。
//Akashc2dmActivity.java文件
public class Akashc2dmActivity extends Activity implements OnClickListener {
Button Register,id;
private static PowerManager.WakeLock mWakeLock;
private static final String WAKELOCK_KEY = "C2DM_LIB";
@Override
protected void onCreate(Bundle savedInstanceState) {
if (mWakeLock == null) {
PowerManager pm = (PowerManager) Akashc2dmActivity.this
.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WAKELOCK_KEY);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Register = (Button) findViewById(R.id.button);
Register.setOnClickListener(this);
}
public void sendRequest(View ignored) {
Log.d("Register", "hello");
Intent registrationIntent = new Intent(Constants.SEND_REGISTRATION_TO_GOOGLE);
iHaveNoClueWhatThisSettingDoesButItIsRequiredForTheIntentToWorkSoIBetterSetIt(registrationIntent);
registrationIntent.putExtra("sender", Constants.C2DM_APPLICATION_SERVER_ID);
startService(registrationIntent);
}
private void iHaveNoClueWhatThisSettingDoesButItIsRequiredForTheIntentToWorkSoIBetterSetIt(Intent registrationIntent) {
registrationIntent.putExtra("app", PendingIntent.getBroadcast(Akashc2dmActivity.this, 0, new Intent(), 0));
Log.d("app", ""+PendingIntent.getBroadcast(Akashc2dmActivity.this, 0, new Intent(), 0));
}
@Override
public void onClick(View v) {
if(v == Register){
sendRequest(Register);
}
}
//Constants.java文件
public class Constants {
public static final String TAG = "c2dm";
public static final String REGISTRATION_INTENT = "com.google.android.c2dm.intent.REGISTER";
public static final String SEND_REGISTRATION_TO_GOOGLE = "com.google.android.c2dm.intent.REGISTER";
public static final String RECEIVED_REGISTRATION_ID_FROM_GOOGLE = "com.google.android.c2dm.intent.REGISTRATION";
public static final String RECEIVED_C2DM_MESSAGE_FROM_GOOGLE = "com.google.android.c2dm.intent.RECEIVE";
public static final String START_C2DM_SERVICE = "com.google.android.c2dm.intent.START_SERVICE";
public static final String C2DM_APPLICATION_SERVER_ID = "akash.singh55@gmail.com";
private Constants() {
}
}
//C2DMBroadcastReceiver.java文件
public class C2DMBroadcastReceiver extends BroadcastReceiver {
@Override
public final void onReceive(Context context, Intent intent) {
if (Constants.RECEIVED_REGISTRATION_ID_FROM_GOOGLE.equals(intent.getAction())) {
Log.d(Constants.TAG, "Received a registration ID from Google.");
intent.setAction(Constants.REGISTRATION_INTENT);
intent.setClassName(context, RegistrationIDReceiver.class.getName());
} else if (Constants.RECEIVED_C2DM_MESSAGE_FROM_GOOGLE.equals(intent.getAction())) {
Log.d(Constants.TAG, "Received a C2DM message from Google.");
intent.setAction(Constants.START_C2DM_SERVICE);
intent.setClass(context, C2DMService.class);
}
context.startService(intent);
}
}
//C2DMService.java文件
public class C2DMService extends Service {
@Override
public IBinder onBind(Intent intent) {
Log.e(com.technosoft.Akashc2dm.Constants.TAG, "I was awakend by C2DM!");
return new Binder();
}
}
//RegistrationException.java文件
public class RegistrationException extends Exception {
private final String usedUrl;
private final int responseCode;
public RegistrationException(String message, String usedUrl, int responseCode) {
super(message);
this.usedUrl = usedUrl;
this.responseCode = responseCode;
}
public RegistrationException(String message, Throwable cause) {
super(message, cause);
usedUrl = "";
responseCode = 0;
}
public RegistrationException(String message, String usedUrl, IOException e) {
super(message, e);
this.usedUrl = usedUrl;
responseCode = 0;
}
@Override
public String getMessage() {
return String.format("%s; URL: %s; Response code: %d",
super.getMessage(), usedUrl, responseCode);
}
}
//注册IDReceiver.java文件
public class RegistrationIDReceiver extends IntentService {
NotificationManager nm;
public static final String EXTRA_UNREGISTERED = "unregistered";
private final RegistrationIDRegistrar registrar =
RegistrationIDRegistrar.getInstance();
private static final String EXTRA_ERROR = "error";
private static final String EXTRA_REGISTRATION_ID = "registration_id";
public RegistrationIDReceiver() {
super(Constants.C2DM_APPLICATION_SERVER_ID);
}
@Override
public final void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
String message = (String)extras.get("message");
Log.d("Tag", "msg:" + message);
Log.d(Constants.TAG, "Received intent to register");
final String registrationId = intent.getStringExtra(
EXTRA_REGISTRATION_ID);
notifcation(registrationId);
String error = intent.getStringExtra(EXTRA_ERROR);
if (error == null) {
registerDevice(registrationId);
} else {
handleRegistrationError(error);
}
}
private void notifcation(String id) {
nm = (NotificationManager) RegistrationIDReceiver.this.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Please Testing for Recive id";
CharSequence message = "received ID"+id;
Intent notifyintent = new Intent(getApplicationContext(),Akashc2dmActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,notifyintent, 0);
Notification notif = new Notification(R.drawable.ic_launcher,"Please take your Looking 4 Answers daily survey now", System.currentTimeMillis());
notif.setLatestEventInfo(getApplicationContext(), from, message, contentIntent);
nm.notify(1, notif);
}
private void registerDevice(String registrationId) {
Log.d(Constants.TAG, "Will now register device with ID: " +
registrationId);
try {
registrar.registerIdWithC2DMService(registrationId);
} catch (RegistrationException e) {
Log.e(Constants.TAG, e.getMessage(), e);
}
}
private void handleRegistrationError(String error) {
Log.e(Constants.TAG, "Registration error " + error);
Log.e(Constants.TAG,
"Please click the registration button again to register the device.");
}
}
//RegistrationIDRegistrar.java文件
class RegistrationIDRegistrar {
private static final String REGISTER_NEW_DEVICE = "register_device";
private static final String NODE_ID_PARAMETER = "nodeid";
private static final String REGISTRATION_IS_PARAMETER = "registrationid";
private final String url;
static final String MASHMOBILE_C2DM_SERVER_URL = "http://10.0.1.3:8888";
private RegistrationIDRegistrar(String url) {
this.url = url;
}
void registerIdWithC2DMService(final String registrationId) throws RegistrationException {
DefaultHttpClient httpClient = new DefaultHttpClient();
String nodeId = "realNodeId";
final String requestUrl = createRegistrationUrl(registrationId, nodeId);
HttpGet request = new HttpGet(requestUrl);
try {
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RegistrationException(String.format(
"Could not register %s with the server.", registrationId),
requestUrl, statusCode);
}
} catch (IOException e) {
throw new RegistrationException(String.format(
"Registration of %s failed.", registrationId), requestUrl, e);
}
}
private String createRegistrationUrl(String registrationId, String nodeId) {
return String.format("%s/%s?%s=%s&%s=%s",
url, REGISTER_NEW_DEVICE, NODE_ID_PARAMETER, nodeId,
REGISTRATION_IS_PARAMETER, registrationId);
}
static RegistrationIDRegistrar getInstance() {
return new RegistrationIDRegistrar(MASHMOBILE_C2DM_SERVER_URL);
}
}
最后使用 list 文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.technosoft.Akashc2dm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<permission
android:name="com.google.android.c2dm.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission
android:name="com.google.android.c2dm.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".Akashc2dmActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".C2DMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND"
>
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="com.technosoft.Akashc2dm"/>
</intent-filter>
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.RECEIVE"/>
<category android:name="com.technosoft.Akashc2dm"/>
</intent-filter>
</receiver>
<service android:name=".RegistrationIDReceiver"
>
<intent-filter>
<action
android:name="com.technosoft.c2dm.intent.REGISTER"/>
<category android:name="com.technosoft.Akashc2dm"/>
</intent-filter>
</service>
<service
android:name=".C2DMService">
<intent-filter>
<action
android:name="com.technosoft.c2dm.intent.START_SERVICE"/>
<category android:name="com.technosoft.Akashc2dm"/>
</intent-filter>
</service>
<meta-data android:value="true" android:name="ADMOB_ALLOW_LOCATION_FOR_ADS"/>
</application>
请告诉我如何在 c2dm 中获取注册 ID 并向第三方应用程序发送消息
最佳答案
上面的代码代码运行成功。有一些变化 在 C2DMBroadcastReceiver.java 类中用于接收消息并且有 添加用于向服务器发送消息的 MessageClass.java 类
C2DMBroadcastReceiver.java文件
public class C2DMBroadcastReceiver extends BroadcastReceiver {
NotificationManager nm;
@Override
public final void onReceive(Context context, Intent intent) {
if (Constants.RECEIVED_REGISTRATION_ID_FROM_GOOGLE.equals(intent.getAction())) {
Log.d(Constants.TAG, "Received a registration ID from Google.");
intent.setAction(Constants.REGISTRATION_INTENT);
intent.setClassName(context, RegistrationIDReceiver.class.getName());
} else if (Constants.RECEIVED_C2DM_MESSAGE_FROM_GOOGLE.equals(intent.getAction())) {
Function_notification(context,intent);
Log.d(Constants.TAG, "Received a C2DM message from Google.");
intent.setAction(Constants.START_C2DM_SERVICE);
intent.setClass(context, C2DMService.class);
}
context.startService(intent);
}
private void Function_notification(Context context,Intent intent ) {
Bundle extras = intent.getExtras();
Log.d("extras",""+extras);
String message2 = (String)extras.get("collapse_key");
Log.d("collapse_key","collapse_key=" + message2);
String message1 = (String)extras.get("payload");
Log.d("extras","payload=" + message1);
String error = intent.getStringExtra("error");
Log.d("extras","error=" + error);
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Please Testing for Recive message";
CharSequence message = message1;
Intent notifyintent = new Intent(context,Akashc2dmActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notifyintent, 0);
Notification notif = new Notification(R.drawable.icon,"Please take your Recive message", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}
> **Add This class in com.technosoft.C2dm_Server_1 package**
MessageClass .java 文件
public class MessageClass {
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
public static String sendMessage(String auth_token, String registrationId,
String message) throws IOException {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(registrationId);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("1");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode("hello", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpsURLConnection
.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_token);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
Log.d("C2DM", "Unauthorized - need token");
}
String updatedAuthToken = conn.getHeaderField("Update-Client-Auth");
if (updatedAuthToken != null && !auth_token.equals(updatedAuthToken)) {
Log.d("C2DM",
"Got updated auth token from datamessaging servers: "
+ updatedAuthToken);
sendMessage(updatedAuthToken,registrationId,
message);
}
String responseLine = new BufferedReader(new InputStreamReader(
conn.getInputStream())).readLine();
// NOTE: You *MUST* use exponential backoff if you receive a 503
// response code.
// Since App Engine's task queue mechanism automatically does this
// for tasks that
// return non-success error codes, this is not explicitly
// implemented here.
// If we weren't using App Engine, we'd need to manually implement
// this.
if (responseLine == null || responseLine.equals("")) {
Log.i("C2DM", "Got " + responseCode
+ " response from Google AC2DM endpoint.");
throw new IOException(
"Got empty response from Google AC2DM endpoint.");
}
String[] responseParts = responseLine.split("=", 2);
if (responseParts.length != 2) {
Log.e("C2DM", "Invalid message from google: " + responseCode
+ " " + responseLine);
throw new IOException("Invalid response from Google "
+ responseCode + " " + responseLine);
}
if (responseParts[0].equals("id")) {
Log.i("Tag", "Successfully sent data message to device: "
+ responseLine);
}
if (responseParts[0].equals("Error")) {
String err = responseParts[1];
Log.w("C2DM",
"Got error response from Google datamessaging endpoint: "
+ err);
// No retry.
throw new IOException(err);
}
return responseLine;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
**This class use in RegistrationIDRegistrar.java class**
RegistrationIDRegistrar.java文件
class RegistrationIDRegistrar {
static final String MASHMOBILE_C2DM_SERVER_URL = "http://10.0.1.3:8888";
String response;
private RegistrationIDRegistrar(String url) {
}
void registerIdWithC2DMService(final String registrationId){
//getAuthentification();
Log.d("registrationId", ""+registrationId);
try {
String auth_key =getToken(Constants.C2DM_APPLICATION_SERVER_ID,Constants.C2DM_APPLICATION_SERVER_Password);
Log.d("auth_key", ""+auth_key);
response = MessageClass.sendMessage(auth_key,registrationId, "hello test android");
Log.d("Response code", ""+response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getToken(String email, String password)
throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(email);
builder.append("&Passwd=").append(password);
builder.append("&accountType=GOOGLE");
builder.append("&source=MyLittleExample");
builder.append("&service=ac2dm");
// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = con.getOutputStream();
output.write(data);
output.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
String auth_key = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Auth=")) {
auth_key = line.substring(5);
Log.d("auth_key", ""+auth_key);
}
}
// Finally get the authentication token
// To something useful with it
return auth_key;
}
static RegistrationIDRegistrar getInstance() {
return new RegistrationIDRegistrar(MASHMOBILE_C2DM_SERVER_URL);
}
}
关于android - 如何在 android c2dm0+ 中检索注册 ID 并向第三方应用程序发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033213/
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我想用ruby编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende