Local Notification not working while save video recording - java

I want to just Generate a notification after save Video.
for this i'll try below code :
public void stopRecordingVideo() {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.MediaColumns.DATA, file.toString());
activity.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(activity, "Video saved: " + file, Toast.LENGTH_SHORT).show();
//Log.v(TAG, "Video saved: " + getVideoFile(context));
Log.v(TAG, "Video saved: " + file);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word") // message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
} else{
// do something for phones running an SDK before lollipop
}
try{
mMediaRecorder.stop();
mMediaRecorder.release();
}catch(RuntimeException stopException){
//handle cleanup here
}
try {
mSession.stopRepeating();
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setup2Record();
} else {
finish(); //just blows up anyway.
}
}
Video save perfectly in Storage and Toast msg also show. but only notification not generated please help for this solution.

Solution:
On Android 8.0 (Oreo) you must have something called as a NotificationChannel So try the below implementation:
Step1: Create Notification Channel
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Finally: Then your Notification:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word") // message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
notificationManager.notify(1, mBuilder.build());
Try this, Hope it helps.

Related

Turn Screen on when Notification Received

I am building an android application which push notification in specific times and this working well for me and notification received at these times but I want to turn on screen when Notification received.
I searched for that and I found all answers use PowerManager.FULL_WAKE_LOCK which is deprecated now so I need new way for this, How can I do that ?
this is my Notification code
public void ShowNotification(String title, String message, Class acticity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, "my app",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID);
builder.setSmallIcon(R.drawable.notif)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setAutoCancel(true);
Intent intent = new Intent(context, acticity);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.putExtra("clicked", true);
PendingIntent pi = PendingIntent.getActivity(context, 99,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);
Uri sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound);
mp = MediaPlayer.create(context, sound);
mp.start();
mcompact.notify(99, builder.build());
}

Sending notification from IntentService is not working?

I'm trying to send a notification from an IntentService.
I do get all the logs, but I don't get the notification (Using my galaxy s8 instead of an emulator).
I've tried to extend Service and I have tried to use a scheduler, but both did not work.
Service Code:
public class AppService extends IntentService {
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;
public AppService() {
super("AppService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d("AppService", "Started");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
Log.d("AppService", "Sending notification");
sendNotification("We might have some brand new movies to offer you!");
Log.d("AppService", "Notification sent");
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("AppService", "1");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Analyze.class), 0);
Log.d("AppService", "2");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MyCienma")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSmallIcon(R.drawable.icon_500x500_no_edge)
.setContentText(msg);
Log.d("AppService", "3");
mBuilder.setContentIntent(contentIntent);
Log.d("AppService", "4");
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d("AppService", "5");
}
}
I do get all the Logs, but I don't get any notification.
My project's min version is 21 and my phone is running 26. Is that a problem?
Yes, just because you have to set the notification channel id after android version 8.0(api 26).
Reference link:here
Hope! this will help you.
Happy coding...
After API v26 you have to define a NotificationChannel for every notification
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}

Android Studio - Service Crash after WebView uses file:/// to display local website

