用于实现类似音乐播放器通知栏功能(播放、暂停、上下一曲)
1、自定义通知栏
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default");
builder.setSmallIcon(android.R.drawable.sym_def_app_icon);
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.message);
rv.setTextViewText(R.id.tv, "泡沫");//修改自定义View中的歌名
//修改自定义View中的图片(两种方法)
rv.setImageViewResource(R.id.iv, R.mipmap.ic_launcher);
rv.setImageViewBitmap(R.id.iv, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContent(rv);
//设置button监听为发送广播------------------
Intent previous = new Intent("com.example.Bean.MyBroadcastReceiver");
PendingIntent pi_previous = PendingIntent.getBroadcast(Tongzhi.this, 0,
previous, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.btn1, pi_previous);
//----------------------------------------
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0x1, notification);
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="仗剑走天涯"/>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一首"/>
</LinearLayout>
2、自定义广播
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "okgb", Toast.LENGTH_SHORT).show();
}
}
................
</activity>
<receiver
android:name=".Bean.MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter ><action android:name="com.example.Bean.MyBroadcastReceiver"></action> </intent-filter>
</receiver>
</application>
发送这条广播测试广播是否注册成功
Intent integer = new Intent("com.example.Bean.MyBroadcastReceiver");
sendBroadcast(integer);