Android获取手机短信
- import android.content.pm.PackageManager;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.content.ContextCompat;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
-
- import android.app.Activity;
- import android.database.ContentObserver;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.widget.TextView;
-
- public class MainActivity extends AppCompatActivity {
-
- private TextView vSms;
- private SMSContent smsObsever;
-
- private Handler handler = new Handler() {
- public void handleMessage(android.os.Message msg) {
- Bundle bundle = msg.getData();
- String body = bundle.getString("body");
- vSms.setText(body);
- }
-
- ;
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- vSms = (TextView) this.findViewById(R.id.tx_sms);
- smsObsever = new SMSContent(handler);
-
- getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObsever);
- }
-
-
-
-
-
- class SMSContent extends ContentObserver {
- private Handler mHandler;
-
- public SMSContent(Handler handler) {
- super(handler);
- mHandler = handler;
- }
-
- @Override
- public void onChange(boolean selfChange) {
- super.onChange(selfChange);
- Cursor cursor = null;
- String body = null;
-
-
- final int REQUEST_CODE_ASK_PERMISSIONS = 123;
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);
-
-
- if (ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
- try {
- cursor = getContentResolver().query(
- Uri.parse("content://sms/inbox"), null, null, null,
- "date desc");
- if (cursor != null) {
- if (cursor.moveToNext()) {
-
- body = cursor.getString(cursor.getColumnIndex("body"));
- Message msg = Message.obtain();
- Bundle bundle = new Bundle();
- bundle.putString("body", body);
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- }
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (cursor != null) {
- cursor.close();
- }
-
- }
- }
- }
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
-
- getContentResolver().unregisterContentObserver(smsObsever);
- }
- }
-
- <uses-permission android:name="android.permission.RECEIVE_SMS"/>
-
- <uses-permission android:name="android.permission.READ_SMS"/>
没有评论:
发表评论