首页 > 代码库 > 外部类监听发送短信--------------------------setOnLongClickListener------------------------

外部类监听发送短信--------------------------setOnLongClickListener------------------------

定义了两个Java。一个作为事件监听器发送短信。MainActivity调用它。

---------------------------外部类监听器-------------------

SendSMsListener.java

package com.example.admin.webchanjian;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
* Created by admin on 2016/10/6.
*/
public class SendSMsListener implements View.OnLongClickListener {
private Activity activity;
private EditText address;
private EditText content;
public SendSMsListener(Activity activity,EditText address,EditText content){
this.activity=activity;
this.address=address;
this.content=content;
}

@Override
public boolean onLongClick(View v) {
String addressStr=address.getText().toString();
String contentStr=content.getText().toString();
//获取信息管理器
SmsManager smsManager=SmsManager.getDefault();
//创建发送信息的PendingIntent
PendingIntent pendingIntent=PendingIntent.getBroadcast(activity,0,new Intent(),0);
smsManager.sendTextMessage(addressStr,null,contentStr,pendingIntent,null);
Toast.makeText(activity,"短信发送完成",Toast.LENGTH_LONG).show();
return false;
}
}


-------------------------MainActivity-------------------------

//------------------------sent messages---------------------
EditText address;
EditText content;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sentsmslistener);
address=(EditText) findViewById(R.id.address);
content=(EditText) findViewById(R.id.content);
Button btn=(Button) findViewById(R.id.sent);
btn.setOnLongClickListener(new SendSMsListener(this,address,content));
}
}


--------------------------------布局-------------------------------------------
sentsmslistener.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="35dp"
/>
<EditText
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="35dp"
/>
<Button
android:id="@+id/sent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
android:textSize="35dp"
/>
</LinearLayout>

技术分享

 

外部类监听发送短信--------------------------setOnLongClickListener------------------------