activity类:
package com.example.toast_04;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView text =null;
private Button button =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
button= (Button)findViewById(R.id.button);
String s = "收到短信时会提示";
text.setText(s);
text.setTextSize(30);
button.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Toast.makeText(MainActivity.this, "显示短信内容", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
新建一个类,扩展至BroadcastReceiver类,用于处理收到短信之后的事情
package com.example.toast_04;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView text =null;
private Button button =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
button= (Button)findViewById(R.id.button);
String s = "收到短信时会提示";
text.setText(s);
text.setTextSize(30);
button.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Toast.makeText(MainActivity.this, "显示短信内容", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
因为涉及到了读取短信的权限,所以需要在Androidmanifest文件中做如下配置:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
并且需要在Androidmanifest内注册广播接收器:
<receiver android:name="com.example.toast_04.SmsReceive">
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>