Android (BroadcastReceiver与程序的开机自启动)
一般Context也可以通过braodcast方式来广播Intent.
最简单的显示使用:
先声明一个BroadcastReceiver 的子类:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class TestBroadReceier extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "You have Receiver Broadcast", Toast.LENGTH_LONG).show();
}
}
在项目的AndroidManifest.xml中声明此Reciever:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.Test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestReceiver"
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 android:name="TestBroadReceier" android:label="@string/hello"></receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
编写调用者:
package test.Test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class TestReceiver extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
menu.add(1, Menu.FIRST +1, 1, "Broadcast");
menu.add(1, Menu.FIRST +2, 2, "Test");
menu.add(1, Menu.FIRST +3, 3, "Test1");
menu.add(1, Menu.FIRST +4, 4, "Close");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId())
{
case Menu.FIRST+ 1:
{
Intent i = new Intent(this, TestBroadReceier.class);
this.sendBroadcast(i);
this.setTitle("Broadcast");
break;
}
case Menu.FIRST + 2:
{
this.setTitle("Del Item...");
break;
}
case Menu.FIRST + 3:
{
this.setTitle("Exit Item...");
break;
}
}
return true;
}
}
这是最简单的用法,
系统启动时,自动运行程序 :
当系统启动完成时,会Broadcast一个Intent,Action为android.intent.action.BOOT_COMPLETED.
我们可以编写一个BroadcastReceiver 接收这个广播就可以了,然后在这个BroadcastReceiver中运行自己的程序代码。就达到了自动运行的目的。
要使这个BroadcastReceiver能接收这个Intent,要为这个Receiver加上对应的permission(android.permission.RECEIVE_BOOT_COMPLETED);
要达到上述的目的,我们只需要修改这个BroadcastReceiver所在的AndroidManifest.xml即可
......
<receiver android:name="TestBroadReceier" android:enabled="true" android:label="@string/hello"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
......
编译运行,当模拟器启动后,会马上调用BroadcastReceiver中的代码,会显示一个提示框。目的达到,我也要睡觉了!