无法通过登录活动通过网络服务发送注册ID(GCM)

用户5653135

我是Android新手,这是我第一次进行推送通知,并且从我的Log System.out.println(“ Registration ID:” + registrationId);中的 云服务器获取注册ID GCMIntentService类别,但无法在登录屏幕上将其作为带有URL的参数发送到后端。我在这里发布我的代码。请帮助我。

CommonUtilities.java

public final class CommonUtilities {
/**
 * Base URL 
 */
public static final String SERVER_URL ="";

/**
 * Google API project id registered to use GCM.
 */


// date 16 april 2015
public static final String SENDER_ID = "332948388069";

// API_Key = AIzaSyCBpVn9J2TWxPZDqyilCssUh5dbphQQtWE

/**API_Key=AIzaSyDsAQ_ynBJNPCOstGcDjAwRReDWF5uYsc0
 * Tag used on log messages.
 */
public static final String TAG = "Sample";

/**
 * Intent used to display a message in the screen.
 */
public static final String DISPLAY_MESSAGE_ACTION = "com.xxxxxxxx.DISPLAY_MESSAGE";

/**
 * Intent's extra that contains the message to be displayed.
 */
public 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.
 */
public static void displayMessage(Context context, String message) {
    Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
    intent.putExtra(EXTRA_MESSAGE, message);
    context.sendBroadcast(intent);
 }
 }

GCMIntentService.java

import static com.xxxxxx.CommonUtilities.SENDER_ID;
import static com.xxxxxx.CommonUtilities.displayMessage;


public class GCMIntentService extends GCMBaseIntentService{
private static final String TAG = "GCMIntentService";

public GCMIntentService() {
    super(SENDER_ID);
}

/**
 * Method called on device registered
 **/

@Override
protected void onRegistered(Context context, String registrationId) {
    Log.i(TAG, "Device registered: regId = " + registrationId);
    displayMessage(context, "Your device registred with GCM");
    ServerUtilities.register(context, registrationId);
}

/**
 * Method called on device un registred
 * */
@Override
protected void onUnregistered(Context context, String registrationId) {
    Log.i(TAG, "Device unregistered");
    displayMessage(context, getString(R.string.gcm_unregistered));
    ServerUtilities.unregister(context, registrationId);
}

/**
 * Method called on Receiving a new message
 * */
@Override
protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Received message");
    String message = intent.getExtras().getString("price");

    displayMessage(context, message);
    // notifies user
    generateNotification(context, message);
}

/**
 * Method called on receiving a deleted message
 * */
@Override
protected void onDeletedMessages(Context context, int total) {
    Log.i(TAG, "Received deleted messages notification");
    String message = getString(R.string.gcm_deleted, total);
    displayMessage(context, message);
    // notifies user
    generateNotification(context, message);
}

/**
 * Method called on Error
 * */
@Override
public void onError(Context context, String errorId) {
    Log.i(TAG, "Received error: " + errorId);
    displayMessage(context, getString(R.string.gcm_error, errorId));
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
    // log message
    Log.i(TAG, "Received recoverable error: " + errorId);
    displayMessage(context, getString(R.string.gcm_recoverable_error,
            errorId));
    return super.onRecoverableError(context, errorId);
}

/**
 * Issues a notification to inform the user that server has sent a message.
 */
private static void generateNotification(Context context, String message) {
    int icon = R.mipmap.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = "Testing";
    Intent notificationIntent = new Intent(context, Home_Screen.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);

}

}

Login.java

public class Login extends AppCompatActivity {

EditText edit_email, edit_password;
String email, password;
Button btn_submit;
ProgressDialog dialog;
TextView tv_count, attempt;
String value, url = "http://xxxxxxxxxxx.php?caseid=5",
        forget_url = "http://xxxxxxxxxx.php?caseid=7";
Parser parser = new Parser();
TextView txt_signup, forgot_password;
String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
int count = 3;
String devicetype = "android",deviceid,regid;
AsyncTask<Void, Void, Void> mRegisterTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    attempt = (TextView) findViewById(R.id.attempt);
    attempt.setVisibility(View.GONE);
    tv_count = (TextView) findViewById(R.id.count);
    tv_count.setVisibility(View.GONE);
    forgot_password = (TextView) findViewById(R.id.forgot_password);
    edit_email = (EditText) findViewById(R.id.edit_email);
    edit_password = (EditText) findViewById(R.id.edit_password);
    btn_submit = (Button) findViewById(R.id.btn_submit);
    txt_signup = (TextView) findViewById(R.id.txt_signup);
    txt_signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(Login.this, SignUp.class));
            finish();
        }
    });

    deviceid = Secure.getString(Login.this.getContentResolver(), Secure.ANDROID_ID);

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf = cm.getActiveNetworkInfo();
    if (nf != null && nf.isConnected() == true)
    {
        checkNotNull(CommonUtilities.SERVER_URL, "SERVER_URL");
        checkNotNull(CommonUtilities.SENDER_ID, "SENDER_ID");
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
  //Register Device on GCM Server
        registerReceiver(mHandleMessageReceiver,new IntentFilter(CommonUtilities.DISPLAY_MESSAGE_ACTION));
        regid = GCMRegistrar.getRegistrationId(this);

        if (regid.equals("")) {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, CommonUtilities.SENDER_ID);

        } else {
            // Device is already registered on GCM, check server.
            // if (GCMRegistrar.isRegisteredOnServer(this)) {
            // // Skips registration.
            // } else {
            // // Try to register again, but not in the UI thread.
            // // It's also necessary to cancel the thread onDestroy(),
            // // hence the use of AsyncTask instead of a raw thread.
            // Try to register again, but not in the UI thread.
            // It's also necessary to cancel the thread onDestroy(),
            // hence the use of AsyncTask instead of a raw thread.
            final Context context = this;
            mRegisterTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    // Register on our server
                    // On server creates a new user
                    ServerUtilities.register(context, regid);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mRegisterTask = null;
                }
            };

            mRegisterTask.execute(null, null, null);
            // }
        }
    } else {
        // do nothing
    }
    btn_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          new LoginTask().execute();
        });
    }

    private void checkNotNull(Object reference, String name) {
    if (reference == null) {
        throw new NullPointerException(
                getString(R.string.error_config, name));
    }
}

