標籤:簡訊 xml 通訊 處理序間通訊
在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();
returnfalse;
}
}
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();
returnfalse;
}
}
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-permissionandroid:name="android.permission.SEND_SMS"/>
實際上,包含商務邏輯的時間監聽器將導致程式的現實邏輯和商務邏輯耦合,從玩兒增加程式後期的維護難度。
如果確實有多個實現監聽器需要實現相同的商務邏輯功能,可以考慮使用商務邏輯組件來定義商務邏輯功能,再讓事件監聽器來調用商務邏輯組件的商務邏輯方法。