在收到Broadcast後,直接啟動一個Activity,首先在AndroidManifest.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testbroakcastreceiver" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".Main">
<intent-filter>
<action android:name="com.gill.test.broadcast" />
</intent-filter>
</receiver>
<activity android:name=".Main2" >
</activity>
</application>
</manifest>
接下來需要2個java檔,Main.java繼承BroadcastReceiver,負責接收Broadcast,程式如下:
public class Main extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Gill", "This is a test");
Intent i = new Intent();
i.setClass(context, Main2.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
}
Main2.java是一個單純的Activity,程式如下:
public class Main2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
測試方式,請先將手機和PC連接好後,在命令列模式下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testbroakcastreceiver" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".Main">
<intent-filter>
<action android:name="com.gill.test.broadcast" />
</intent-filter>
</receiver>
<activity android:name=".Main2" >
</activity>
</application>
</manifest>
接下來需要2個java檔,Main.java繼承BroadcastReceiver,負責接收Broadcast,程式如下:
public class Main extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Gill", "This is a test");
Intent i = new Intent();
i.setClass(context, Main2.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
}
Main2.java是一個單純的Activity,程式如下:
public class Main2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
測試方式,請先將手機和PC連接好後,在命令列模式下
adb shell am broadcast -a com.gill.test.broadcast
就可以看到手機執行Main2的畫面了。
沒有留言:
張貼留言