Android的Broadcase的使用

工程目录:
Android的Broadcase的使用
Android的Broadcase的使用
Android的Broadcase的使用
app-MainActivity

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.btn1).setOnClickListener(this);
findViewById(R.id.btn2).setOnClickListener(this);
findViewById(R.id.btn3).setOnClickListener(this);
findViewById(R.id.btn4).setOnClickListener(this);
findViewById(R.id.btn5).setOnClickListener(this);
}

@Override
public void onClick(View v) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.example.app1");
switch(v.getId()){
case R.id.btn1:
intent = getPackageManager().getLaunchIntentForPackage("com.example.app1");
break;
case R.id.btn2:
intent = getPackageManager().getLaunchIntentForPackage("com.example.app2");
break;
case R.id.btn3:
intent = getPackageManager().getLaunchIntentForPackage("com.example.app3");
break;
case R.id.btn4:
intent = getPackageManager().getLaunchIntentForPackage("com.example.app4");
break;
case R.id.btn5:
intent = getPackageManager().getLaunchIntentForPackage("com.example.app5");
break;
}
if (intent == null) {
Toast.makeText(getApplicationContext(),"没有安装该app",Toast.LENGTH_SHORT).show();
} else {
startActivity(intent);
}
}
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="系统广播,接收短信放音乐(静态注册)" />

<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="短信广播,接收短信显示内容(静态注册)" />

<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="系统广播,按钮停止音乐服务(停止服务)" />

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义广播(动态注册)" />

<Button
android:id="@+id/btn5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="使用PendingIntent创建通知" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

app1-MainActivity

package com.example.app1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{"android.permission.RECEIVE_SMS"},1);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if(grantResults[0]!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "未授权,无法实现预定的功能!", Toast.LENGTH_SHORT).show();
finish();
}
}
}

@Override
protected void onDestroy() { //按手机返回键时触发
super.onDestroy();
//创建组件对象
ComponentName receiver = new ComponentName(this,SmsReceiver.class);
//获取包管理器对象
PackageManager pm = getPackageManager();
//禁用一个静态注册的广播接收者
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}

SmsReceiver

package com.example.app1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;

public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer = MediaPlayer.create(context,R.raw.cc);
mediaPlayer.start();
}
}

manifestes

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app1">

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<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">
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

app2-manifestes

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app2">

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<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">
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

MainActivity

package com.example.app2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{"android.permission.RECEIVE_SMS"},1);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if(grantResults[0]!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "未授权,无法实现预定的功能!", Toast.LENGTH_SHORT).show();
finish();
}
}
}

@Override
protected void onDestroy() { //按手机返回键时触发
super.onDestroy();
//创建组件对象
ComponentName receiver = new ComponentName(this,SmsReceiver.class);
//获取包管理器对象
PackageManager pm = getPackageManager();
//禁用一个静态注册的广播接收者
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}

SmsReceiver

package com.example.app2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//获取发送短信意图对象携带的数据
Bundle bundle = intent.getExtras();
if(bundle != null){
//可使用动态调试,查看短信数据结构
Object[] pdus = (Object[]) bundle.get("pdus");
//发送方的一条短信可能被分割、分多次发送
SmsMessage[] msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
byte[] pdu = (byte[]) pdus[i];
//获取分段的短信
msgs[i]= SmsMessage.createFromPdu(pdu);
}
//构建短信相关信息字符串
StringBuilder strb=new StringBuilder();
for(SmsMessage msg:msgs){
strb.append("\n发短信人电话:\n")
.append(msg.getDisplayOriginatingAddress())
.append("\n短信内容:\n")
.append(msg.getMessageBody());
//接收时间
Date date=new Date(msg.getTimestampMillis());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strb.append("\n短信接收时间:\n").append(sdf.format(date));
}
//在context指示的上下文(就是模块的MainActivity)里打Toast消息
Toast.makeText(context, strb, Toast.LENGTH_LONG).show();
}
}
}

app3-manifestes

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app3">

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<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">
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>

<service
android:name=".MyAudioService"
android:enabled="true"
android:exported="true" />

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

MainActivity

package com.example.app3;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Button btnStop;
private boolean isCast; //是否为广播激活

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{"android.permission.RECEIVE_SMS"},1);
}
btnStop=findViewById(R.id.btnStop);
Intent intent = getIntent(); //获取广播意图对象
isCast = intent.getBooleanExtra("iscast", false); //默认值为false
btnStop.setEnabled(isCast); //设置停止按钮可用和单击监听
if(isCast) Toast.makeText(this, "正在播放音乐...", Toast.LENGTH_SHORT).show();
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
//显式服务调用意图(非绑定式)
Intent intent=new Intent(MainActivity.this,MyAudioService.class);
//在Activity组件里,停止音乐播放服务
stopService(intent);
finish(); //销毁本活动
}
});
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if(grantResults[0]!= PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "未授权,无法实现预定的功能!", Toast.LENGTH_SHORT).show();
finish();
}else{
Toast.makeText(this, "请发一条短信验证...", Toast.LENGTH_SHORT).show();
}
}
}
}

