如何以与VB6的Form_Load相同的方式或方式在android中启动或调用onCreate

时间:2015-10-17 12:28:51

标签: android vb6 runnable oncreate

我的Android应用程序让我们说活动A和B.我需要的是在启动时启动我的活动B而不显示它,当然还显示活动A,因为它是主要的活动。

这是我的MainActivity代码:

public class MainActivity extends Activity {

    private static final String PROJECT_ID = "api-project-xxxxxxxxxxxxx";
    AsyncTask<Void, Void, Void> mRegisterTask;
    AlertDialogManager adm = new AlertDialogManager();
    ConnectionDetector cd;

    public static String billName;
    public static String emailAdd;
    public static String accntNum;

    Button addDevice, showDevice, showDialog, register;
    Switch swiGCM;
    TextView txtRegStatusResult, txtBroadcastMsg;

    private String registrationStatus = "Not yet registered";
    private String broadcastMessage = "No broadcast message";

    String[] arrContentTxt;
    final Context ctx = this;
    int notifCount = 0;
    int x = 0;
    int contentTxtLength;
    Handler notifLauncher, notifStopper;
    String contentTxt;
    GlobalVariables gv = new GlobalVariables();
    int delay = gv.reminderDelay;
    int stopDelay = delay - (delay / 5);
    Handler hand;

    IntentFilter gcmFilter;

    //new set of variables for billCompute
    //for bill compute
    int totalWatt;
    int timerFirstRun;
    int totalHour = 1;
    double wattHourPerDay;
    double kiloWattPerDay;
    double kiloWattPerMonth;

    //bill
    int id;
    int watt;
    int stat;
    String name;

    //also for bill compute
    double billPerMonth;
    Double res;

    //global variables
    double costPerMonth = gv.costPerMonth;

    Handler handler;
    Handler adapter;

    //end new variables
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addDevice = (Button)findViewById(R.id.btnAddDevice);
        showDevice = (Button)findViewById(R.id.btnShowDevice);
        showDialog = (Button)findViewById(R.id.btnShowDialog);
        register = (Button)findViewById(R.id.btnMainRegister);
        swiGCM = (Switch)findViewById(R.id.switchGCM);

        txtRegStatusResult = (TextView)findViewById(R.id.txtStatus);
        txtBroadcastMsg = (TextView)findViewById(R.id.txtBroadCastMsg);
        txtRegStatusResult = (TextView) findViewById(R.id.lblStatus);

        Log.d("Batelec", "initiating lblBillVal");
        //ListViewForm.lblBillVal.setText("");
        Log.d("Batelec", "initiated lblBillVal");
        Intent i = getIntent();
        billName = i.getStringExtra(billName);
        emailAdd = i.getStringExtra(emailAdd);
        accntNum = i.getStringExtra(accntNum);

        //for local notif 
        Resources res = getResources();
        arrContentTxt = res.getStringArray(R.array.notifContentText);

        contentTxtLength = arrContentTxt.length;
        Log.d("Batelec", "content txt length: "+contentTxtLength);

        Log.d("Batelec", "starting ListViewForm activity");
        startActivity(new Intent(MainActivity.this, ListViewForm.class));

