AlertDialog
中显示onStop()
,就像这样:
protected void onStop() {
builder.setMessage("Test message")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
super.onStop();
Log.e(" onStop","");
}
但这可能无法正常工作。之后,我试图通过服务显示此对话框。各种方式都不适合我。请帮助我有这种能力
截图:
答案 0 :(得分:1)
您需要检测您的应用当前是在后台还是前台。
BroadcastReceiver
以收听传入消息实现更改应用程序状态的自定义Application类
public class MyApplication extends Application {
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
}
将onPause
和onResume
添加到项目中的每个活动以更改应用程序状态:
@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}
添加权限并在清单中注册接收者:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
SMSBroadcastReceiver:
public class SMSBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "no message received";
if(bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length;i++){
msgs[i]= SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from Phone No: " +msgs[i].getOriginatingAddress();
str +="\n"+"Message is: ";
str += msgs[i].getMessageBody().toString();
str +="\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); //contact number and the message
// Now as soon as you get the message check whether your application is running or not and show the dialog
if(!MyAppliction.isActivityVisible())
{
// code to show a dialog box
}
}
}}