[英]How to detect SMS only when application is running in android?
我正在開發一個android應用程序。 在我的應用程序中,我需要檢測傳入的SMS。 我已經嘗試了一個帶有廣播接收器的示例示例。 但是廣播接收器的問題在於,即使您的應用程序未運行,它也會檢測到短信。 我的要求是在應用程序運行時檢測短信。
提前致謝。
沒有簡單的方法來跟蹤您的應用是否對用戶可見。 當它們進入onResume()和onPause()時,您必須自己簡單地對屏幕進行計數來跟蹤它。 當應用程序擊中任何活動的onResume()時,增加一個計數器,當擊中onPause()時減小。 您可以簡單地創建一個基本活動並將其計數系統放入其中,並從您在應用程序中創建的每個活動擴展它。
查看Android活動生命周期。
http://developer.android.com/reference/android/app/Activity.html
嘗試這個 !!
您的廣播接收者必須指定android:exported =“ false”才能不接收在您自己的應用程序外部創建的廣播。
清單中定義了Sample
廣播接收器,如下所示:
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
您的問題有2種解決方案:( 請參閱參考資料 )
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Do your sms receive logic here
}
}
並在您的活動中注冊此接收器,如下所示:
// Global
BroadcastReceiver smsReceiver = new MyReceiver();
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(smsReceiver , new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
unregisterReceiver(smsReceiver);
super.onPause();
}
如果要實現此方法,則必須做更多的工作:
a)在清單中添加“ android.permission.GET_TASKS”權限
b) 在執行任何操作之前 ,請在廣播接收器的onReceive()方法中調用此方法
public boolean checkRunningApps() {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTasks = mActivityManager
.getRunningTasks(Integer.MAX_VALUE);
int pos = -1;
// Checking that your app is in running task list or not
for (int i = 0; i < runningTasks.size(); i++) {
if ((runningTasks.get(i).topActivity.getPackageName()
.contains(AppSettings.REQUIRED_PACKAGENAME))) {
isAppRunning = true;
pos = i;
break;
}
}
if (pos == -1) {
// App is not running, do nothing
return false;
}
if (pos >= 0) {
// App is running, do your logic here
// If you want to check that app is on top, check for only 0 position of runningTasks arrayList
return true;
}
return false;
}
如果此方法返回true,則執行您的邏輯 ,否則不執行任何操作 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.