可在自己需要的位置注册接受广播的action,这边是注册在Intent上。
1.添加action字符串
修改位置
frameworks/base/core/java/android/content/Intent.java
/**
*@hide
@hide必须要加
**/ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_demo="android.intent.action.demo";
2 注册该广播
修改位置
frameworks/base/core/res/AndroidManifest.xml
在需要的地方发送广播
Intentintent= newIntent(Intent.ACTION_demo);
intent.putExtra("state",state);
sendBroadcastToAll(intent);
- private void sendBroadcastToAll(Intent intent) {
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
finallongident = Binder.clearCallingIdentity();
try{
mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
}finally{
Binder.restoreCallingIdentity(ident);
}
- }
3.可在系统中写个接收的广播,此例中,添加一个服务,在服务中注册接收广播
新建服务:
在frameworks/base/packages/SystemUI/src/com/android/systemui/文件夹新建一个自己的目录,新建一个服务。 eg:frameworks/base/packages/SystemUI/src/com/android/systemui/test/TestService.java
+package com.android.systemui.test; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.IBinder; +import android.util.Log; + + +public class TestService extends Service { +
- private static final String TAG = "TestService";
- private SwitchAppReceiver receiver;
- @Override
- public void onCreate() {
super.onCreate();
Log.i(TAG,"TestService oncreate");
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"TestService onStartCommand");
registerReceiver();
returnsuper.onStartCommand(intent, flags, startId);
- }
- @Override
- public IBinder onBind(Intent intent) {
returnnull;
- }
- @Override
- public void onDestroy() {
Log.i(TAG,"TestService onDestroy");
unRegistReceiver();
super.onDestroy();
- }
- private void registerReceiver() {
receiver= new SwitchAppReceiver()
IntentFilterfilter=newIntentFilter();
filter.addAction(Intent.ACTION_TES_SWITCH_APP);
registerReceiver(receiver, filter);
- }
- private void unRegistReceiver() {
try{
this.unregisterReceiver(receiver);
}catch(Exceptione) {
}
- }
+}
新建广播
eg:frameworks/base/packages/SystemUI/src/com/android/systemui/test/SwitchAppReceiver.java
+package com.android.systemui.test; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.util.Log; + +public class SwitchAppReceiver extends BroadcastReceiver { +
+}
4.在合适的地方开启服务
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
public PhoneStatusBarPolicy(Context context, StatusBarIconController iconController) { /* start test switch app */ Log.d("TestService","##################"); Intent mIntent = new Intent(mContext,TesService.class); mContext.startService(mIntent); }
原作者:hxy_sakura
|