在启动android上运行代码

时间:2016-08-02 14:51:34

标签: java android service toast boot

我遇到了在启动时运行代码的问题,我已经下载了一个应该可行的示例的源代码,但事实并非如此。根据这个例子,它应该在手机打开时产生一个干杯,但它不会发生,我已经在Android 6.0和7.0上测试过。
任何帮助表示感谢。 代码如下:
清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidautostartup"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver
            android:name=".BootComplete"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service android:name=".AutoStartUp" >
        </service>

        <activity
            android:name="com.example.androidautostartup.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

BootComplete.java

public class BootComplete extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AutoStartUp.class);
            context.startService(serviceIntent);
        }
    }
}

AutoStartUp.java

public class AutoStartUp extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        // do something when the service is created
    }

}

1 个答案:

答案 0 :(得分:0)

我真的不建议在工作线程(服务)上做UI内容。虽然可以这样做,但它会让用户产生混淆,以便在应用程序上下文之外接收消息。

话虽如此,如果你需要这样做,你应该在UI线程上运行UI代码。

Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(getContext(), "Service Started", Toast.LENGTH_LONG).show();
        }
    });