我尝试使用ImageButton创建自定义通知。 当onclicked时,ImageButton应该启动一个名为TaskActivity的活动,但是我无法实现这一点。
以下是我的代码:
MainActivity.java
public void onCreate(Bundle savedInstanceState){
//button intents
Intent cmdIntent = new Intent(
MainActivity.this, cmdButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, cmdIntent, 0);
//notification mgr
int notifyID = 001;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotifyMgr = (NotificationManager)getSystemService(ns);
//new notification
int icon = R.drawable.icon3;
long when = System.currentTimeMillis();
@SuppressWarnings({ "deprecation" })
Notification notify = new Notification(icon,getString(R.string.text),when);
//remote views
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.custom_notification);
contentView.setImageViewResource(R.id.notification_image, R.drawable.icon4);
contentView.setTextViewText(R.id.notification_title, "APP TITLE");
contentView.setTextViewText(R.id.notification_text, "hello");
contentView.setOnClickPendingIntent(R.id.notification_image, pendingSwitchIntent);
notify.contentView = contentView; //set
//notification intent
Intent nIntent = new Intent(MainActivity.this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nIntent, 0);
notify.contentIntent = contentIntent;
mNotifyMgr.notify(notifyID,notify);
}
公共类cmdButtonListener扩展BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
System.out.println("Here, I am here");
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
}
}
Android清单
<receiver android:name=".MainActivity$cmdButtonListener" />
我不知道,我在哪里做错了,因为我完全按照大多数在线教程中的说法进行操作。 :(
答案 0 :(得分:0)
最后,我找到了解决方案......
声明以下变量
private static Context mContext;
在 public void onCreate(Bundle savedInstanceState){
中添加以下代码mContext = this;
最后,更改公共类中的以下代码片段cmdButtonListener extends BroadcastReceiver {
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
要
Intent Act = new Intent(mContext,TaskActivity.class);
mContext.startActivity(Act);