Android学习(14)-手机通知,手机短信

本文介绍如何在Android应用中创建和显示通知,并演示了如何发送和接收短信,包括短信监听和状态反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先谈一下通知的用法,所谓通知,就是你平时看到手机上方状态栏多了一个小图,可以用手下拉查看通知。在Android中,通知可以通过广播,服务或者活动来创建。但是一般都是程序运行于后台的时候才会给出通知。

我们想做这么一个小东西:



那么如何去做呢?

首先,布局要弄好,一个是发送通知布局,一个是点击后跳转到的布局。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
   

    <Button
        android:id="@+id/SendNotice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送通知" />

</RelativeLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/notification_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="呜哈哈,点击通知之后到了我这~" />

</LinearLayout>
有了布局,那么我们需要两个活动:

public class MainActivity extends Activity implements OnClickListener{

	private Button sendNotification;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sendNotification = (Button)findViewById(R.id.SendNotice);
		sendNotification.setOnClickListener(this);
		//此处该类通过接口的方式为按钮设置响应事件,所以此处如此设置
	}

	@Override
	public void onClick(View view) {
		switch(view.getId()){
		case R.id.SendNotice:
			NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
			//获取通知管理   和之前的网络信息管理一个道理  只要调用系统接口就可以
			Notification notification = new Notification(R.drawable.ic_launcher, "Hello Notification!", System.currentTimeMillis());
			//参数: 通知图标  通知一闪而过的时候出现的文字  通知出现的时间
			Intent intent = new Intent(this,NotificationResult.class);
			PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			notification.setLatestEventInfo(this, "Notification Title", "Notification Content", pi);
			//以上三个语句用于点击通知后调用的事件,即点击通知之后跳转到另外一个界面
			manager.notify(1, notification);
			//发送通知: 编号  通知内容
			break;
		default:
			break;
		}
		
	}
}

以及点击后的活动:

public class NotificationResult extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notification_result);
		
		//点击后取消通知,取消是根据ID来搞的
		NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		manager.cancel(1);
	}
}

别忘了在文件中注册上所有的活动。

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.notificationtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity android:name=".NotificationResult"></activity>
    </application>
还有其他设置,通知时候的声音,手机震动等。


通知的搞定了,下面讲一下短信的发送和接收方法。

我们希望实现下面一个小例子,能够接受短信,而且能够发送短信并监听发送状态:


首先,创建布局layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="来自:" />

        <TextView
            android:id="@+id/sender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
             />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
        	android:padding="10dp"
            android:text="短信内容:" />

        <TextView
            android:id="@+id/content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
             />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="发送给:" />

       <EditText
           android:id="@+id/to"
            android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_gravity="center_vertical" />

       <EditText
           android:id="@+id/msg_input"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_gravity="center_vertical" />

   <Button
       android:id="@+id/send"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="发送" />
    
</LinearLayout>

而后,我们编写活动类,很多说明都在注释中。道理很简单,通过动态注册广播来收听短信和短线发送状态。

public class MainActivity extends Activity {
	
	private TextView sender; //发送方
	private TextView content; //短信内容
	private EditText to;//接收方
	private EditText msgInput;//发送内容
	private Button send; //发送按钮
	
	//用于动态注册短信广播接收器
	private IntentFilter receiveFilter;
	private MessageReceiver messageReceiver;
	
	//监听发送短信是否成功
	private IntentFilter sendFilter;
	private SendStatusReceiver sendStatusReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//接收短信相关
		sender = (TextView)findViewById(R.id.sender);
		content = (TextView)findViewById(R.id.content);
		receiveFilter = new IntentFilter();
		receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
		//receiveFilter.setPriority(100);//用于拦截短信  广播中有的是可以拦截的
		messageReceiver = new MessageReceiver();
		registerReceiver(messageReceiver, receiveFilter);
		
		
		//增加短信发送成功监听广播
		sendFilter = new IntentFilter();
		sendFilter.addAction("SENT_SMS_ACTION");
		sendStatusReceiver = new SendStatusReceiver();
		registerReceiver(sendStatusReceiver, sendFilter);
		
		//发送短信相关
		to = (EditText)findViewById(R.id.to);
		msgInput = (EditText)findViewById(R.id.msg_input);
		send = (Button)findViewById(R.id.send);
		send.setOnClickListener(new OnClickListener() {		
			@Override
			public void onClick(View v) {
				SmsManager smsManager = SmsManager.getDefault();
				//发送后增加后续活动  此处就是为了监听短信是否成功
				Intent sentIntent = new Intent("SENT_SMS_ACTION");
				PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, sentIntent, 0);
				//通知那也用到过这个  用于事件处理后  紧接着调用的活动
				
				smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null);
				//发送短信  注意参数
				
			}
		});		
	}
	
	public void onDestroy(){
		super.onDestroy();
		//取消短信广播注册
		unregisterReceiver(messageReceiver);
		unregisterReceiver(sendStatusReceiver);
	}

	//短信广播接收器
	class MessageReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			Object[] pdus = (Object[])bundle.get("pdus");//提取短信消息
			SmsMessage[] messages = new SmsMessage[pdus.length]; //通过SmsMessage来存储短信
			for(int i = 0; i < messages.length; i++){
				messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
			}
			String address = messages[0].getOriginatingAddress();//获取发送方号码
			String fullMessage = "";
			for(SmsMessage message : messages){
				fullMessage += message.getMessageBody();//获取短信内容
			}
			
			//设置界面上的呈现内容
			sender.setText(address);
			content.setText(fullMessage);
			
			//abortBroadcast();//拦截短信
		}	
	}
	//发送短信状态接收器
	class SendStatusReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			if(getResultCode() == RESULT_OK){
				Toast.makeText(context, "发送短信成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(context, "发送短信失败", Toast.LENGTH_SHORT).show();
			}			
		}		
	}

}

接收短信和发送短信都需要有权限生命,在配置文件中加上下面两句:

 <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>

Ok!  可以成功了





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值