这段时间一直的忙着看Android Dev Guild, 所以顺便把自己学习的一些经验分享出来: 欢迎大家指正!
下面的代码是演示一个简单的计算器的功能;
在Activity中主要是完成与User interaction的操作, 计算器输入数据的验证, 提示消息操作。
在Servicez中开启一个 新的线程, 完成简单(+, -, *, /)运算操作。
BroadCastReceive把Service计算的结果传回给Activity显示。
运行的结果
具体请看源代码
这是Activity 类的代码
package com.wjr.anoys;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class AnoYunsuanActivity extends Activity implements OnClickListener{
static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;
static final int DIALOG_GAMEOVER_ID1 = 2;
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Dialog mDialog;
switch (id) {
case DIALOG_GAMEOVER_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please test input para is valid or not?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AnoYunsuanActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
mDialog = (Dialog)builder.create();
mDialog.setTitle("Pay attention!!!");
return mDialog;
//break;
case DIALOG_PAUSED_ID:
//Context mContext = getApplicationContext(); //--------------> 错误的代码
//if run above sentence will occur the below error
//WindowManager$BadTokenException: Unable to add window -- token null is not for an application
mDialog = new Dialog(this);//--------------> 正确的代码
mDialog.setContentView(R.layout.custom_dialog);
mDialog.setTitle("Custom Dialog");
TextView text = (TextView) mDialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) mDialog.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
return mDialog;
case DIALOG_GAMEOVER_ID1:
AlertDialog.Builder builder1;
//Context mContext1 = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
(ViewGroup) findViewById(R.id.layout_root));
TextView text1 = (TextView) layout.findViewById(R.id.text);
text1.setText("Input parameter cannt be empty!");
ImageView image1 = (ImageView) layout.findViewById(R.id.image);
image1.setImageResource(R.drawable.icon);
builder1 = new AlertDialog.Builder(this);
builder1.setView(layout);
builder1.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AnoYunsuanActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
mDialog = (Dialog)builder1.create();
mDialog.setTitle("Pay attention!!!");
return mDialog;
default:
break;
}
return super.onCreateDialog(id);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
this.unregisterReceiver(mReceive);
super.onDestroy();
}
/** Called when the activity is first created. */
String num1, num2;
public EditText editText, editText1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mReceive = new myBroadcastReceive();
IntentFilter filter = new IntentFilter("service_action");
this.registerReceiver(mReceive, filter);
this.findViewById(R.id.cal_addBtn).setOnClickListener(this);
this.findViewById(R.id.cal_subBtn).setOnClickListener(this);
this.findViewById(R.id.cal_mulBtn).setOnClickListener(this);
this.findViewById(R.id.cal_divBtn).setOnClickListener(this);
}
public myBroadcastReceive mReceive;
class myBroadcastReceive extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String num1 = intent.getStringExtra("msg");
editText = (EditText)findViewById(R.id.res);
editText.setText(num1);//在Activity EditText控件显示, 通过BroadCastReceive显示Service计算的结果
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent my = new Intent(AnoYunsuanActivity.this, YService.class);
Bundle myBundle = new Bundle();
editText = (EditText)findViewById(R.id.Num1);
editText1 = (EditText)findViewById(R.id.Num2);
String num1 = new String();
num1 = editText.getText().toString();
int len1 = editText.getText().toString().length();
String num2 = new String();
num2 = editText1.getText().toString();
int len2 = editText1.getText().toString().length();
boolean pan = false;
if (len1 > 0 && len2 > 0) {
pan = true;
}
myBundle.putString("num1", num1);
myBundle.putString("num2", num2);
my.putExtra("service", myBundle);
switch (v.getId()) {
case R.id.cal_addBtn:
myBundle.putInt("num3", 0);
break;
case R.id.cal_subBtn:
myBundle.putInt("num3", 1);
break;
case R.id.cal_mulBtn:
myBundle.putInt("num3", 2);
break;
case R.id.cal_divBtn:
myBundle.putInt("num3", 3);
if ("0".equals(num2) || "".equals(num1)) {
Toast.makeText(this, "error:the decimi is zeros", Toast.LENGTH_LONG).show();
return;
}
break;
default:
break;
}
if (pan) {
this.startService(my);//启动Service服务
}else {
showDialog(DIALOG_GAMEOVER_ID1);//提示计算输入参数为空, 或者做除法运算输入除数为零的提示消息
}
}
}
这里是Service类的代码
package com.wjr.anoys;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class YService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (intent != null) {
final Bundle myBundle = intent.getBundleExtra("service");
//开启一个新的线程, 专门做算术运算操作
new Thread(new Runnable() {
//获取Activity EditText控件输入的做运算的参数值
String num1 = myBundle.getString("num1").trim();
String num2 = myBundle.getString("num2").trim();
int iselect = myBundle.getInt("num3");int res = 0;//对应计算的结果@Overridepublic void run() {// TODO Auto-generated method stubswitch (iselect) {case 0:res = Integer.parseInt(num1.trim()) + Integer.parseInt(num2.trim());break;case 1:res = Integer.parseInt(num1) - Integer.parseInt(num2);break;case 2:res = Integer.parseInt(num1) * Integer.parseInt(num2);break;case 3:res = Integer.parseInt(num1) / Integer.parseInt(num2);break;default:break;}sendInfor(Integer.toString(res));}}).start();}return super.onStartCommand(intent, flags, startId);}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubreturn super.onUnbind(intent);}//iselect变量为选择计算的方式(+ - * /)
//通过这个函数向Activity发送对应广播事件
public void sendInfor(String msg){
Intent myIntent = new Intent("service_action");
myIntent.putExtra("msg", msg);
this.sendBroadcast(myIntent);
}
}
欢迎指教!如果需要源码可以给我联系, QQ 258130629
email:jr209152@gmail.com
今天就到这里吧!继续加油……