android之广播(二)

时间:2022-02-23 18:40:42

广播接受者不仅可以通过清单文件来向系统注册,也可以通过代码来注册。并且有的广播必须通过代码来注册广播接受者。

  • 锁屏和解锁广播
  • 电量改变广播

打开屏幕和关闭屏幕


这里将广播接收者写在服务里面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="开始播放"
android:onClick="start"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="停止播放"
android:onClick="stop"/>
</LinearLayout>

Activity

package xidian.dy.com.chujia;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View; public class MainActivity extends AppCompatActivity {
Intent service;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
service = new Intent(this, MyService.class);
} public void start(View v){
startService(service);
} public void stop(View v){
stopService(service);
}
}

服务

在服务开启的时候注册广播,在服务销毁的时候销毁广播

package xidian.dy.com.chujia;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; /**
* Created by dy on 2016/7/12.
*/
class MyReceiver extends BroadcastReceiver{ @Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_SCREEN_OFF))
Log.i(this.getClass().getName(), "屏幕关闭");
if(action.equals(Intent.ACTION_SCREEN_ON))
Log.i(this.getClass().getName(), "屏幕点亮");
}
} public class MyService extends Service {
MyReceiver ms = new MyReceiver(); @Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(ms, filter);
} @Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(ms);
}
}

清单文件

在清单文件中只需要注册服务即可

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xidian.dy.com.chujia"> <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="主界面">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
</manifest>