在Android中,使用内部类能够在当前类里面发用改监听器类,由于监听器类是外部类的内部类。所以能够自由訪问外部类的全部界面组件。
下面是一个调用系统内部类实现短信发送的一个样例:
SMS类:
package com.example.msmlistener;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class SMS implements OnLongClickListener{
private Activity act;
private EditText add;
private EditText content;
public SMS(Activity act, EditText addr, EditText content){
this.act = act;
this.add = addr;
this.content = content;
}
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
String addressStr = add.getText().toString();
String contentStr = content.getText().toString();
SmsManager sm = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent.getBroadcast(act, 0, new Intent(), 0);
sm.sendTextMessage(addressStr, null, contentStr, sentIntent, null);
Toast.makeText(act, "短信发送完毕!\n", Toast.LENGTH_LONG).show();
return false;
}
}
Activity XML:package com.example.msmlistener;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class SMS implements OnLongClickListener{
private Activity act;
private EditText add;
private EditText content;
public SMS(Activity act, EditText addr, EditText content){
this.act = act;
this.add = addr;
this.content = content;
}
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
String addressStr = add.getText().toString();
String contentStr = content.getText().toString();
SmsManager sm = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent.getBroadcast(act, 0, new Intent(), 0);
sm.sendTextMessage(addressStr, null, contentStr, sentIntent, null);
Toast.makeText(act, "短信发送完毕!
\n", Toast.LENGTH_LONG).show();
return false;
}
}
Activity JAVA:package com.example.msmlistener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText address;
EditText content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取页面信息
address = (EditText)findViewById(R.id.address);
content = (EditText)findViewById(R.id.content);
Button btnsend = (Button)findViewById(R.id.send);
btnsend.setOnLongClickListener(new SMS(this, address, content));
}
}
注意须要加入发送短信的权限到Manfest中:
<uses-permission android:name="android.permission.SEND_SMS"/>
实际上,包括业务逻辑的时间监听器将导致程序的现实逻辑和业务逻辑耦合,从玩儿添加程序后期的维护难度。假设确实有多个实现监听器须要实现同样的业务逻辑功能。能够考虑使用业务逻辑组件来定义业务逻辑功能,再让事件监听器来调用业务逻辑组件的业务逻辑方法。