本文通过将app设置为launcher的方式,来实现屏蔽home键的效果.
底层修改什么的那些个东西,我也不懂,所以,直接上我写的代码吧.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ilike.key"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" //这里将launchMode设置为singleTask来防止点击home键时,不停的创建MainActivity android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.MAIN" /> //这里添加home和default来将app设置为launcher <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> //声明一个广播,监听home键的action <receiver android:name=".HOME_RECEIVER" /> </application> </manifest>
public class HOME_RECEIVER extends BroadcastReceiver { //这里是固定key String SYSTEM_REASON = "reason"; String SYSTEM_HOME_KEY = "homekey"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_REASON); if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) { //表示按了home键,程序到了后台 // context.startActivity(new Intent(context, MainActivity.class)); //此处使用了PendingIntent来实现,防止直接用Intent的时候,会有延迟或者闪的情况 startSelfFromPendingIntent(context); } } } private void startSelfFromPendingIntent(Context context) { Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //这里需要注意 intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setComponent(new ComponentName(context, MainActivity.class)); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); try { pendingIntent.send(); } catch (Exception e) { Log.e("广播", "stayTop fail"); } }
这里没什么可说的,注册与注销
public class MainActivity extends AppCompatActivity { private HOME_RECEIVER receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver=new HOME_RECEIVER(); registerReceiver(receiver,new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); Log.e("MainActivity","onCreate"); } @Override protected void onDestroy() { super.onDestroy(); if (receiver!=null){ unregisterReceiver(receiver); } Log.e("MainActivity","onDestroy"); } @Override protected void onResume() { super.onResume(); Log.e("MainActivity","onResume"); } }
最后,最后,app启动后,点击home键,将当前app设置为启动桌面,然后就完事了,如果觉得这种方法不行,那么你自己去改底层吧,反正我是不知道其他的办法了.