在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"/>
实际上,包含业务逻辑的时间监听器将导致程序的现实逻辑和业务逻辑耦合,从玩儿增加程序后期的维护难度。如果确实有多个实现监听器需要实现相同的业务逻辑功能,可以考虑使用业务逻辑组件来定义业务逻辑功能,再让事件监听器来调用业务逻辑组件的业务逻辑方法。