Making a notification icon appear on boot/headset plugin (2个答案)
7年前关闭。
我要这样做,以便在有人插入耳机,在手机上执行任何操作而不仅仅是在应用程序上开始时,通知图标出现在通知区域中(非常顶部),我已经有了通知图标代码
//Notification Icon Starts
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification=new Notification(R.drawable.icon_notification, "Icon Notification", System.currentTimeMillis());
Context context=MainActivity.this;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), Notification.FLAG_ONGOING_EVENT);
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(this, "Notification Icon", "Touch for more options", contentIntent);
Intent intent=new Intent(context,MainActivity.class);
PendingIntent pending=PendingIntent.getActivity(context, 0, intent, 0);
nm.notify(0, notification);
//Notification Icon Ends
现在我只需要它,所以当您插入显示的耳机时。因此,我为此创建了一个新类,该类可以检测是否插入了该类,然后将其记录下来。而且一切正常
public class MusicIntentReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d("unplugged", "Headset was unplugged");
break;
case 1:
Log.d("plugged", "Headset is plugged");
break;
default:
Log.d("uh", "I have no idea what the headset state is");
}
}
}
因此,我尝试将Notification Icon代码放入案例1中,以便当它检测到已插入时,它将运行该代码。但是事实并非如此,相反,我遇到了大量错误。这是一个屏幕截图
http://prntscr.com/1xblhb,我只是想不出其他方法来实现此目的,我已经坚持了很长时间。因此,如果您能帮助我并尝试以初学者的方式说出来,那对我来说将意味着世界。非常感谢。
您在大多数地方都没有设置上下文。上下文不是MainActivity.this
,您甚至没有作用于mainactivity的范围。您的onReceive
中有一个上下文变量,只需使用它即可。
要从非 Activity /服务获取system service
,您需要使用
context.getSystemService()
您还试图在已经创建一个名为
intent
的变量时创建它,因此您需要另一个名称。
总而言之,看看错误在说什么并进行更改