Android 试图理解程序的流程

Android 试图理解程序的流程,android,google-cloud-messaging,Android,Google Cloud Messaging,我正在尝试使用推送通知应用程序。我一直在关注Ravi Tamada的博客,因为我不了解其中一个课程的流程 课程如下 public class InitialActivity extends Activity { // label to display gcm messages TextView lblMessage; // Asyntask AsyncTask<Void, Void, Void> mRegisterTask; // Alert dialog manager Al

我正在尝试使用推送通知应用程序。我一直在关注Ravi Tamada的博客,因为我不了解其中一个课程的流程

课程如下

 public class InitialActivity extends Activity {
// label to display gcm messages
TextView lblMessage;

// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;

// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

// Connection detector
ConnectionDetector cd;

public static String name;
public static String email;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_pn);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(InitialActivity.this,
                "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Getting name, email from intent
    Intent i = getIntent();

    name = i.getStringExtra("name");
    email = i.getStringExtra("email");      

    // Make sure the device has the proper dependencies.
    GCMRegistrar.checkDevice(this);

    // Make sure the manifest was properly set - comment out this line
    // while developing the app, then uncomment it when it's ready.
    GCMRegistrar.checkManifest(this);

    lblMessage = (TextView) findViewById(R.id.lblMessage);

    registerReceiver(mHandleMessageReceiver, new IntentFilter(
            DISPLAY_MESSAGE_ACTION));

    // Get GCM registration id
    final String regId = GCMRegistrar.getRegistrationId(this);

    // Check if regid already presents
    if (regId.equals("")) {
        // Registration is not present, register now with GCM   
        lblMessage.append("inside first if condition where regid = null" + "\n\n"); 
        GCMRegistrar.register(this, SENDER_ID);
    } else {
        // Device is already registered on GCM
        if (GCMRegistrar.isRegisteredOnServer(this)) {
            // Skips registration.              
            Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
        } 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.
            lblMessage.append("inside 2nd if condition where regid != null and GCMRegistrar.isRegisteredOnServer(this) = false " + "\n");   
            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
                    lblMessage.append("inside doinbackground" + "\n\n");
                    ServerUtilities.register(context, name, email, regId);
                    return null;
                }

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

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

/**
 * Receiving push messages
 * */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        lblMessage.append("inside BroadcastReceiver mHandleMessageReceiver " + "\n\n"); 
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        // Waking up mobile if it is sleeping
        WakeLocker.acquire(getApplicationContext());

        /**
         * Take appropriate action on this message
         * depending upon your app requirement
         * For now i am just displaying it on the screen
         * */

        // Showing received message
        lblMessage.append(newMessage + "\n\n");         
        Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
        // From Demo Server: successfully added device!
        // Releasing wake lock
        WakeLocker.release();
    }
};

