Android實現安裝後自啓動

實現apk安裝後自啓動的前提是:

1、觸發“android.intent.action.PACKAGE_REPLACED”廣播,apk覆蓋安裝後會接收到該廣播,初次安裝不會觸發,因爲app還未運行過。

2、上述“android.intent.action.PACKAGE_REPLACED”廣播使用靜態註冊,(動態註冊廣播在運行後纔可以接收到)。

3、app已運行過,非首次安裝(即不處於stopped狀態)。

不會觸發覆蓋安裝廣播的情況:

1、首次安裝apk,不會觸發廣播

2、覆蓋安裝未運行過的app,不會觸發廣播

3、在系統設置中,將app【強行停止】,不會觸發廣播

實現apk安裝後自啓動相關代碼

1、自定義廣播接收器-監聽apk覆蓋安裝的廣播

/**
 * Created by cwang on 2019/1/10.
 */
public class AppStartReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //取得AppStartReceiver所在的App的包名
        String localPkgName = context.getPackageName();
        Uri data = intent.getData();
        //取得安裝的Apk的包名,只在該app覆蓋安裝後自啓動
        String installedPkgName = data.getSchemeSpecificPart();
        if((action.equals(Intent.ACTION_PACKAGE_ADDED)
                || action.equals(Intent.ACTION_PACKAGE_REPLACED)) && installedPkgName.equals(localPkgName)){
            //app啓動的Activity
            Intent launchIntent = new Intent(context,MainActivity.class);
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(launchIntent);
        }

    }
}

2、在AndroidManifest.xml配置文件中靜態註冊上述廣播接收器

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.interjoy.myapplication">

    <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">
        <!--app啓動的第一個Activity-->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--靜態註冊廣播接收器-->
        <receiver android:name=".AppStartReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />

                <data android:scheme="package" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章