My Problem as follows:
Since I added into webview "file:///android_asset/index.html" to load from, it crashes at startService(new Intent(this, TimeService.class));. If startService commented out. It works fine. When it is used, but I give webview a address like www.google.de, everything works fine. I am using API Level 26 for developing. Unfortunately I can not resolve this issue by now.
Java Code:
MainActivity.webView.loadUrl("file:///android_asset/index.html");
MainActivity.webView.getSettings().setJavaScriptEnabled(true);
MainActivity.webView.getSettings().setUseWideViewPort(true);
MainActivity.webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
//tel nummer support
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:"))
{
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
//email support
if(url.startsWith("mailto:")){
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
startActivity(i);
}
view.loadUrl(url);
return true;
}
});
startService(new Intent(this, TimeService.class));
Crash message:
FATAL EXCEPTION: Thread-6
Process: com.feuerwehrmautern.ffmautern, PID: 3656
android.os.FileUriExposedException: file:///android_asset/index.html exposed beyond app through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1978)
at android.net.Uri.checkFileUriExposed(Uri.java:2371)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10247)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10201)
at android.app.PendingIntent.getActivity(PendingIntent.java:347)
at android.app.PendingIntent.getActivity(PendingIntent.java:309)
at com.feuerwehrmautern.ffmautern.TimeService.sendNotification(TimeService.java:241)
at com.feuerwehrmautern.ffmautern.TimeService.notificationStuff(TimeService.java:133)
at com.feuerwehrmautern.ffmautern.TimeService.access$100(TimeService.java:41)
at com.feuerwehrmautern.ffmautern.TimeService$TimeDisplayTimerTask$1$2.run(TimeService.java:223)
at java.lang.Thread.run(Thread.java:764)
Service Classs sendNotification
public synchronized void sendNotification(String headtext, String bodytext) {
synchronized(TimeService.class) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Preferences.HOMEPAGE));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
if (notificationID > 999) {
notificationID = 1;
}
NotificationManager mNotificationManager;
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = Preferences.ANDROID_CHANNEL_NAME;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(Preferences.CHANNEL_ID, name, importance);
channel.setDescription(Preferences.CHANNEL_DESCRIPTION);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
mNotificationManager = getSystemService(NotificationManager.class);
mNotificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(TimeService.this, Preferences.CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(headtext)
.setContentText(bodytext)
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(new Notification.BigTextStyle().bigText(bodytext))
.build();
} else {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification.Builder(TimeService.this)
.setContentIntent(pendingIntent)
.setContentTitle(headtext)
.setContentText(bodytext)
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(new Notification.BigTextStyle().bigText(bodytext))
.build();
Uri notificationRingtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notificationRingtone);
r.play();
}
mNotificationManager.notify(new Random().nextInt(99999 + 1), notification);
// System.out.println("Notification " + headtext + " notification NR: " + notificationID);
incrementNotificationID();
}
}
Starting from api v24 file: scheme is forbidden. Check this solution.

Android Version 8.1, Bad notification for startForeground

I have given my couple of days to solve this issue. My app is getting crash whose android version is 8.1. It is working perfectly fine in Android Version 8.0.
I followed the link mentioned below for the solution and tried many solutions given in this link but my application is not opening.
startForeground fail after upgrade to Android 8.1
I check the Android version in FirebaseMessageService class and create the channel for Oreo version but below given error is showing everytime
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Here below is my code. Please help me to rectify this problem
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
private NotificationManager notifManager;
Context mContext;
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
sendNotification();
}
public void sendNotification()
{
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logipace")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel(channelId, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Below is the code which I used in the onCreate() method of my Activity class.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
// Create channel to show notifications.
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.default_notification_channel_name);
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_LOW));
}
Help me to resolve this issue.
Put your logic inside onMessageReceived: Check Firebase quickstart sample.
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
final String msg = object.getString("msg");
sendNotification(msg);
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Notification Does Not Open Intent

When I click on the notification that pops up it doesn't open BaseApplication.class. What am I doing wrong here? I want the notification to open BaseApplication.class
public static void sendBasicNotification(int minor, int major, String task) {
Intent notifyIntent = new Intent(currentContext, BaseApplication.class);
notifyIntent.putExtra("t", task);
notifyIntent.putExtra("ma", major);
notifyIntent.putExtra("mi", minor);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(currentContext, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
int notificationID = 21;
NotificationCompat.Builder builder = new NotificationCompat.Builder(currentContext)
.setContentText("You have started the task: " + task).setContentTitle("Task Alert")
.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis()).setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.getNotification();
NotificationManager notificationManager = getNotificationManager(currentContext);
notificationManager.notify(notificationID, notification);
}
static NotificationManager getNotificationManager(Context context) {
return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Turns out I was sending the intent to the wrong class. Thanks all, fixed now. That code works just fine.
try adding this line
notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_SINGLE_TOP);
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// MainActivity is the Notification Intent that open by intent
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Application name")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
hope it will work

Categories