        showDialog.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                /*DialogFragment diag = new SwitchCheckChange();
                diag.show(getFragmentManager(), "cbo Click");*/
                showNotif();
            }

        });

        gcmFilter = new IntentFilter();
        gcmFilter.addAction("GCM_RECEIVED_ACTION");

        useNotifLauncher();
        //useNotifStopper();
        //BillComputer.useHandler();

        swiGCM.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                Log.d("Batelec", "inside switch GCM");
                if(swiGCM.isChecked()){
                    connectToGCMServer();
                }
            }

        });

    }

    //connect to gcm
    public void connectToGCMServer(){
        //try{
            Log.d("Batelec", "start gcm client");
            //start gcm
            cd = new ConnectionDetector(getApplicationContext());
            Log.d("Batelec", "loaded connection detector");  
            // Check if Internet present
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                adm.showAlertDialog(MainActivity.this, "Internet Connection Error",
                "Please connect to a working Internet connection", false);
                // stop executing code by return
                Log.d("Batelec", "not connecting to internet");
                return;
            }

            // Make sure the device has the proper dependencies.
            GCMRegistrar.checkDevice(ctx);
            Log.d("Batelec", "device checked");
            // Make sure the manifest was properly set - comment out this line
            // while developing the app, then uncomment it when it's ready.
            GCMRegistrar.checkManifest(ctx);
            Log.d("Batelec", "manifest checked");


            registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
            Log.d("Batelec", "registered receiver");
            // Get GCM registration id
            final String regId = GCMRegistrar.getRegistrationId(ctx);
            Log.d("Batelec", "acquire registration id");


            try{
            // Check if regid already presents
            if (regId.equals("")) {
                // Registration is not present, register now with GCM           
                GCMRegistrar.register(this, SENDER_ID);
                Log.d("Batelec", "registration id is null, registering device");
            }
            else {
                // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.              
                Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
                Log.d("Batelec", "device already registered");
            } 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.
                Log.d("Batelec", "registering again using AsyncTask");
                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, billName, emailAdd, accntNum, regId);
                        Log.d("Batelec", "registering user to server");
                        return null;
                    }

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

                };
                mRegisterTask.execute(null, null, null);
                }
            }//end gcm
        }catch(Exception e){
            Log.d("Batelec", "GCM Client Err: "+e);
        }

    }

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            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
            txtRegStatusResult.append(newMessage + "\n");           
            Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

            // Releasing wake lock
            WakeLocker.release();
        }
    };

    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            //unregisterReceiver(mHandleMessageReceiver);
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }

    public void registerClick(View v){
        Intent i = new Intent(this, RegisterActivity.class);
        startActivity(i);
    }
    //start countdown for showing local notif
    public void useNotifLauncher(){
        notifLauncher = new Handler(){
             @Override
              public void handleMessage(Message msg) {
                  Bundle bundle = msg.getData();
                  String string = bundle.getString("myKey");
                  Log.d("Batelec", "in handler string val: "+string);
                  try{
                      ListViewForm.lblBillVal.setText(string);
                  }
                  catch(Exception e){
                      Log.d("Batelec", "handler err: "+e);
                  }
                  gv.billVal = string;
                  Log.d("Batelec", "main gv.billVal: "+gv.billVal);
              }
        };
        notifLauncher.postDelayed(runNotif, delay);
    }

    public Runnable runNotif = new Runnable(){

        @Override
        public void run() {
            showNotif();
            billCompute();
            notifLauncher.postDelayed(runNotif, delay);
        }

    };

    public void useNotifStopper(){
        notifStopper = new Handler();
        notifStopper.postDelayed(stopNotif, stopDelay);
    }
    //destroy local notif
    public Runnable stopNotif = new Runnable(){

        @Override
        public void run() {

            cancelNotification(x);
            notifStopper.postDelayed(stopNotif, stopDelay);
        }

    };

    // If the user changes the orientation of his phone, the current activity
        // is destroyed, and then re-created.  This means that our broadcast message
        // will get wiped out during re-orientation.
        // So, we save the broadcastmessage during an onSaveInstanceState()
        // event, which is called prior to the destruction of the activity.
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

        super.onSaveInstanceState(savedInstanceState);

        savedInstanceState.putString("BroadcastMessage", broadcastMessage);

    }

    // When an activity is re-created, the os generates an onRestoreInstanceState()
    // event, passing it a bundle that contains any values that you may have put
    // in during onSaveInstanceState()
    // We can use this mechanism to re-display our last broadcast message.      
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);

        broadcastMessage = savedInstanceState.getString("BroadcastMessage");
        txtBroadcastMsg.setText(broadcastMessage);
    }


    // If our activity is paused, it is important to UN-register any
    // broadcast receivers.
    @Override
    protected void onPause() {

        unregisterReceiver(mHandleMessageReceiver);
        super.onPause();
    }

    // When an activity is resumed, be sure to register any
    // broadcast receivers with the appropriate intent
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mHandleMessageReceiver, gcmFilter);

    }

    //add device button
    public void addClick(View v){
        Intent i = new Intent(this, AddDeviceForm.class);
        startActivity(i);
    }
    //show device button
    public void showClick(View v){
        Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
        Intent i = new Intent(this, ListViewForm.class);
        startActivity(i);
    }
    //show local notif
    public void showNotif(){
        contentTxt = arrContentTxt[notifCount];
        Log.d("Batelec", "main notifCount: "+notifCount);

        Bundle b = new Bundle();
        b.putInt("notifCountNum", notifCount);


        Uri notifSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent i = new Intent(MainActivity.this, NotifReceiver.class);
        i.putExtras(b);
        PendingIntent pi = PendingIntent.getActivity(MainActivity.this, (int)(Math.random()*100), i, 0);

        Notification notif = new Notification.Builder(this)
            .setContentTitle("MyPower Reminder")

            .setContentText(contentTxt)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pi)
            .setSound(notifSound)

            .addAction(0, "View Full Reminder", pi)
            .build();

        NotificationManager notifMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notifMgr.notify(0, notif);

        notifCount++;
        if(notifCount == contentTxtLength){
            notifCount = 0;
        }
    }
    //destroy local notif
    public void cancelNotification(int notificationId){

        if (Context.NOTIFICATION_SERVICE!=null) {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
            nMgr.cancel(notificationId);
        }
    }

    public void billCompute(){

        TodoItemDatabase td = new TodoItemDatabase(ctx);
        Cursor cur = td.getActiveDevice();

        if(timerFirstRun == 0){
            timerFirstRun++;
            Log.d("batelec", "timer = 0");
        }
        else{
            try{
                if(cur != null){
                    Toast.makeText(ctx, "1 hour elapsed", Toast.LENGTH_LONG).show();

                    cur.moveToFirst();
                    for(int x = 1; x <= cur.getCount(); x++){
                        id = cur.getInt(cur.getColumnIndex("_id"));
                        name = cur.getString(cur.getColumnIndex("deviceName"));
                        watt = cur.getInt(cur.getColumnIndex("deviceWattage"));
                        stat = cur.getInt(cur.getColumnIndex("deviceStatus"));

                        totalWatt = totalWatt + watt;
                        Log.d("batelec", "id: " + id + " name: " + name + " watt: " + watt + " status: " + stat);
                        cur.moveToNext();
                    }
                    //totalWatt = 125;
                    Log.d("batelec", "total watt: "+totalWatt);

                    wattHourPerDay = totalWatt;//all active device wattage 
                    Log.d("batelec", "wattPerHour: "+wattHourPerDay+" (totalWatt)");

                    kiloWattPerDay = wattHourPerDay / 1000;//all device watts divided by 1000 watts = 1 kW
                    Log.d("batelec", "kilowatt per day: "+kiloWattPerDay+" (wattPerHour / 1000)");

                    kiloWattPerMonth = (wattHourPerDay * 30) / 1000;//watts per month
                    Log.d("batelec", "kiloWatt per month: "+kiloWattPerMonth+" ((wattPerHour * 30) / 1000)");

                    billPerMonth = kiloWattPerMonth * costPerMonth;//estimated bill per month
                    Log.d("batelec", "bill per month: "+billPerMonth+" (kiloWattPerMonth * costPerMonth)");


                    //Double res;
                    DecimalFormat df = new DecimalFormat("#.##");
                    res = Double.valueOf(df.format(billPerMonth));

                    Log.d("batelec", "new bill: "+res);
                    //ListViewForm.lblBillVal.setText(String.valueOf(res));

                    Message msg = notifLauncher.obtainMessage();
                    Bundle bundle = new Bundle();
                    Log.d("Batelec", "res val: "+String.valueOf(res));
                    bundle.putString("myKey", String.valueOf(res));
                    msg.setData(bundle);
                    notifLauncher.sendMessage(msg);
                }
            }catch(Exception e){
                    Log.d("batelec", "MainErr: "+e);
                }
        }

    }
}

正如您所看到的,我已经在我的应用中使用了startActivity。但正如我之前所说,我只是想开始活动B而不是显示它,就像我们如何在VB6中调用Form_Load一样。如果他们是一种隐藏活动B的方式,如果它开始,你能教我如何尽可能最详细的方式。我会很感激

0 个答案:

没有答案