private final BroadcastReceiver mHandleMessageReceiver =
        new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String newMessage = intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE);
            }
        };


public class LoginTask extends AsyncTask<String, String, JSONObject> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(Login.this);
        dialog.setIndeterminate(false);
        dialog.setMessage("Please Wait....");
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... params) {

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("email", email));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        nameValuePairs.add(new BasicNameValuePair("deviceid", deviceid));
        nameValuePairs.add(new BasicNameValuePair("devicetype",devicetype));
        nameValuePairs.add(new BasicNameValuePair("regid", regid));
        System.out.println("email: "+email+" deviceid: "+deviceid+" devicetype: "+devicetype+" regisid: "+regid);

        JSONObject json = parser.getJSONFromUrl(url, nameValuePairs);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        dialog.dismiss();
        try {
            int result = json.getInt("udata");

            if (result == 1) {
                SaveSharedPreference.setUserEmail(Login.this, email);
                Intent intent = new Intent(Login.this, Home_Screen.class);
                startActivity(intent);
                finish();

            }
            if (result == 2) {
                Toast toast = Toast.makeText(getApplicationContext(), "Email id or password not correct", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                tv_count.setVisibility(View.VISIBLE);
                attempt.setVisibility(View.VISIBLE);

                //  tv_count.setBackgroundColor(Color.RED);
                count--;
                tv_count.setText(Integer.toString(count));

                if (count == 0) {
                    btn_submit.setEnabled(false);
                }
            }
            if (count == 0) {
                    Toast.makeText(Login.this,"something went wrong",Toast.LENGTH_SHORT).show();
                    btn_submit.setEnabled(false);
                }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("Exception", "" + e.toString());

        }


    }
  }

ServerUtilities.java

import static com.xxxxxx.CommonUtilities.SERVER_URL;
import static com.xxxxxx.CommonUtilities.displayMessage;

public 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, final String regId) {
    Log.e("registering(regId = ", "" + regId + ")");
    String serverUrl = SERVER_URL;
    Map<String, String> params = new HashMap<String, String>();
    params.put("regId", regId);

    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("Attempt #","" + i + " to register");
        try {
            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("Failed to register" ,""+ i + ":" + e);
            if (i == MAX_ATTEMPTS) {
                break;
            }
            try {
                Log.d("Sleeping for ","" + backoff + " ms before retry");
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                // Activity finished before we complete - exit.
                Log.d("Thread interrupted:","");
                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("unregistering(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, String params)throws IOException {

    try {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        connection_respones_String = new WebResponseClass();
        HttpResponse httpResponse;
        InputStream inputStream;
        HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 180000);
        HttpPost httpPost = new HttpPost(endpoint);
        HttpEntity entity;

        List<NameValuePair> params_post = new ArrayList<NameValuePair>();

        params_post.add(new BasicNameValuePair("regId", params));
        try {
            entity = new UrlEncodedFormEntity(params_post);
        } catch (final UnsupportedEncodingException e) {
            // this should never happen.
            throw new AssertionError(e);
        }

        // StringEntity se = new StringEntity(params_post);
        // System.out.println("StringEntityyyyyyyyyy"+se);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type",
                "application/x-www-form-urlencoded");
        httpResponse = defaultHttpClient.execute(httpPost);
        inputStream = httpResponse.getEntity().getContent();
        if (inputStream != null) {
            // connection_respones_String =
            // convertInputStreamToString(inputStream);
            connection_respones_String.setStrData(convertInputStreamToString(inputStream));
            connection_respones_String.setResponse(httpResponse);
  //if (httpResponse.getStatusLine().getStatusCode() == 200) {
 //Jsonloginset set = Utill
//.getAuthenticationFromJson(connection_respones_String
 //.getStrData());
 //connection_respones_String.setData(set);
  //}
            System.out.println("result>>>>>>>>>>>>>>>"+connection_respones_String.getStrData());
        }
        // else
        // connection_respones_String = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
        e.printStackTrace();
    }

    System.out.println("qqqqqqqqqqq"
            + connection_respones_String.getStrData());



}

private static String convertInputStreamToString(InputStream inputStream)
        throws IOException {
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;
    inputStream.close();
    return result;
}
}
乔杜里·阿马尔

