- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我是 Android 新手,需要一些关于我的代码的帮助。我正在做推送通知,我使用发布请求将注册 ID 传递到我的服务器。我编写了代码来执行此操作,但在调试时我不断收到 null 的注册 id。这是我编写的代码:
Splashscreen.java
package com.driverapp.inis.zuber;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
import Connectivity_manager.Internet_CheckingActivity;
import UI_Alert.AlertDialogManager;
public class Splashscreen extends Activity {
private static final String TAG = "SplashScreenActivity";
private static final String TAG1 = "lifecycle";
private Location newLocation = null;
private AlertDialogManager alert;
private Internet_CheckingActivity chckInternt;
private GeoLocationFinder geoLocationFinder;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
protected String SENDER_ID = "525761298572";
private GoogleCloudMessaging gcm = null;
private String regid = null;
private Context context = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
alert = new AlertDialogManager();
chckInternt = new Internet_CheckingActivity(this);
Log.d(TAG1, "oncreate");
context = getApplication();
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
} else {
Log.d(TAG, "No valid Google Play Services APK found.");
}
}
}
@Override
public void onBackPressed() {
restart();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG1, "onresume");
// setupLocation();
if (chckInternt.isNetworkAvailable() == true) {
setupLocation();
} else {
alert.showAlertDialog(Splashscreen.this, "Error", "Please Check Your Internet Connection", false);
}
checkPlayServices();
}
/**
* Method for checking the current lat log values.
*/
private void setupLocation() {
GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {
@Override
public void gotLocation(Location location) {
if (location != null) {
newLocation = new Location(location);
newLocation.set(location);
Log.d(TAG,
"Got coordinates, congratulations. Longitude = "
+ newLocation.getLongitude() + " Latitude = "
+ newLocation.getLatitude());
Intent i = new Intent(Splashscreen.this, DefaultMAP.class);
startActivity(i);
finish();
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
alert.showAlertDialog(Splashscreen.this, "Check Your GPS", "Restart your Application", false);
}
});
}
}
};
geoLocationFinder = new GeoLocationFinder();
geoLocationFinder.getLocation(this, locationResult);
RelativeLayout root = (RelativeLayout) findViewById(R.id.splash);
root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restart();
}
});
}
public void restart() {
Intent rIntent = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
rIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(rIntent);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG1, "onpause");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG1, "onstart");
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported - Google Play Services.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.d(TAG, "Registration ID not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.d(TAG, "App version changed.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return getSharedPreferences(Splashscreen.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void registerInBackground() {
new AsyncTask() {
@Override
protected Object doInBackground(Object... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
Log.d(TAG, "########################################");
Log.d(TAG, "Current Device's Registration ID is: " + msg);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return null;
}
protected void onPostExecute(Object result) { //to do here
};
} .execute(null,null,null);
}
}
登录 Activity
public class LoginActivity extends AppCompatActivity {
private Button btnlogin;
private EditText txtusername;
private EditText txtpassword;
private String userName;
private String message;
private String userid;
private JSONArray login_data = null;
private Internet_CheckingActivity chckInternt;
private TransparentProgressDialog pDialog;
private static final String URL_Login = "http:myapi";
private static final String TAG_MESSAGE = "message";
private static final String TAG_username = "username";
private static final String TAG_password = "password";
SessionManager msessionManager;
private AlertDialogManager alert;
private Location newLocation = null;
private static final String TAG = "SplashScreenActivity";
private GeoLocationFinder geoLocationFinder;
private static final String TAG_regid = "gcm_regid";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
alert = new AlertDialogManager();
chckInternt = new Internet_CheckingActivity(this);
txtusername = (EditText) findViewById(R.id.lusername);
txtpassword = (EditText) findViewById(R.id.lpassword);
btnlogin = (Button) findViewById(R.id.loginbtn);
msessionManager = new SessionManager(getApplicationContext());
btnlogin.setOnClickListener(mbtnLogin);
if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
|| SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
alert.showAlertDialog(LoginActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
}
@Override
public void onBackPressed() {
startActivity(new Intent(this, Splashscreen.class));
}
private View.OnClickListener mbtnLogin = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (chckInternt.isNetworkAvailable() == true) {
if (txtusername.getText().toString().isEmpty() || txtpassword.getText().toString().isEmpty()) {
alert.showAlertDialog(LoginActivity.this, "Login failed", "Both Username and Password required", false);
txtusername.setText("");
txtpassword.setText("");
} else {
setupLocation();
}
} else {
alert.showAlertDialog(LoginActivity.this, "Login failed", "Please check your internet Connection and Retry Again", false);
txtusername.setText("");
txtpassword.setText("");
}
}
};
private void setupLocation() {
GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {
@Override
public void gotLocation(Location location) {
if (location != null) {
newLocation = new Location(location);
newLocation.set(location);
Log.d(TAG,
"Got coordinates, congratulations. Longitude = "
+ newLocation.getLongitude() + " Latitude = "
+ newLocation.getLatitude());
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
new AttemptLogin().execute();
}
});
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
alert.showAlertDialog(LoginActivity.this, "Check Your GPS", "Restart your Application", false);
}
});
}
}
};
geoLocationFinder = new GeoLocationFinder();
geoLocationFinder.getLocation(this, locationResult);
}
@Override
protected void onPause() {
super.onPause();
txtusername.setText("");
txtpassword.setText("");
}
class AttemptLogin extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new TransparentProgressDialog(LoginActivity.this,R.drawable.spinner);
pDialog.setCancelable(Boolean.FALSE);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
HashMap<String, String> regId = msessionManager.getUserregidDetails();
String registrationId = regId.get(SessionManager.KEY_Regid);
Httpmanager hm = new Httpmanager();
final String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
List params1 = new ArrayList();
params1.add(new BasicNameValuePair(TAG_username, username));
params1.add(new BasicNameValuePair(TAG_password, password));
params1.add(new BasicNameValuePair(TAG_regid, registrationId));
String jsonstr = hm.makeServiceCall(URL_Login, Httpmanager.post, params1);
Log.d("Response: ", "> " + jsonstr);
if (jsonstr != null) {
try {
JSONObject jsonObject = new JSONObject(jsonstr);
if (jsonObject.getString("hasError").equals("1")) {
message = jsonObject.getString(TAG_MESSAGE);
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Alert", message, false);
}
});
}
else {
message = jsonObject.getString(TAG_MESSAGE);
login_data = jsonObject.getJSONArray("data");
for (int i = 0; i < login_data.length(); i++) {
JSONObject l = login_data.getJSONObject(i);
userName = l.getString("username");
userid = l.getString("userid");
msessionManager.createLoginSession(userName, userid);
Intent intent = new Intent(LoginActivity.this, DefaultMAP.class);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), message + userName, Toast.LENGTH_LONG).show();
}
});
startActivity(intent);
finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.e("HttpManager", "Couldn't get any data from the url");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Please check your internet Connection and Retry Again", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void file_url) {
pDialog.dismiss();
txtusername.setText("");
txtpassword.setText("");
}
}
}
Commonutilities.java
public class CommonUtilities {
// give your server registration url here
static final String SERVER_URL = "http:myapp";
// Google project id
static final String SENDER_ID = "525761298572";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM";
static final String DISPLAY_MESSAGE_ACTION =
"com.driverapp.inis.zuber.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
服务器实用程序.java
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, String email, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = CommonUtilities.SERVER_URL;
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
params.put("email", email);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register on our server
// As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
CommonUtilities.displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
最佳答案
Larry 尝试了你的方法,但未能找到错误。将 google play 服务添加到您的项目中并尝试 getDeviceToken() 方法。
private void getDeviceToken() {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context
.getApplicationContext());
String deviceToken = null;
try {
deviceToken = gcm.register(Constants.Project_ID);
} catch (IOException e) {
e.printStackTrace();
}
Log.i("GCM", "Device token : " + deviceToken);
if (deviceToken == null) {
System.out.println("null");
getDeviceToken();
} else {
System.out.println("device"+deviceToken);
// save registeration ID here
}
}
有关更多信息,请尝试这些链接 Android hive
push-notifications-in-android-platform
关于java - 如何创建推送通知?代码中的问题。未获取注册 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32375875/
我找到了 this excellent question and answer它以 x/y(加上 center x/y 和 degrees/radians)开始并计算旋转- 到 x'/y'。这个计算很
全部: 我已经创建了一个 Windows 窗体和一个按钮。在另一个线程中,我试图更改按钮的文本,但它崩溃了;但是如果我尝试更改按钮的颜色,它肯定会成功。我认为如果您更改任何 Windows 窗体控件属
本网站的另一个问题已证实,C 中没有缩写的字面后缀,并且可以执行以下操作: short Number = (short)1; 但是转换它和不这样做有什么区别: short Number = 1; 您使
我有下表: ID (int) EMAIL (varchar(50)) CAMPAIGNID (int) isSubscribe (bit) isActionByUser (bit) 此表存储了用户对事
也就是说,无需触发Javascript事件即可改变的属性,如何保留我手动选中或取消选中的复选框的状态,然后复制到另一个地方? 运行下面的代码片段并选中或取消选中其中的一些,然后点击“复制”: $('#
我在网上找到的所有关于递增指针导致段错误的示例都涉及指针的取消引用 - 如果我只想递增它(例如在 for 循环的末尾)并且我不在乎它是否最终进入无效内存,因为我不会再使用它。例如,在这个程序中,每次迭
我有一个 Spring MVC REST 服务,它使用 XStream 将消息与 XML 相互转换。 有什么方法可以将请求和响应中的 xml(即正文)打印到普通的 log4j 记录器? 在 Contr
做我的任务有一个很大的挑战,那就是做相互依赖的任务我在这张照片中说的。假设我们有两个任务 A 和 B,执行子任务 A1、A2 和 B1、B2,假设任务 B 依赖于 A。 要理想地执行任务 B,您应该执
通过阅读该网站上的几个答案,我了解到 CoInitialize(Ex) should be called by the creator of a thread 。然后,在该线程中运行的任何代码都可以使
这个问题已经困扰我一段时间了。我以前从未真正使用过 ListViews,也没有使用过 FirebaseListAdapters。我想做的就是通过显示 id 和用户位置来启动列表的基础,但由于某种原因,
我很难解释这两个(看似简单)句子的含义: “受检异常由编译器在编译时检查” 这是什么意思?编译器检查是否捕获了所有已检查的异常(在代码中抛出)? “未经检查的异常在运行时检查,而不是编译时” 这句话中
我有一个包含排除子字符串的文本文件,我想迭代该文件以检查并返回不带排除子字符串的输入项。 这里我使用 python 2.4,因此下面的代码可以实现此目的,因为 with open 和 any 不起作用
Spring 的缓存框架能否了解请求上下文的身份验证状态,或者更容易推出自己的缓存解决方案? 最佳答案 尽管我发现这个用例 super 奇怪,但您可以为几乎任何与 SpEL 配合使用的内容设置缓存条件
我有以下函数模板: template HeldAs* duplicate(MostDerived *original, HeldAs *held) { // error checking omi
如果我的应用程序具有设备管理员/设备所有者权限(未获得 root 权限),我如何才能从我的应用程序中终止(或阻止启动)另一个应用程序? 最佳答案 设备所有者可以阻止应用程序: DevicePolicy
非常简单的问题,但我似乎无法让它正常工作。 我有一个组件,其中有一些 XSLT(用于导航)。它通过 XSLT TBB 使用 XSLT Mediator 发布。 发布后
我正在将一个对象拖动到一个可拖放的对象内,该对象也是可拖动的。放置对象后,它会嵌套在可放置对象内。同样,如果我将对象拖到可放置的外部,它就不再嵌套。 但是,如果我经常拖入和拖出可放置对象,则可拖动对象
我正在尝试为按钮和弹出窗口等多个指令实现“取消选择”功能。也就是说,我希望当用户单击不属于指令模板一部分的元素时触发我的函数。目前,我正在使用以下 JQuery 代码: $('body').click
我从 this question 得到了下面的代码,该脚本用于在 Google tasks 上更改 iframe[src="about:blank"] 内的 CSS使用 Chrome 扩展 Tempe
我有一些 @Mock 对象,但没有指定在该对象上调用方法的返回值。该方法返回 int (不是 Integer)。我很惊讶地发现 Mockito 没有抛出 NPE 并返回 0。这是预期的行为吗? 例如:
我是一名优秀的程序员,十分优秀!