参考:《第一行代码》 效果 
点击按钮后会发个广播
public class MainActivity extends BaseActivity { Button forceOffline; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); forceOffline=(Button) findViewById(R.id.force_offline); myListener(); } private void myListener() { forceOffline.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent("com.example.Controller.FORCE_OFFLINE"); sendBroadcast(intent); } }); }}接收到MainActivity 发来的广播后,创建对话框,实现强制下线功能
public class ForOfflineReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { // 创建一个对话框,用于提醒用户强制下线,然后确定退出到登录界面 /* * 不能直接通过AlertDialog的构造函数来生产一个AlertDialog。 * 研究AlertDialog的源码发现AlertDialog所有的构造方法都是写保护的 */ AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(context); alertDialogBuilder.setTitle("Warning"); alertDialogBuilder.setMessage("You are forced to offline"); alertDialogBuilder.setCancelable(false);//设置不能返回 alertDialogBuilder.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //销毁所有活动 ActivityController.finishAll(); Intent intent=new Intent(context,LoginActivity.class); //根据配置的Affinity决定创建的活动在哪个栈 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //因为本身不是Activity,使用上下文来启动另一个活动 context.startActivity(intent); } }); AlertDialog alertDialog=alertDialogBuilder.create(); //需要设置AlertDialog的类型,保护在广播接收器中可以正常弹出, 系统提示。它总是出现在应用程序窗口之上 alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); alertDialog.show(); }}加上
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />否则对话框无法在广播接收器弹出 还有广播接收器是静态注册,所以不需程序启动即可接收,完整配置
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.Controller" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- allowBackup="true"表示允许备份的意思,涉及设置存在敏感信息泄露 --> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/APPTheme" > <activity android:name=".LoginActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity" /> <receiver android:name=".ForOfflineReceiver" > <intent-filter> <action android:name="com.example.Controller.FORCE_OFFLINE" /> </intent-filter> </receiver> </application></manifest>新闻热点
疑难解答