插卡开机后弹出消费提示语,用PopupWindow实现

项目需求:

1.插卡开机后,要求弹出上图的消费提示语(Algunas aplicaciones requieren conexión a datos pudiendo aplicar algún costo. Te sugerimos contratar un paquete de internet. Detalles con tu operador de Servicio.),

2.若没有按Aceptar,则该提示框不会消失
3.若勾选了上图中的No mostrar este mensaje de nuevo,然后按Aceptar,此消费提示对话框将不再弹出,除非恢复出厂设置或刷机

4.数据消费提示语中,仅当点击这几个字paquete de internet 就调起浏览器打开链接 www.internetclaro.com.pe。 点击这几个以外的字则不要调起这个链接


关于PopupWindow:

   在OnCreate()中使用showAtLocation()的时候,我们一般是写在监听事件中。但是如果写在监听事件外时,会报错。

这是因为activity没有初始化结束,这时候就执行showAtLocation()显示PopupWindow框,这当然会报错。这时候我们就需要确定activity初始化结束后再调用,可以用Handler和Runnable监测。可以看MainActivity中的代码。

还有一点要注意的是在activity_main中必须要有

    android:minWidth="1dp"
    android:minHeight="1dp"
否则会进入死循环,弹不出PopupWindow框。

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test_popupwindow"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />
    <!-- 获取权限 -->
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent" >
 <activity
            android:name="com.example.test_popupwindow.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<receiver android:name="com.example.test_popupwindow.SIMReceiver">
           <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED"/>
           </intent-filter>
       </receiver>
    </application>

</manifest>


用于填充PopupWindow的自定义布局item.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#333333"
    android:orientation="vertical" >
 <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="3dp" />
 <CheckBox
        android:id="@+id/box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="3dp"
        android:text="No velver a mostrar" />

    <Button
        android:id="@+id/but"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Aceptar" />

</LinearLayout>

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="1dp"
    android:minHeight="1dp"
    android:id="@+id/main"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 <!-- 特别要注意的是其中的  android:minHeight="1dp" 和android:minWidth="1dp"属性。要是没有这个属性,
      监测activity初始化的代码会进入死循环,PopupWindow也显示不出来。 -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>


MainActivity.java:


public class MainActivity extends Activity {

	private Handler handler;
	private View main;
	private CheckBox box;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		handler = new Handler();   
		
		final LayoutInflater inflater = LayoutInflater.from(this);
		main = inflater.inflate(R.layout.activity_main, null);
                //创建PopupWindow对象
		final PopupWindow pop = new PopupWindow(main,
		LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
                //设置除PopupWindow窗口外不可点击
		pop.setOutsideTouchable(false);
		//设置PopupWindow大小
		pop.setHeight(300);
		pop.setWidth(400);
		//设置PopupWindow可获得焦点(如果不写或者设为false则窗口的各种Button或者Editor将不可点击或输入)
		pop.setFocusable(true);
                //PopupWindow窗口的自定义布局。
		View v = inflater.inflate(R.layout.item, null);
		pop.setContentView(v);

		TextView text = (TextView) v.findViewById(R.id.text);
		Button but = (Button) v.findViewById(R.id.but);
		box = (CheckBox) v.findViewById(R.id.box);
                SpannableString sp = new SpannableString(
				"Algunas aplicaciones requieren conexión "
						+ "a datos pudiendo aplicar algún costo. Te sugerimos contratar un paquete de internet."
						+ " Detalles con tu operador de Servicio.");
		// 设置超链接
		sp.setSpan(new URLSpan("http://www.internetclaro.com.pe"), 104, 124,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //设置字体颜色
		sp.setSpan(new ForegroundColorSpan(Color.WHITE), 0, 104,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		sp.setSpan(new ForegroundColorSpan(Color.WHITE), 125, 162,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		
		text.setMovementMethod(LinkMovementMethod.getInstance());
		text.setTextSize(15);
		text.setText(sp);
                but.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (box.isChecked()) {
					//如果选择了复选框,则改变SharedPreferences的SIM卡状态信息。
					SharedPreferences sp = getApplicationContext()
							.getSharedPreferences("SIMState", 0);
					Editor editor = sp.edit();
					editor.putBoolean("isSelect", true);
					editor.commit();
                }
				Toast.makeText(getApplicationContext(),
						"@@@@@" + box.isChecked(), Toast.LENGTH_SHORT).show();
			}
		});
                /*****************以下代码用来循环检测activity是否初始化完毕***************/
		Runnable run = new Runnable() {

			@Override
			public void run() {

				// 得到activity中的根元素,不能用inflater.inflate(R.layout.item, null);
				main = findViewById(R.id.main);
				Log.v("TAG", main.getWidth() + " @@  " + main.getHeight());
                                // 如果根元素的width和height大于0说明activity已经初始化完毕
				if (main != null && main.getHeight() > 0 && main.getWidth() > 0) {
					//显示popupwindow
					pop.showAtLocation(main, Gravity.CENTER, 0, 0);
					//停止检测
					handler.removeCallbacks(this);
				} else {
					//如果activity没有初始化完毕则等待5毫秒再次检测
					handler.postDelayed(this, 5);
				}
			}
		};
                 //开始检测 
		handler.post(run);
		 /******************以上代码用来循环检测activity是否初始化完毕*************/
	}

}

SIMReceiver.java:


public class SIMReceiver extends BroadcastReceiver{

	private TelephonyManager tm;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		
		tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		String action = intent.getAction();
		
		Log.v("TAG", "SIMService--------------------"+action);
               //检测开机事件
		if(action.equals("android.intent.action.BOOT_COMPLETED")){
			//检测SIM卡状态,若是返回5则表明SIM卡存在
			if(tm.getSimState() == 5){
				//用SharedPreferences保持SIM信息,主要是序列号SimSerialNumber和复选框的选择状态
				SharedPreferences sp = context.getSharedPreferences("SIMState", 0);
				Editor editor = sp.edit();
				String str = sp.getString("SimSerialNumber", "");
				boolean isSelect = sp.getBoolean("isSelect", false);
                                if(str.equals(tm.getSimSerialNumber())){
					//若是SIM没变,且没有选中复选框,则重新跳到Activity
					if(!isSelect){
						Intent intent1 = new Intent(context,MainActivity.class);
						//必须要设置addFlags(),否则报错。
					    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					    context.startActivity(intent1);	
					}
				}else{
                                        //若是SIM改变或者第一次开机(刷机,恢复出厂设置),跳到Activity
					Intent intent1 = new Intent(context,MainActivity.class);
				        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				        context.startActivity(intent1);		
					//保存SIM状态
					editor.putString("SimSerialNumber", tm.getSimSerialNumber());
					editor.putBoolean("isSelect", false);
					editor.commit();
				}

			}

		    Log.v("TAG", "SIMReceiver");
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值