如何创建推送通知?代码中的问题。没有得到注册ID

Posted

技术标签:

【中文标题】如何创建推送通知?代码中的问题。没有得到注册ID【英文标题】:How can i create Push notification? Problems in Code. not getting registration id 【发布时间】:2015-09-03 12:37:57 【问题描述】:

我是 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);
    

登录活动

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);
    

Serverutility.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();
            
        
      

【问题讨论】:

【参考方案1】:

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 hivepush-notifications-in-android-platform

【讨论】:

params1.add(new BasicNameValuePair(TAG_regid, registrationId));我在调试时得到它为空 对不起老兄,我的意思是我没有找到你在哪里获得注册ID。 我的 json 帖子 username="" password="" gcm_regid="" 已更新代码,但我的注册 ID 在我登录时显示为空

以上是关于如何创建推送通知?代码中的问题。没有得到注册ID的主要内容,如果未能解决你的问题,请参考以下文章

如何使用推送通知处理注销事件?

使用 pushsharp 获取 android 的注册 ID 以进行推送通知

企业微信推送[python]

如何使用 Cordova 推送插件向我的所有设备发送推送通知

无法从 Urban Airship 获得推送通知

在 MFP 推送通知中注册用户 ID 和显示名称