Android 使用廣播系統解決app開機自啓動問題

源碼Demo獲取方法

關注 【網羅開發】微信公衆號,回覆【160】即可領取。 網羅天下方法,方便你我開發,更多iOS技術乾貨等待領取,全部文檔會持續更新,歡迎關注一塊兒成長! 總結一下使用ACTION_BOOT_COMPLETED的廣播,解決app開機自啓動的問題 1.首先在你的工程上建一個廣播接受的類,繼承BroadcastReceiver:android

package guide.example.com.guidedemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Created by fby on 2017/6/26.
 */

public class BootReceiver extends BroadcastReceiver {
    static final String action_boot ="android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive (Context context, Intent intent) {

        Log.i("charge start", "啓動完成");

        if (intent.getAction().equals(action_boot)){

            Intent mBootIntent = new Intent(context, MainActivity.class);
            // 下面這句話必須加上才能開機自動運行app的界面
            mBootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mBootIntent);
        }
    }
}
複製代碼

2.而後要在AndroidManifest.xml中加入權限和配置相關信息:bash

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  

複製代碼

3.在application標籤中,配置如下相關信息:微信

//BootReceiver是上面建的廣播類
        <receiver android:name=".BootReceiver">  
            <intent-filter>  
                <!--註冊開機廣播地址-->  
                <action android:name="android.intent.action.BOOT_COMPLETED">            
                </action>  

                <category android:name="android.intent.category.DEFAULT" />  
            </intent-filter>  
        </receiver>  
複製代碼

補充說明: 1.查看系統中是否安裝了相似360管家的軟件,爲了加快開機速度,默認是關閉掉開機廣播的,只須要在設置中打開便可。 2.若是監聽不到廣播,能夠嘗試同時監聽廣播和sd卡。 3.同時監聽廣播和sd卡,在application標籤中,配置如下相關信息:app

<receiver android:name=".broadcastReceiver.BootCompletedReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.HOME" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />

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

        </receiver>
複製代碼

但願能夠幫助你們 若是哪裏有什麼不對或者不足的地方,還望讀者多多提意見或建議ide

相關文章
相關標籤/搜索