0% found this document useful (0 votes)
16 views10 pages

Lab 6 X

Uploaded by

bukasz1500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views10 pages

Lab 6 X

Uploaded by

bukasz1500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Laboratorium nr 6

Temat: Powiadomienia lokalne w aplikacji wysyłającej


SMS.

Cel: Rozbudowa programu wysyłającego SMS w oparciu o


bibliotekę NotificationCompat.

Budowa aplikacji do obsługi Powiadomień Lokalnych:


Plik activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="utp.edu.notification.MainActivity">

<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="7"
android:columnCount="2"
android:orientation="horizontal">

<EditText
android:id="@+id/main_primary_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"
android:hint="@string/main_primary_title"
android:text="@string/main_primary_title" />

<Button
android:id="@+id/main_primary_send1"
android:layout_columnWeight="1"
android:layout_height="wrap_content"

android:text="@string/main_primary_send1" />

<Button
android:id="@+id/main_primary_send2"
android:layout_columnWeight="1"
android:layout_height="wrap_content"

android:text="@string/main_primary_send2" />

<ImageButton
android:id="@+id/main_primary_config"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"

android:src="@android:drawable/ic_menu_preferences"
android:contentDescription="@string/main_primary_config" />

<Space
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal" />

<EditText
android:id="@+id/main_secondary_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"
android:hint="@string/main_secondary_title"
android:text="@string/main_secondary_title" />

<Button
android:id="@+id/main_secondary_send1"
android:layout_columnWeight="1"
android:layout_height="wrap_content"

android:text="@string/main_secondary_send1" />

<Button
android:id="@+id/main_secondary_send2"
android:layout_columnWeight="1"
android:layout_height="wrap_content"

android:text="@string/main_secondary_send2"/>

<ImageButton
android:id="@+id/main_secondary_config"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"

android:src="@android:drawable/ic_menu_preferences"
android:contentDescription="@string/main_secondary_config" />

</GridLayout>

<LinearLayout
android:id="@+id/main_footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true">

<Button
android:text="@string/btnA_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/btnA"
android:layout_weight="1" />
</LinearLayout>

</RelativeLayout>

Plik: MainActivity

package utp.edu.notification;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

/**
* Display main screen for sample. Displays controls for sending test notifica-
tions.
*/
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();

private static final int NOTI_PRIMARY1 = 1100;


private static final int NOTI_PRIMARY2 = 1101;
private static final int NOTI_SECONDARY1 = 1200;
private static final int NOTI_SECONDARY2 = 1201;

/*
* A view model for interacting with the UI elements.
*/
private MainNotifUi Notifui;

/*
* A
*/
private NotificationHelper noti;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noti = new NotificationHelper(this);
Notifui = new MainNotifUi(findViewById(R.id.activity_main));
}

/**
* Send activity notifications.
*
* @param id The ID of the notification to create
* @param title The title of the notification
*/
@RequiresApi(api = Build.VERSION_CODES.Q)
public void sendNotification(int id, String title) {
NotificationCompat.Builder nb = null;
switch (id) {
case NOTI_PRIMARY1:
nb = noti.getNotification1(title, getString(R.string.pri-
mary1_body), "Kanał1 P1");
break;

case NOTI_PRIMARY2:
nb = noti.getNotification1(title, getString(R.string.pri-
mary2_body), "Kanał1 P2");
break;

case NOTI_SECONDARY1:
nb = noti.getNotification2(title, getString(R.string.second-
ary1_body), "Kanał2 P1");
break;
case NOTI_SECONDARY2:
nb = noti.getNotification2(title, getString(R.string.second-
ary2_body), "Kanał2 P2");
break;
}
if (nb != null) {
noti.notify(id, nb);

}
}

/**
* Send Intent to load system Notification Settings for this app.
*/
public void goToNotificationSettings() {
Intent i = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
i.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(i);
}

/**
* Send intent to load system Notification Settings UI for a particular chan-
nel.
*
* @param channel Name of channel to configure
*/
public void goToNotificationSettings(String channel) {
Intent i = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
i.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
i.putExtra(Settings.EXTRA_CHANNEL_ID, channel);
startActivity(i);
}

/**
* View model for interacting with Activity UI elements. (Keeps core logic for
sample
* seperate.)
*/
class MainNotifUi implements View.OnClickListener {
final TextView titlePrimary;
final TextView titleSecondary;

private MainNotifUi(View root) {


titlePrimary = root.findViewById(R.id.main_primary_title);
root.findViewById(R.id.main_primary_send1).setOnClickListener(this);
root.findViewById(R.id.main_primary_send2).setOnClickListener(this);
root.findViewById(R.id.main_primary_config).setOnClickListener(this);

titleSecondary = root.findViewById(R.id.main_secondary_title);
root.findViewById(R.id.main_secondary_send1).setOnClickListener(this);
root.findViewById(R.id.main_secondary_send2).setOnClickListener(this);
root.findViewById(R.id.main_secondary_config).setOnClick-
Listener(this);

root.findViewById(R.id.btnA).setOnClickListener(this);
}

private String getTitlePrimaryText() {


if (titlePrimary != null) {
return titlePrimary.getText().toString();
}
return "";
}

private String getTitleSecondaryText() {


if (titlePrimary != null) {
return titleSecondary.getText().toString();
}
return "";
}

@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.main_primary_send1:
sendNotification(NOTI_PRIMARY1, getTitlePrimaryText());
break;
case R.id.main_primary_send2:
sendNotification(NOTI_PRIMARY2, getTitlePrimaryText());
break;
case R.id.main_primary_config:
goToNotificationSettings(NotificationHelper.PRIMARY_CHANNEL);
break;

case R.id.main_secondary_send1:
sendNotification(NOTI_SECONDARY1, getTitleSecondaryText());
break;
case R.id.main_secondary_send2:
sendNotification(NOTI_SECONDARY2, getTitleSecondaryText());
break;
case R.id.main_secondary_config:
goToNotificationSettings(NotificationHelper.SECONDARY_CHAN-
NEL);
break;
case R.id.btnA:
goToNotificationSettings();
break;
default:
Log.e(TAG, "Unknown click event.");
break;
}
}
}
}

