[英]Check if application is running (either background or foreground) Android
I have created a BroadCastReceiver for SMS and I want it to work only when the application is running (either in forgeground or background) . 我已经为SMS创建了BroadCastReceiver,我希望它仅在应用程序运行时(在Forgeground或后台)运行。 The current code im using is :
我正在使用的当前代码是:
public class BroadCastReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
ActivityManager am = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
String packageName = am.getRunningTasks(1).get(0).topActivity
.getPackageName();
if(packageName.contains("com.example.sms") )
{
abortBroadcast();
}else
{
}
}
}
But the problem is this code only works in foreground , so when the user hits back button or home button the application will work in background but the BroadCastReceiver will not work . 但是问题在于此代码仅在前台运行,因此当用户单击后退按钮或主页按钮时,该应用程序将在后台运行,但BroadCastReceiver将无法运行。 So is there's any method to solve this issue ??
那么有什么方法可以解决这个问题? &Thanks in advance
&提前致谢
If you only want to run a broadcast when your app is running, then you only have to register the broadcast when the app is running. 如果您只想在应用程序运行时运行广播,则只需在应用程序运行时注册广播。
public class BroadCastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
/** SMS received while app was running. Do whatever */
}
}
public class MainActivity extends Activity {
private BroadCastReceiver mBroadcastReceiver = new BroadCastReceiver();
@Override
public void onStart() {
super.onStart();
registerReceiver(myBroadcastReciever, new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION);
}
@Override
public void onStop() {
super.onStop();
unregisterReceiver(myBroadcastReceiver);
}
}
The broadcast receiver will only receive broadcasts when your app is running. 广播接收器仅在您的应用程序运行时才接收广播。 No need to check running processes.
无需检查正在运行的进程。 You can move them to onResume()/onPause() if you only want to receive broadcasts when the app is visible to users.
如果只希望在用户可见该应用程序时接收广播,则可以将它们移至onResume()/ onPause()。 You can (un)register in onCreate()/onDestroy() if you want to start receiving broadcasts as soon as possible.
如果您想尽快开始接收广播,则可以在onCreate()/ onDestroy()中进行(取消)注册。 You can do the same thing in a Service with its respective callbacks.
您可以在服务及其相应的回调中执行相同的操作。
You can run ps and check output for your package name 您可以运行ps并检查输出的软件包名称
try {
Process process = Runtime.getRuntime().exec("ps | grep \""+myPackageName+"\"");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int bytes;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((bytes = reader.read(buffer)) > 0) {
output.append(buffer, 0, bytes);
}
reader.close();
process.waitFor();
return output.toString().length()>1;
} catch (Exception e) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.