I am writing code in my MyActivity.java
class that extends android.app.Activity
It creates a custom notification, when user click on the button it sends a broadcast
.
There is a broadcast receiver that receives the broadcast
.
private void createDownloadNotification() {
Intent closeButton = new Intent("Download_Cancelled");
closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, closeButton, 0);
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.widget_update_notification);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setTicker("Ticker Text").setContent(notificationView);
notificationView.setProgressBar(R.id.pb_progress, 100, 12, false);
notificationView.setOnClickPendingIntent(R.id.btn_close, pendingSwitchIntent);
notificationManager.notify(1, builder.build());
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Received Cancelled Event");
}
}
Register receiver in AndroidManifest.xml
<receiver android:name=".MainActivity$DownloadCancelReceiver" android:exported="false">
<intent-filter>
<action android:name="Download_Cancelled" />
</intent-filter>
</receiver>
Since it is inner class so have to use $
sign
Widget xml is here
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close Me" />
<ProgressBar
android:id="@+id/pb_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…