一、创建Service前台服务
package com.iwhalecloud.demo.SMS;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.RequiresApi;
import com.iwhalecloud.demo.MainActivity;
import com.iwhalecloud.demo.R;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
private int count;
private SMSContentObserver smsObserver;
protected static final int MSG_INBOX = 1;
public String phoneNo = "10659874";
public String httpUrl = "http://10.0.2.2:8888/api/test/t1";
private final Handler smsHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_INBOX:
setSmsCode();
break;
}
}
};
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder {
public MyService getService(){
return MyService.this;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onCreate() {
super.onCreate();
startForeground(100,getNotification("服务运行中...","正在监听号码:"+phoneNo+",保持应用后台运行..."));
smsObserver = new SMSContentObserver(MyService.this,smsHandler);
getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
phoneNo=intent.getStringExtra("phoneNum");
httpUrl=intent.getStringExtra("httpUrl");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private Notification getNotification(String title, String message){
count++;
Intent clickIntent = new Intent(this, MainActivity.class);
clickIntent.putExtra("flag",count);
Notification.Builder builder = new Notification.Builder(this);
NotificationChannel notificationChannel = null;
String CHANNEL_ONE_ID = "com.iwhalecloud.com";
String CHANNEL_ONE_NAME = "Channel One";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
PendingIntent contentIntent = PendingIntent.getActivity(this,count,clickIntent
,PendingIntent.FLAG_UPDATE_CURRENT);
builder = new Notification.Builder(this)
.setChannelId(CHANNEL_ONE_ID)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("服务开启")
.setWhen(System.currentTimeMillis())
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
Notification notify = builder.build();
return notify;
}
return null;
}
@SuppressLint("Range")
private void setSmsCode() {
Cursor cursor = null;
try {
cursor = getContentResolver().query(
Uri.parse("content://sms"),
new String[] { "_id", "address", "body", "date" },
null, null, "_id asc");
Log.i(TAG, "setSmsCode: You");
Log.i(TAG, String.valueOf(cursor != null));
if (cursor != null) {
cursor.moveToLast();
final long smsdate = Long.parseLong(cursor.getString(cursor.getColumnIndex("date")));
final long nowdate = System.currentTimeMillis();
Log.i(TAG, "setSmsCode: smsdate ==="+smsdate);
Log.i(TAG, "setSmsCode: nowdate ==="+nowdate);
if (nowdate - smsdate > 60 * 1000) {
Log.i(TAG, "短信过期");
return;
}
final String strAddress = cursor.getString(cursor.getColumnIndex("address"));
final String strbody = cursor.getString(cursor.getColumnIndex("body"));
final int smsid = cursor.getInt(cursor.getColumnIndex("_id"));
if (TextUtils.isEmpty(strAddress) || TextUtils.isEmpty(strbody)) {
return;
}
Log.i(TAG, "setSmsCode: "+phoneNo);
Log.i(TAG, "setSmsCode: "+httpUrl);
if (strAddress.equals(phoneNo)){
Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{6})(?![0-9])");
Matcher m = continuousNumberPattern.matcher(strbody);
String dynamicPassword = "";
while (m.find()) {
dynamicPassword = m.group();
}
String finalDynamicPassword = dynamicPassword;
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient mOkHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder().add("code", finalDynamicPassword).build();
Request request = new Request.Builder().url(httpUrl).post(requestBody).build();
try {
Response response = mOkHttpClient.newCall(request).execute();
String result = response.body().string();
Log.d(TAG, "result: " + result);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Log.i(TAG, "onReceiveSms: "+ dynamicPassword);
}
}
}catch (Exception e) {
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
public class SMSContentObserver extends ContentObserver {
private static final int MSG_INBOX = 1;
private int flag = 1;
private Context mContext;
private Handler mHandler;
public SMSContentObserver(Context mContext,
Handler mHandler) {
super(mHandler);
this.mContext = mContext;
this.mHandler = mHandler;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
if (flag%3 == 2){
mHandler.obtainMessage(MSG_INBOX, "监听到短信").sendToTarget();
}
flag++;
}
}
}
二、主界面(参考)
package com.iwhalecloud.demo;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.iwhalecloud.demo.SMS.MyService;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "CC";
final private int REQUEST_CODE_ASK_PERMISSIONS = 1;
private boolean serviceFlag = false;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences read = getSharedPreferences("info", MODE_PRIVATE);
String phoneNum = "10659874";
String httpUrl= "";
if (read.getString("phoneNum",null)!=null){
phoneNum = read.getString("phoneNum",null);
}
if (read.getString("httpUrl",null)!=null){
httpUrl = read.getString("httpUrl",null);
}
TextView v1 = findViewById(R.id.editText1);
TextView v2 = findViewById(R.id.editText2);
v1.setText(phoneNum);
v2.setText(httpUrl);
}
public void openService(View v){
TextView pn = findViewById(R.id.editText1);
TextView httpUrl = findViewById(R.id.editText2);
Button button = findViewById(R.id.button);
if (!serviceFlag){
Intent service = new Intent(getApplicationContext(), MyService.class);
SharedPreferences.Editor editor = getSharedPreferences("info",MODE_PRIVATE).edit();
editor.putString("phoneNum",pn.getText().toString());
editor.putString("httpUrl",httpUrl.getText().toString());
editor.apply();
service.putExtra("phoneNum",pn.getText().toString());
service.putExtra("httpUrl",httpUrl.getText().toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int hasReadSmsPermission = checkSelfPermission(Manifest.permission.READ_SMS);
if (hasReadSmsPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_SMS}, REQUEST_CODE_ASK_PERMISSIONS);
return;
}
}
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.startService(service);
}
pn.setEnabled(false);
httpUrl.setEnabled(false);
serviceFlag = !serviceFlag;
button.setText("停止服务");
}else {
Intent service = new Intent(getApplicationContext(), MyService.class);
this.stopService(service);
pn.setEnabled(true);
httpUrl.setEnabled(true);
button.setText("启动服务");
serviceFlag = !serviceFlag;
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
Intent service = new Intent(getApplicationContext(), MyService.class);
this.stopService(service);
}
}
三、清单文件
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
....
....>
<service
android:name=".SMS.MyService"
android:enabled="true"
android:exported="false" />
</application>
|