在设备启动时启动应用程序效果不佳

时间:2017-09-03 09:41:17

标签: android

我已经使用BroadcastReceiver在设备启动完成后立即自动启动应用程序。但它没有用。在使用cmd(adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -p com.capitaleyejobschedulers.com.jobschedulers)进行测试时,仅当应用程序位于前台时才会显示日志。如果它被最小化或从应用程序列表中滑出(即应用程序未运行),则它无法正常工作。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
    mReceiver = new BootCompletedIntentReceiver();
    registerReceiver(mReceiver, filter);
}

public class BootCompletedIntentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Log.e("bootDeviceValue", " zzz");
        }
    }
}
@Override
public void onDestroy() {
    try{
        if(mReceiver!=null)
            unregisterReceiver(mReceiver);
    }catch(Exception e){
    }
    super.onDestroy();
}

更新1:

MainActivity

public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.e("bootDeviceValue", " aaaaa");
    }
}

YourActivityRunOnStartup类

public class YourActivityRunOnStartup extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Log.e("bootDeviceValue", " bbbbb");
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }
}

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zzzz.com.autorunonboot">

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

    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:enabled="true"
            android:exported="true"
            android:name=".YourActivityRunOnStartup"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

0 个答案:

没有答案