1.我的这个方法我测试了一下,在android8.0不能用,其他的都能用
以下是我的代码
2.创建broadreceived播放器,创建类NetworkStateReceiver.java
package com.example.administrator.breceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
//创建一个播放器
public class NetworkStateReceiver extends BroadcastReceiver {
private final String ACTION_BOOT = "com.example.administrator.MY_BROADCAST";
@Override
public void onReceive(Context context, Intent intent) {
//equals()复合数据的比较
if(ACTION_BOOT.equals(intent.getAction()))
Toast.makeText(context, "收到告白啦~",Toast.LENGTH_SHORT).show();
}
}
3.在AndroidManifest.xml中注册
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.breceiver">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//这里是注册的代码
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="com.example.administrator.MY_BROADCAST"/>
</intent-filter>
</receiver>
</application>
</manifest>
就是这个
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="com.example.administrator.MY_BROADCAST"/>
</intent-filter>
</receiver>
然后在MainActivity.java启动Intent
package com.example.administrator.breceiver;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//启动隐式intent
sendBroadcast(new Intent("com.example.administrator.MY_BROADCAST"));
}
});
}
}
这是主要代码,其他简单,自己加上就好,