我试图做一个通知,上面有2个按钮:
- 一个把我带回到活动
- 其他关闭它
有没有人有关于如何捕捉到按钮单击事件的想法(记住,活动暂停)?
我试图做一个通知,上面有2个按钮:
有没有人有关于如何捕捉到按钮单击事件的想法(记住,活动暂停)?
我很高兴将它张贴! 工作了一整夜后,我发现了什么。 所以,在这里,我们走!
1.创建您的通知的XML布局文件。
2.创建使用Notification.Builder通知。 将一切后,你想要(图标,声音等),这样做:
//R.layout.notification_layout is from step 1
RemoteViews contentView=new RemoteViews(ctx.getPackageName(), R.layout.notification_layout);
setListeners(contentView);//look at step 3
notification.contentView = contentView;
3.创建一个方法setListeners。 在此方法中,你必须这样写:
//HelperActivity will be shown at step 4
Intent radio=new Intent(ctx, packagename.youractivity.class);
radio.putExtra("AN_ACTION", "do");//if necessary
PendingIntent pRadio = PendingIntent.getActivity(ctx, 0, radio, 0);
//R.id.radio is a button from the layout which is created at step 2 view.setOnClickPendingIntent(R.id.radio, pRadio);
//Follows exactly my code!
Intent volume=new Intent(ctx, tsapalos11598712.bill3050.shortcuts.helper.HelperActivity.class);
volume.putExtra("DO", "volume");</p>
//HERE is the whole trick. Look at pVolume. I used 1 instead of 0.
PendingIntent pVolume = PendingIntent.getActivity(ctx, 1, volume, 0);
view.setOnClickPendingIntent(R.id.volume, pVolume);
4.对于我的要求我用它响应了主意,HelperActivity。 但对于你,我不认为这是必要的。
如果你想完整的源代码,你可以浏览它或者从我的混帐回购协议下载。 该代码是供个人使用的,所以不要指望有很多评论阅读华丽的代码。 https://github.com/BILLyTheLiTTle/AndroidProject_Shortcuts
所有上述,回答捕事件从不同的按钮的问题。
关于取消通知我在这里您重定向
如何清除Android的通知
不过,别忘了使用您的通知方法解析的ID,当你要求拳头时间通知
至于ICS,问题是简单的回复,因为所需的行为反映了默认的通知:您可以关闭通知其滑动到右侧,你可以定义用户发送当他按下它简单地使用到活动 PendingIntent
:
// The PendingIntent to launch our activity if the user selects this
// notification. Note the use of FLAG_CANCEL_CURRENT so that, if there
// is already an active matching pending intent, cancel it and replace
// it with the new array of Intents.
PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
makeMessageIntentStack(this, from, message), PendingIntent.FLAG_CANCEL_CURRENT);
从代码中采取http://developer.android.com/guide/topics/ui/notifiers/notifications.html
如果你想具体意图分配到一个按钮:
views.setOnClickPendingIntent(R.id.your_button_id, pendingIntent);
我想你只需要一个意向单击该按钮时发送,所以你必须避免设置的主要意图通知
notification.contentIntent = yourPendingIntent;
否则(如果设置“notification.contentIntent =的PendingIntent;”像往常一样)都意图将被称为这可能不是你想要什么/用户的期望。
如果你仍然想按通知的其他地方调用这个总的意图(或任何其他),你可以使用意向按次分配的方法与以上相同。 不要忘记设置
android:clickable="true"
任何视图你想跟踪的onClick()进行。
您可以通过它们在它们被调用活动额外跟踪这些意图。 如果你打电话给你主/发射活动比你在这里追踪他们(因为它来自的javadoc此方法):
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle data = intent.getExtras();
if (data != null && data.containsKey(YOUR_INTENT_KEY_SOURCE_CONSTANT)) {
// process your notification intent
}
// go on with smth else
}
您可以在简单的添加动作按钮Notification
设定行动的Notification.Builder
和定义PendingIntent
每个动作
下面是示例代码:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.addAction(R.drawable.action_posetive,"posetive",PendingIntent.getActivity(0,intent,0))
.addAction(R.drawable.action_clear,"clear",PendingIntent.getActivity(0,intent,0));
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
有你在这里一个完整的例子
//Add this code to onCreate or some onclick Buttton
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
long when = System.currentTimeMillis();
builder.setSmallIcon(R.drawable.ic_notification);
Intent notificationIntent = new Intent(getApplicationContext(), notificationActivity.class).putExtra("notification", "1");
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
Notification notification = builder.getNotification();
notification.when = when;
RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_view);
remoteViews.setTextViewText(R.id.tvName, "New Name");
listener(remoteViews,getApplicationContext());
notification.contentView = remoteViews;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(1, notification);
然后你就可以定义监听器的方法:
public void listener(RemoteViews remoteViews, Context context) {
// you have to make intetns for each action (your Buttons)
Intent intent = new Intent("Accept");
Intent intent2 = new Intent("Reject");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1,intent,0);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context,1,intent2,0);
// add actions here !
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Accept");
intentFilter.addAction("Reject");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("Accept")){
Toast.makeText(context, "Accepted !!", Toast.LENGTH_SHORT).show();
} else if(intent.getAction().equals("Reject")) {
Toast.makeText(context, "Rejected !!", Toast.LENGTH_SHORT).show();
}
}
};
context.registerReceiver(receiver,intentFilter);
remoteViews.setOnClickPendingIntent(R.id.ivRequest,pendingIntent);
remoteViews.setOnClickPendingIntent(R.id.ivReject,pendingIntent2);
}
这里是notification_view布局costumize您的通知。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Request from "
/>
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="15dp"
android:layout_toRightOf="@id/textView"
android:text="Amin"
/>
<ImageView
android:id="@+id/ivRequest"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:src="@drawable/notification"
/>
<ImageView
android:id="@+id/ivReject"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginEnd="10dp"
android:layout_toLeftOf="@id/ivRequest"
android:layout_centerVertical="true"
android:src="@drawable/trash"
/>
</RelativeLayout>
对我来说,这是工作大大..我会记下整个例子。 这是创建的通知
public void createNotification2(String aMessage) {
final int NOTIFY_ID = 11;
String name = getString(R.string.app_name);
String id = getString(R.string.app_name); // The user-visible name of the channel.
String description = getString(R.string.app_name); // The user-visible description of the channel.
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setLightColor(getColor(R.color.colorPrimaryDark));
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
} else {
}
Intent Off_broadcastIntent = new Intent(this, Database_Update.class);
Off_broadcastIntent.setAction("on");
Off_broadcastIntent.putExtra("toastMessage", "1");
PendingIntent Off_actionIntent = PendingIntent.getService(this, 0, Off_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent on_broadcastIntent = new Intent(this, Database_Update.class);
on_broadcastIntent.setAction("off");
on_broadcastIntent.putExtra("toastMessage", "0");
PendingIntent on_actionIntent = PendingIntent.getService(this, 0, on_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent cancel_broadcastIntent = new Intent(this, Database_Update.class);
cancel_broadcastIntent.setAction("cancel");
cancel_broadcastIntent.putExtra("toastMessage", "close");
PendingIntent cancel_actionIntent = PendingIntent.getService(this, 0, cancel_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent content_intent = new Intent(this, Status_Page.class);
content_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, content_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, id)
.setSmallIcon(android.R.drawable.ic_popup_reminder)
.setContentTitle(name)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.addAction(R.drawable.block, "ON", Off_actionIntent)
.addAction(R.drawable.notification, "OFF", on_actionIntent)
.addAction(R.drawable.clear, "CLOSE", cancel_actionIntent);
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;
notifManager.notify(11, notification);
}
在Android中Menifest
<service android:name=".Database_Update"></service>
这是服务类
public class Database_Update extends Service {
String result="";
Realm realm;
BlockList blockList;
@Override
public void onCreate() {
try {
RealmConfiguration config = new RealmConfiguration.Builder()
.name("notification.realm")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.build();
realm = Realm.getInstance(config);
} catch (Exception e) {
Log.d("Error Line Number", Log.getStackTraceString(e));
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.d("SERVICE","SERVICE CHECKING");
result=intent.getStringExtra("toastMessage");
Log.d("SERVICE",result);
if (realm!=null){
Log.d("SERVICE","realm working");
}else {
Log.d("SERVICE","Realm not working");
}
blockList=realm.where(BlockList.class).equalTo("package_name", "BLOCK_ALL").findFirst();
try {
Log.d("SERVICE",blockList.getStatus());
} catch (Exception e) {
Log.d("Error Line Number", Log.getStackTraceString(e));
}
realm.beginTransaction();
if (result.equals("1")){
if (blockList==null){
BlockList blockList_new=realm.createObject(BlockList.class);
blockList_new.setPackage_name("BLOCK_ALL");
blockList_new.setStatus("yes");
}else {
blockList.setStatus("yes");
}
Log.d("SERVICE","BLOCKING NOTIFICATION");
Toast.makeText(this, "BLOCKING", Toast.LENGTH_SHORT).show();
}else if (result.equals("0")){
if (blockList==null){
BlockList blockList_new=realm.createObject(BlockList.class);
blockList_new.setPackage_name("BLOCK_ALL");
blockList_new.setStatus("no");
}else {
blockList.setStatus("no");
}
Log.d("SERVICE","ALLOW NOTIFICATION");
Toast.makeText(this, "ALLOW NOTIFICATION", Toast.LENGTH_SHORT).show();
}else if (result.equals("close")){
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(11);
Log.d("SERVICE","REMOVING");
Toast.makeText(this, "CLOSED", Toast.LENGTH_SHORT).show();
}
realm.commitTransaction();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
if (realm!=null){
realm.close();
}
Toast.makeText(this, "REMOVING", Toast.LENGTH_SHORT).show();
}
}