来自C2DM注册类的Android更新UI



我已经设置并运行了C2DM。它还将用户ID发送到我的服务器,这样我就可以向它发送消息。然而,我很难更新UI,提醒用户注册状态。我遇到的问题是,注册是在一个不是活动的类中处理的,所以我很难弄清楚如何提醒用户。

我有一个类"RegistrationScreen",它包含以下内容:

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class RegistrationScreen extends Activity {

    public static int status;
    public static String userID;
    public static String regPass;
    public static int bankID=201;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registrationscreen);
        Button btn1 = (Button)findViewById(R.id.registerSubmitButton);
        btn1.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View arg0) {
                //Get data from form
                final EditText userIdText = (EditText) findViewById(R.id.userID);
                userID = userIdText.getText().toString();
                final EditText userPasswordText = (EditText) findViewById(R.id.userPassword);
                regPass = userPasswordText.getText().toString();

                register();
            }
        });
    }
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 0:
            Dialog superSimpleDlg = new Dialog(this);
            superSimpleDlg.setTitle("blah");
            return superSimpleDlg;
        }
        return null;
    }
    private void register() {
        status=1; //1= being processed
        String emailOfSender ="*removed*";
        Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
        registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
        registrationIntent.putExtra("sender", emailOfSender);
        startService(registrationIntent);
        //        while(status==1){
        //          
        //        }
        showDialog(0);
        //TODO Show "Registering..." dialogue???
    }
}

这成功地调用了注册过程。然而,我想在它进行注册过程中显示一个"处理对话框",并在它成功注册时显示一个"确认对话框"。

我有另一个类"C2DMReceiver",它处理谷歌服务器的注册,还使用套接字在我自己的服务器上注册。

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
public class C2DMReceiver extends BroadcastReceiver {
    private static String KEY = "c2dmPref";
    private static String REGISTRATION_KEY = "registrationKey";
    private Context context;
    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
            handleRegistration(context, intent);
        } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
            handleMessage(context, intent);
        }
    }
    private void handleRegistration(Context context, Intent intent) {
        String registration = intent.getStringExtra("registration_id");
        if (intent.getStringExtra("error") != null) {
            // Registration failed, should try again later.
            Log.d("c2dm", "registration failed");
            String error = intent.getStringExtra("error");
            if(error == "SERVICE_NOT_AVAILABLE"){
                Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
            }else if(error == "ACCOUNT_MISSING"){
                Log.d("c2dm", "ACCOUNT_MISSING");
            }else if(error == "AUTHENTICATION_FAILED"){
                Log.d("c2dm", "AUTHENTICATION_FAILED");
            }else if(error == "TOO_MANY_REGISTRATIONS"){
                Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
            }else if(error == "INVALID_SENDER"){
                Log.d("c2dm", "INVALID_SENDER");
            }else if(error == "PHONE_REGISTRATION_ERROR"){
                Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
            }
        } else if (intent.getStringExtra("unregistered") != null) {
            // unregistration done, new messages from the authorized sender will be rejected
            Log.d("c2dm", "unregistered");
        } else if (registration != null) {
            Log.d("c2dm", registration);
            Editor editor =
                    context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
            editor.putString(REGISTRATION_KEY, registration);
            editor.commit();
            registerWithServer(registration);
            // Send the registration ID to the 3rd party site that is sending the messages.
            // This should be done in a separate thread.
            // When done, remember that all registration is done.
        }
    }
    private void handleMessage(Context context, Intent intent)
    {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            // String blah = (String) extras.get("POSTFIELDS");
            Log.d("c2dm", "recieved: "+extras.getString("message"));
        }
    }
    private void registerWithServer(String c2dmID) {
        String hostname = "10.0.2.2";
        int port = 54321;
        socketClient client = new socketClient(hostname, port);
        String message = client.sendMessage("registerRSA|c2dmID="+c2dmID+",userID="+RegistrationScreen.userID+",bankID="+RegistrationScreen.bankID+",passcode="+RegistrationScreen.regPass+",deviceID=njfdfdsj389rfb,timestamp=00000,");
        Log.v("SOCKETCLIENT",message);
        //Do actions on input string
        String tokens[] = message.split("\|");
        System.out.println(tokens[0]);
        //
        if (tokens[0].equals("success")) {
            RegistrationScreen.status=100;
        } else if (tokens[0].equals("error")) {
            int errorID = 0;
            String friendlyErrorMessage = null;
            //Split the , then the =
            String variables[] = tokens[1].split(",");
            for (int i=0; i<variables.length; i++) {
                String tempSplit[] = variables[i].split("=");
                if (tempSplit[0].equals("errorID")) {
                    errorID=Integer.parseInt(tempSplit[1]);
                } else if (tempSplit[0].equals("friendlyErrorMessage")) {
                    friendlyErrorMessage=tempSplit[1];
                } 
            }
            //Update UI to alert of error
            //TextView textViewToChange = (TextView) findViewById(R.id.registerTextHeader);
            //textViewToChange.setText("Error getting seed! (ERR" + errorID + ") " + friendlyErrorMessage);
            RegistrationScreen.status=200;
        } else {
            RegistrationScreen.status=300;
            //unknown problem
        }
    }
}

正如你所看到的,我曾尝试使用while循环检查"状态"变量来实现它,但这会导致程序挂起,而且似乎不是很有效的编程。

在这种情况下,您可以使用SharedPreferenceListener。

一旦用户注册成功,请尝试以下操作:

  SharedPreferences prefs = PreferenceManager
 .getDefaultSharedPreferences(this.getApplicationContext());
 Editor edit = prefs.edit();
 edit.putBoolean("isRegistered",true).commit();

一旦用户注销成功,请尝试以下操作:

  SharedPreferences prefs = PreferenceManager
 .getDefaultSharedPreferences(this.getApplicationContext());
 Editor edit = prefs.edit();
 edit.putBoolean("isRegistered",false).commit();

在你的活动中,创建一个文本视图(或者你喜欢的东西。我在这个例子中使用的是文本视图)。您可以将此代码放在OnCreate()中的某个位置;

 SharedPreferences prefs = PreferenceManager
 .getDefaultSharedPreferences(this.getApplicationContext());
 OnSharedPreferenceChangeListener listener;
 listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences arg0,
        String key) {
        if (key.equalsIgnoreCase("isRegistered")) {
            Log.v("RegistrationScreen", "registration status changed");             
            if (prefs.getBoolean("isRegistered", false))
                {
                  textView.setText("Registered Successfully");
                }
                else
                {
                  textView.setText("Successfully UnRegistered");
                }
        }
    }
};
    prefs.registerOnSharedPreferenceChangeListener(listener);

希望这有帮助。。。

最新更新