1). 寫一個主程式,Broadcast需要去啟動的程式。BroadcastTest1
2). 繼承Broadcast類別,並設定intent連到主程式。StartUpReceiver
3). 在Androidmanifest.xml設置<receive>的標籤
4). 在Androidmanifest.xml添加權限
//=============================================================
[BroadcastTest1]
package com.broadcasttest1;
import android.app.Activity;
import android.os.Bundle;
public class BroadcastTest1 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
//-------------------------------------------------------------------------------------------------------------
[StartUpReceiver]
package com.broadcasttest1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
Intent intent = new Intent(arg0, BroadcastTest1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(intent);
}
}
//-------------------------------------------------------------------------------------------------------------
[AndroidManifest.xml]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcasttest1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<!-- Activity -->
<activity
android:name=".BroadcastTest1"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Receiver -->
<receiver android:name=".StartUpReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
沒有留言:
張貼留言