Plik: NotificationHelper

package utp.edu.notification;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

/**
* Helper class to manage notification channels, and create notifications.
*/
class NotificationHelper extends ContextWrapper {
private NotificationManager manager;
public static final String PRIMARY_CHANNEL = "default";
public static final String SECONDARY_CHANNEL = "second";

/**
* Registers notification channels, which can be used later by individual no-
tifications.
*
* @param ctx The application context
*/
@TargetApi(Build.VERSION_CODES.Q)

public NotificationHelper(Context ctx) {


super(ctx);

NotificationChannel chan1 = new NotificationChannel(PRIMARY_CHANNEL,


getString(R.string.noti_channel_default), NotificationManager.IM-
PORTANCE_DEFAULT);
chan1.enableLights(false);
chan1.setShowBadge(false);

chan1.setLightColor(Color.GREEN);
chan1.setAllowBubbles(false);
long[] longs = {45L, 1007L};
chan1.setVibrationPattern(longs);

chan1.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(chan1);

NotificationChannel chan2 = new NotificationChannel(SECONDARY_CHANNEL,


getString(R.string.noti_channel_second), NotificationManager.IM-
PORTANCE_HIGH);
chan2.setLightColor(Color.BLUE);
chan2.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(chan2);
}

/**
* Get a notification of type 1
* <p>
* Provide the builder rather than the notification it's self as useful for
making notification
* changes.
*
* @param title the title of the notification
* @param body the body text for the notification
* @return the builder as it keeps a reference to the notification (since API
24)
*/
@RequiresApi(api = Build.VERSION_CODES.Q)

public NotificationCompat.Builder getNotification1(String title, String body,


String text2) {
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", body);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Builder(getApplicationContext(), PRI-
MARY_CHANNEL)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setContentTitle(title)
.setSubText(text2)
.setContentText(body)
.setSmallIcon(getSmallIcon())
.setStyle(new NotificationCompat.InboxStyle()
.addLine("This is line 1" + body)
.addLine("This is line 2" + body)
.addLine("This is line 3" + body)
.addLine("This is line 4" + body)
.addLine("This is line 5" + body + "5")
.addLine("This is line 6" + body)
.addLine("This is line 7" + body)
.setBigContentTitle("Big Content Title")
.setSummaryText("Summary Text"))
.setColor(Color.RED)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher, body, actionIntent);

/**
* Build notification for secondary channel.
*
* @param title Title for notification.
* @param body Message for notification.
* @return A Notification.Builder configured with the selected channel and de-
tails
*/
@RequiresApi(api = Build.VERSION_CODES.Q)

public NotificationCompat.Builder getNotification2(String title, String body,


String text2) {
// Instantiate the Image (Big Picture) style:
Notification.BigPictureStyle picStyle = new Notification.BigPictur-
eStyle();
// Convert the image to a bitmap before passing it into the style:

Intent activityIntent = new Intent(this, MainActivity.class);


PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", body);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawa-
ble.lemur);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

return new NotificationCompat.Builder(getApplicationContext(), SECOND-


ARY_CHANNEL)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentTitle(title)
.setSubText(text2)
.setLargeIcon(largeIcon)

.setStyle(new NotificationCompat.BigTextStyle()
.bigText(getString(R.string.long_dummy_text))
.setBigContentTitle("Big Content Title")
.setSummaryText("Summary Text"))
.setContentText(body)
.setSmallIcon(getSmallIcon())
.setColor(Color.YELLOW)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.addAction(R.mipmap.ic_launcher, body, actionIntent);

/**
* Send a notification.
*
* @param id The ID of the notification
* @param notification The notification object
*/
@RequiresApi(api = Build.VERSION_CODES.Q)

public void notify(int id, NotificationCompat.Builder notification) {


getManager().notify(id, notification.build());
}

/**
* Get the small icon for this app
*
* @return The small icon resource id
*/
@RequiresApi(api = Build.VERSION_CODES.Q)

private int getSmallIcon() {

return android.R.drawable.stat_notify_chat;
}
@RequiresApi(api = Build.VERSION_CODES.Q)

private int getEmailIcon() {

return android.R.drawable.ic_dialog_email;
}

/**
* Get the notification manager.
* <p>
* Utility method as this helper works with it a lot.
*
* @return The system service NotificationManager
*/
@RequiresApi(api = Build.VERSION_CODES.Q)

private NotificationManager getManager() {


if (manager == null) {

manager = (NotificationManager) getSystemService(Context.NOTIFICA-


TION_SERVICE);
}
return manager;
}

Plik: NotificationReceiver

package utp.edu.notification;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class NotificationReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("toastMessage");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}

You might also like