解析登录API上的推送通知的注册ID

时间:2015-09-05 10:40:40

标签: java android push-notification google-cloud-messaging sharedpreferences

我正在运行一个问题,我需要将我的注册ID解析到我的服务器抛出API,我在启动屏幕活动中获取我的注册ID,并在我将该值传递给登录活动之后。在登录活动中,我将注册ID添加到共享首选项,并尝试通过从共享首选项获取保存的值来在doinbackground中发送值。解析第一次成功从共享首选项获取注册ID但当我注销并尝试再次登录时,我的注册ID正在解析默认值“id”。

Loginactivity.java

    package com.driverapp.inis.zuber;

import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import Connectivity_manager.Httpmanager;
import Connectivity_manager.Internet_CheckingActivity;
import Session_manager.SessionManager;
import UI_Alert.AlertDialogManager;
import UI_Alert.TransparentProgressDialog;


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";
private String regid;
    private String regId = null;


    @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);
        regid= getIntent().getStringExtra("regig");
        msessionManager.setregid("registrationid",regid);
       regId = msessionManager.getregistration("registrationid","id");


//        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) {


            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, regId));
            Log.d("regid", regId);
            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("");
        }
    }
    }

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

                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);
                    Log.d(TAG, "Current Device's Registration ID is: " + regid);

                } catch (IOException ex) {
                    regid = "Error :" + ex.getMessage();
                }
                return null;
            }

            protected void onPostExecute(Object result) {
                Intent myIntent = new Intent(Splashscreen.this, LoginActivity.class);
                myIntent.putExtra("regig", regid);
                Splashscreen.this.startActivity(myIntent);
            };

        } .execute(null,null,null);
    }
}

Sessionmanager.java

    package Session_manager;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

import com.driverapp.inis.zuber.LoginActivity;
import com.driverapp.inis.zuber.Splashscreen;

import java.util.HashMap;

public class SessionManager {
    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "name";

    // All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";

    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "username";

    // Reg Id for GCM (make variable public to access from outside)
    public static final String KEY_Regid = "regid";

    public static final String KEY_ID = "userid";

    //trip id
    public static final String Key_trip = "trip_id";

    // Constructor
    public SessionManager(Context context){
        this._context = context;
        pref = PreferenceManager.getDefaultSharedPreferences(_context);//_context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    /**
     * Create login session
     * */
    public void createLoginSession(String name, String id){
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);

        // Storing name in pref
        editor.putString(KEY_NAME, name);


        // Storing id in pref
        editor.putString(KEY_ID, id);

        // commit changes
        editor.commit();
    }

    //create trip id

    public void tripid(String tid){
        editor.putString(Key_trip,tid);
        editor.commit();
    }

    //get stored data for trip id

    public HashMap<String,String> gettripid(){
        HashMap<String,String>tid = new HashMap<String,String>();
        tid.put(Key_trip,pref.getString(Key_trip,null));
        return tid;
    }

    /**
     * Create RegId session
     * */
    public void createRegIdSession(String regid){
//        // Storing login value as TRUE
//        editor.putBoolean(IS_LOGIN, true);

        // Storing name in pref
        editor.putString(KEY_Regid, regid);
        // commit changes
        editor.commit();
    }

    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     * */
    public void checkLogin(){
        // Check login status
        if(!this.isLoggedIn()){
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

    }
    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        HashMap<String, String> id = new HashMap<String, String>();
        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));

        // user email id

        user.put(KEY_ID, pref.getString(KEY_ID, null));

        // return user
        return user;
    }

    /**
     * Get stored session data for regid
     * */
    public HashMap<String, String> getUserregidDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_Regid, pref.getString(KEY_Regid, null));
        return user;
    }
    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, Splashscreen.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

    /**
     * Quick check for login
     * **/
    // Get Login State
    public boolean isLoggedIn(){
        return pref.getBoolean(IS_LOGIN, false);

    }

    public String getString(String key, String defaultVal){
        return pref.getString(key, defaultVal);
    }

    public String getregistration(String key, String dvalue){
        return pref.getString(key,dvalue);
    }

    public void setregid(String key,String value){
    Editor editor1 = pref.edit();
        editor1.putString(key, value);
//      editor.apply();
        editor1.commit();
    }

    public void setString(String key, String value){
        Editor e = pref.edit();
        e.putString(key, value);
        e.apply();
    }
}

0 个答案:

没有答案