您在登录时会遇到此问题,因为您正在同一屏幕上获取和发送Reg_Id,因此很快它需要从云服务器生成一些Reg_Id,有时它无法获取,并且您的参数保持为空。尝试一件事在“启动画面”上获取它,并将其保存到您的SharedPreference,然后将其发送到“仪表板”屏幕上。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

通过休息网络服务发送时的空地图

来自分类Dev

将 Gmail 邮件转换为文件并通过网络服务发送

来自分类Dev

我如何通过Google Glass调用网络服务

来自分类Dev

通过网络服务传递参数为null

来自分类Dev

通过SSH重新启动本地VM的网络服务

来自分类Dev

通过GP网络服务传递多个订单项

来自分类Dev

在 Flutter / Dart 中打印通过网络服务下载的 pdf

来自分类Dev

允许通过自己的网络服务器iOS 7发送电子邮件吗?

来自分类Dev

我可以通过终端登录我的服务器,但无法通过 Mac 网络进入

来自分类Dev

无法使用网络服务

来自分类Dev

通过交换网络服务移动到另一个文件夹后如何通过 id 或 guid 访问电子邮件

来自分类Dev

我无法通过网络服务器部署OTA iPhone应用程序,但是Diawi之类的服务可以在我的设备上安装该应用程序

来自分类Dev

我无法通过网络服务器部署OTA iPhone应用程序,但是Diawi之类的服务可以在我的设备上安装该应用程序

来自分类Dev

无法通过移动3g网络访问服务器发送事件

来自分类Dev

无法通过注册器注册Docker服务

来自分类Dev

通过网络服务共享图书数据的良好标准是什么?

来自分类Dev

如何通过Mac OS X上的终端停用网络服务?

来自分类Dev

通过链接在网络服务器上执行python脚本

来自分类Dev

okhttp-urlconnection测试使模拟网络服务器崩溃,但仍通过

来自分类Dev

通过网络服务获取数组时PHP中的未定义偏移量

来自分类Dev

尝试通过向左或向右滑动来删除 RecycleView 项目(从网络服务加载)

来自分类Dev

如何查看谁通过 wifi 从网络服务访问我的 IP 地址

来自分类Dev

通过网络发送音频

来自分类Dev

通过网络发送 AVPacket

来自分类Dev

如何通过Windows Azure通过GCM通过唯一ID发送特定Android设备的通知?

来自分类Dev

无法从gcm获取注册ID

来自分类Dev

无法从GCM获取注册ID

来自分类Dev

无法从gcm获取注册ID

来自分类Dev

在python中通过TCP服务器网络发送对象

Related 相关文章

  1. 1

    通过休息网络服务发送时的空地图

  2. 2

    将 Gmail 邮件转换为文件并通过网络服务发送

  3. 3

    我如何通过Google Glass调用网络服务

  4. 4

    通过网络服务传递参数为null

  5. 5

    通过SSH重新启动本地VM的网络服务

  6. 6

    通过GP网络服务传递多个订单项

  7. 7

    在 Flutter / Dart 中打印通过网络服务下载的 pdf

  8. 8

    允许通过自己的网络服务器iOS 7发送电子邮件吗?

  9. 9

    我可以通过终端登录我的服务器,但无法通过 Mac 网络进入

  10. 10

    无法使用网络服务

  11. 11

    通过交换网络服务移动到另一个文件夹后如何通过 id 或 guid 访问电子邮件

  12. 12

    我无法通过网络服务器部署OTA iPhone应用程序,但是Diawi之类的服务可以在我的设备上安装该应用程序

  13. 13

    我无法通过网络服务器部署OTA iPhone应用程序,但是Diawi之类的服务可以在我的设备上安装该应用程序

  14. 14

    无法通过移动3g网络访问服务器发送事件

  15. 15

    无法通过注册器注册Docker服务

  16. 16

    通过网络服务共享图书数据的良好标准是什么?

  17. 17

    如何通过Mac OS X上的终端停用网络服务?

  18. 18

    通过链接在网络服务器上执行python脚本

  19. 19

    okhttp-urlconnection测试使模拟网络服务器崩溃,但仍通过

  20. 20

    通过网络服务获取数组时PHP中的未定义偏移量

  21. 21

    尝试通过向左或向右滑动来删除 RecycleView 项目(从网络服务加载)

  22. 22

    如何查看谁通过 wifi 从网络服务访问我的 IP 地址

  23. 23

    通过网络发送音频

  24. 24

    通过网络发送 AVPacket

  25. 25

    如何通过Windows Azure通过GCM通过唯一ID发送特定Android设备的通知?

  26. 26

    无法从gcm获取注册ID

  27. 27

    无法从GCM获取注册ID

  28. 28

    无法从gcm获取注册ID

  29. 29

    在python中通过TCP服务器网络发送对象

热门标签

归档