@Override
protected void onDestroy() {
    if (mRegisterTask != null) {
        mRegisterTask.cancel(true);
    }
    try {
        lblMessage.append("onDestroy " + "\n"); 
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(this);
    } catch (Exception e) {
        Log.e("UnRegister Receiver Error", "> " + e.getMessage());
    }
    super.onDestroy();
}
公共类InitialActivity扩展活动{
//显示gcm消息的标签
文本视图LBL消息;
//阿森塔克
异步任务mRegisterTask;
//警报对话框管理器
AlertDialogManager alert=新建AlertDialogManager();
//连接检测器
连接检测器cd;
公共静态字符串名;
公共静态字符串电子邮件;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u main\u pn);
cd=新连接检测器(getApplicationContext());
//检查互联网是否存在
如果(!cd.isConnectingToInternet()){
//Internet连接不存在
alert.showAlertDialog(InitialActivity.this,
“Internet连接错误”,
“请连接到正在工作的Internet连接”,错误);
//通过返回停止执行代码
返回;
}
//从intent获取姓名、电子邮件
Intent i=getIntent();
名称=i.getStringExtra(“名称”);
email=i.getStringExtra(“电子邮件”);
//确保设备具有正确的依赖项。
GCMRegistar.检查装置(本);
//确保清单设置正确-注释此行
//开发应用程序时,请在应用程序准备就绪时取消注释。
GCMRegistar.检查清单(本);
lblMessage=(TextView)findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver,新意向过滤器(
显示(信息(动作));
//获取GCM注册id
最终字符串regId=gcmregistar.getRegistrationId(this);
//检查regid是否已出现
if(regId.equals(“”){
//注册不存在,请立即向GCM注册
lblMessage.append(“在regid=null的第一个if条件内”+”\n\n”);
GCMRegistar.register(这是发送者的ID);
}否则{
//设备已在GCM上注册
if(GCMRegistrar.isRegisteredOnServer(本)){
//跳过注册。
Toast.makeText(getApplicationContext(),“已向GCM注册”,Toast.LENGTH_LONG.show();
}否则{
//尝试再次注册,但不要在UI线程中注册。
//还需要取消onDestroy()线程,
//因此,使用AsyncTask而不是原始线程。
lblMessage.append(“第二个if条件内,其中regid!=null,gcmregistar.isRegisteredOnServer(this)=false”+“\n”);
最终上下文=此;
mRegisterTask=newasynctask(){
@凌驾
受保护的Void doInBackground(Void…参数){
//在我们的服务器上注册
//在服务器上创建新用户
lblMessage.append(“内部doinbackground”+“\n\n”);
注册(上下文、名称、电子邮件、regId);
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
mRegisterTask=null;
}
};
mRegisterTask.execute(null,null,null);
}
}
}       
/**
*接收推送消息
* */
专用最终广播接收器mHandleMessageReceiver=新广播接收器(){
@凌驾
公共void onReceive(上下文、意图){
lblMessage.append(“内置广播接收器mHandleMessageReceiver”+“\n\n”);
String newMessage=intent.getExtras().getString(额外消息);
//在手机处于睡眠状态时唤醒手机
获取(getApplicationContext());
/**
*对此消息采取适当的操作
*取决于您的应用程序要求
*现在我只是把它显示在屏幕上
* */
//显示收到的信息
lblMessage.append(newMessage+“\n\n”);
Toast.makeText(getApplicationContext(),“新消息:”+newMessage,Toast.LENGTH\u LONG.show();
//从演示服务器:已成功添加设备!
//释放尾流锁
WakeLocker.release();
}
};
@凌驾
受保护的空onDestroy(){
if(mRegisterTask!=null){
mRegisterTask.cancel(true);
}
试一试{
lblMessage.append(“onDestroy”+“\n”);
未注册接收者(mHandleMessageReceiver);
GCMRegistar.ondestory(本);
}捕获(例外e){
Log.e(“取消注册接收器错误”,“>”+e.getMessage());
}
super.ondestory();
}
}

现在它的输出如下。。


节目进入广播接收机3次。。这是怎么发生的?我将相同的代码应用于另一个应用程序,但该代码只进入广播接收器一次。。那么到底发生了什么呢?

评论说明了一切。查看开头的代码,您将检查internet连接。第二,一旦选中,您将注册接收GCM消息的接收器。首先,您将尝试从GCM服务器获取设备的注册ID。如果未注册(您将获得“”),请尝试在GCM服务器中注册您的设备,这对于获取GCM消息非常重要。一旦注册了该应用程序项目(您将无法获得任何ID),请尝试在您的服务器中注册,因为您的服务器需要具有唯一的手机注册ID才能发送GCM消息。接收方接收来自GCM的消息。这就是整个代码所说的。对于分步代码,对不起。你至少需要为此付出一些努力。

你可以问问Ravi Tamada,不管他是谁is@Alex是的。。没有回应。。我有点迫切需要这个……我建议你不要使用这个博客(这不是最近的),而是使用当前GCM的官方演示。