MyAudioService

package com.example.app3;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MyAudioService extends Service {
MediaPlayer mediaPlayer;

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this,R.raw.cc);
mediaPlayer.start();
}
@Override
public void onDestroy() {
mediaPlayer.stop();
}
}

SmsReceiver

package com.example.app3;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

Intent serviceIntent = new Intent(context, MyAudioService.class);
//在广播组件里,通过上下文对象启动音乐播放服务组件
context.startService(serviceIntent);

//新建调用Activity组件的意图
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra("iscast", true); //携带数据
//新建栈用来存放被启动的Activity(当已经存在时,只做移动处理)
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//在广播组件里,通过上下文对象启动Activity组件
context.startActivity(activityIntent);
}
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/btnStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="Stop Music" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

app4-MainActivity

package com.example.app4;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private TextView tv; //用于显示接收到的广播信息
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle mybundle = intent.getExtras();
String str1 = mybundle.getString("data1");
String str2 = mybundle.getString("data2");
Toast.makeText(context, str1+" " +str2, Toast.LENGTH_LONG).show();
tv.setText(str1+" " +str2);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//使用意图过滤器类IntentFilter动态注册广播接收者
IntentFilter myintentfliter = new IntentFilter();
myintentfliter.addAction("com.example.broadcast.MY_BROADCAST");
registerReceiver(myReceiver, myintentfliter);

tv = findViewById(R.id.tv);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent myintent = new Intent("com.example.broadcast.MY_BROADCAST");
Bundle bundle = new Bundle();
bundle.putString("data1", "自定义广播与接收案例");
bundle.putString("data2", "我是自定义的字符串!");
myintent.putExtras(bundle); //捆绑数据
sendBroadcast(myintent); //发送广播
try {
Thread.sleep(1000); //休眠一下,模拟广播可能存在的延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="运行时快速发广播" />

<TextView
android:id="@+id/tv"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

app5-MainActivity

package com.example.app5;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
NotificationManager notificationManager; //通知管理器
NotificationCompat.Builder builder; //通知构造器(与Android版本相关)
Button btn_notification; //按钮
boolean isCreate = false; //通知未创建

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn_notification = findViewById(R.id.btn_notification);
//创建设置意图对象
Intent intent = new Intent(Settings.ACTION_SETTINGS);
//创建延期意图对象
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
//获取通知管理器
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//使用通知构造器
builder = new NotificationCompat.Builder(this,getPackageName());
//构建通知内容
builder.setSmallIcon(R.drawable.ic_launcher_foreground) //图标使用矢量图形
.setContentTitle("进入设置界面")
.setContentText("点击进入设置界面")
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent); //关键方法
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //Android 8.0
NotificationChannel channel = new NotificationChannel( //Android 8.0需要创建通知频道
getPackageName(),
"MusicNotify",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}

btn_notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isCreate = !isCreate; //在创建与取消之间切换
TextView tv=findViewById(R.id.hide_tv);
if(isCreate) { //如果准备创建通知
//发送通知至通知栏
notificationManager.notify(1, builder.build()); //发通知
tv.setVisibility(View.VISIBLE); //设置可见
btn_notification.setText("取消通知");
}else {
notificationManager.cancel(1); //取消通知
btn_notification.setText("创建通知");
tv.setVisibility(View.INVISIBLE); //设置不可见
}
}
});
}
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/btn_notification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发通知" />

<TextView
android:id="@+id/hide_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
android:gravity="center"
android:text="通知已创建,请下拉查看!" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

app1:
Android的Broadcase的使用
app2:
Android的Broadcase的使用
app3:
Android的Broadcase的使用
app4:
Android的Broadcase的使用
app5:
Android的Broadcase的使用

原创:https://www.panoramacn.com
源码网提供WordPress源码,帝国CMS源码discuz源码,微信小程序,小说源码,杰奇源码,thinkphp源码,ecshop模板源码,微擎模板源码,dede源码,织梦源码等。

专业搭建小说网站,小说程序,杰奇系列,微信小说系列,app系列小说

Android的Broadcase的使用

免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。

您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可-> 联系客服 投诉资源
www.panoramacn.com资源全部来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:2640602276@qq.com
未经允许不得转载:书荒源码源码网每日更新网站源码模板! » Android的Broadcase的使用
关注我们小说电影免费看
关注我们,获取更多的全网素材资源,有趣有料!
120000+人已关注
分享到:
赞(0) 打赏

评论抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

您的打赏就是我分享的动力!

支付宝扫一扫打赏

微信扫一扫打赏