如何在android中以与VB6'相同的方式启动或调用onCreate;s形荷载
我的android应用程序有活动A和B。我需要的是在启动时启动我的活动B,而不显示它,当然显示活动A,因为它是主要活动 这是我的主要活动代码:如何在android中以与VB6'相同的方式启动或调用onCreate;s形荷载,android,vb6,runnable,oncreate,Android,Vb6,Runnable,Oncreate,我的android应用程序有活动A和B。我需要的是在启动时启动我的活动B,而不显示它,当然显示活动A,因为它是主要活动 这是我的主要活动代码: public class MainActivity extends Activity { private static final String PROJECT_ID = "api-project-xxxxxxxxxxxxx"; AsyncTask<Void, Void, Void> mRegisterTask; A
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);
}
}
}
}
公共类MainActivity扩展活动{
私有静态最终字符串项目\u ID=“api-PROJECT-XXXXXXXXXXXX”;
异步任务mRegisterTask;
AlertDialogManager adm=新建AlertDialogManager();
连接检测器cd;
公共静态字符串billName;
公共静态字符串emailAdd;
公共静态字符串accntNum;
按钮addDevice、showDevice、showDialog、register;
开关开关;
TextView txtRegStatusResult,txtBroadcastMsg;
私有字符串registrationStatus=“尚未注册”;
私有字符串broadcastMessage=“无广播消息”;
字符串[]arrContentTxt;
最终上下文ctx=此;
int notifCount=0;
int x=0;
int contentTxtLength;
处理者notifLauncher,notifStopper;
字符串contentTxt;
GlobalVariables gv=新的GlobalVariables();
int delay=gv.REMENTERDELAY;
int stopDelay=延迟-(延迟/5);
手;
意向过滤器GCM过滤器;
//billCompute的新变量集
//账单计算
整数瓦特;
int timerFirstRun;
整小时=1;
每日双瓦;
每天两千瓦;
双千瓦/月;
//账单
int-id;
整数瓦特;
int stat;
字符串名;
//也适用于账单计算
双倍比尔/月;
双res;
//全局变量
双成本月=gv.成本月;
处理者;
处理器适配器;
//结束新变量
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addDevice=(按钮)findViewById(R.id.btnAddDevice);
showDevice=(按钮)findViewById(R.id.btnShowDevice);
showDialog=(按钮)findViewById(R.id.btnShowDialog);
寄存器=(按钮)findViewById(R.id.btnMainRegister);
swiGCM=(开关)findViewById(R.id.switchGCM);
txtRegStatusResult=(TextView)findviewbyd(R.id.txtStatus);
txtBroadcastMsg=(TextView)findViewById(R.id.txtBroadcastMsg);
txtRegStatusResult=(TextView)findViewById(R.id.lblStatus);
Log.d(“Batelec”,“启动LBillval”);
//ListViewForm.lblBillVal.setText(“”);
Log.d(“Batelec”,“启动LBillval”);
Intent i=getIntent();
billName=i.getStringExtra(billName);
emailAdd=i.getStringExtra(emailAdd);
accntNum=i.getStringExtra(accntNum);
//本地notif
Resources res=getResources();
arrContentTxt=res.getStringArray(R.array.notifContentText);
contentTxtLength=arrContentTxt.length;
Log.d(“Batelec”,“content-txt-length:+contentTxtLength”);
Log.d(“Batelec”,“启动ListViewForm活动”);
startActivity(新意图(MainActivity.this、ListViewForm.class));
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
/*DialogFragment diag=新开关检查更改();
diag.show(getFragmentManager(),“cbo单击”)*/
showNotif();
}
});
gcmFilter=newintentfilter();
gcmFilter.addAction(“GCM_已收到_操作”);
使用NotifLauncher();
//使用notifstopper();
//bullcomputer.useHandler();
swiGCM.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
Log.d(“Batelec”,“内部开关GCM”);
if(swiGCM.isChecked()){
connectToGCMServer();
}
}
});
}
//连接到gcm
public void connectToGCMServer(){
//试一试{
Log.d(“Batelec”,“启动gcm客户端”);
//启动gcm
cd=新连接检测器(getApplicationContext());
Log.d(“Batelec”,“负载连接检测器”);
//检查互联网是否存在
如果(!cd.isConnectingToInternet()){
//Internet连接不存在
adm.showAlertDialog(MainActivity.this,“Internet连接错误”,
“请连接到工作的Internet连接”,错误);
//通过返回停止执行代码
Log.d(“Batelec”,“未连接到互联网”);
回来
}
//确保设备具有正确的依赖项。
GCM注册检查装置(ctx);
日志d(“Batelec”,“设备检查”);
//确保清单设置正确-注释此行
//开发应用程序时,请在应用程序准备就绪时取消注释。
GCMRegistrar.检查清单(ctx);
日志d(“Batelec”,“检查舱单”);
registerReceiver(mHandleMessageReceiver,新意向过滤器(显示消息和操作));
Log.d(“Batelec”,“注册接收人”);
//获取GCM注册id
最终字符串regId=gcmregistar.getRegistrationId(ctx);
Log.d(“Batelec”,“获取注册id”);
试一试{
//检查regid是否已出现
if(regId.equals(“”){
//注册不存在,请立即向GCM注册
GCMRegistar.register(这是发送者的ID);
Log.d(“Batelec”,“注册id为空,注册设备”);
}
否则{
//设备已在GCM上注册
if(GCMRegistrar.isRegisteredOnServer(本)){
//跳过注册。
Toast.makeText(getApplicationContext(),“已向GCM注册”,Toast.LENGT