I have the content module loaded, the specific error I'm getting is: The constructor Intent(new View.OnClickListener(){}, Class<ContactWidget>) is undefined
Any ideas on this? I got this from the tutorial here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
package com.example.contactwidget;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ContactWidget extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button calc1 = (Button) findViewById(R.id.calc_button_1);
calc1.setOnClickListener(buttonListener);
setContentView(R.layout.main);
}
private static final int HELLO_ID = 1;
private OnClickListener buttonListener = new OnClickListener() {
public void onClick (View v) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence ticketBrief = "Button Pressed Brief";
CharSequence ticketTitle = "Button pressed";
CharSequence ticketText = "You pressed button 1";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, ticketBrief, when);
Intent notificationIntent = new Intent(this, ContactWidget.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), ticketTitle, ticketText, contentIntent);
mNotificationManager.notify(HELLO_ID, notification);
}
};
}
Change this:
new Intent(this, ContactWidget.class);
to
new Intent(ContactWidget.this, ContactWidget.class);
The error happens because, in that case, this is referencing the instance of OnClickListener, but the Intent's constructor expects a Context. The context you have to pass is the reference to the activity itself, thus you have to access it explicitly using ContactWidget.this.
The context passed in could be from a remote application host... apparently you need the app context from your app, the one with your class (your broadcast reciever for instance).
Intent intent = new Intent(context.getApplicationContext(), WidgetryBroadcastReceiver.class);
instead of
Intent intent = new Intent(context, WidgetryBroadcastReceiver.class);
go figure.
yeah that workerd for me aswell for the error in
Geocoder gc = new Geocoder(this, Locale.getDefault());
Related
I have been trying to make an alarm application. I have been struggling with making a full screen notification. I finally did manage to do it, but it only works when the app is running in the background.
It also needs to work when you have closed the app. I don't understand what I am supposed to do to achieve this. I know it is possible because my alarm clock app I use every day is able to do this.
Mainactivity.java
package com.example.wekkerapp;
import java.util.Calendar;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "my_channel";
static final String FULL_SCREEN_ACTION = "full_screen_action";
static final int NOTIFICATION_ID = 1;
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Alarm";
String description = "Het alarm gaat";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("2", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
createNotificationChannel(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TimePicker klok = findViewById(R.id.timePicker1);
klok.setIs24HourView(true);
final Button getTimeBtn = findViewById(R.id.getTimeBtn);
final TextView showText = findViewById(R.id.showText);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
getTimeBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Intent intent = new Intent(FULL_SCREEN_ACTION, null, getApplicationContext(), WekkerService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int uur = klok.getHour();
int minuut = klok.getMinute();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, uur);
cal.set(Calendar.MINUTE, minuut);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Toast.makeText(getApplication().getApplicationContext(), "Alarm gaat om " + uur + ":" + minuut,Toast.LENGTH_LONG).show();
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
showText.setText(Integer.toString(uur) + ':' + Integer.toString(minuut));
NotificationManagerCompat.from(getApplicationContext()).cancel(NOTIFICATION_ID);
}
});
}
static void CreateFullScreenNotification(Context context) {
Intent intent = new Intent(context, MainActivity2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Alarm")
.setContentText("Het alarm gaat")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true);
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("channel_description");
notificationManager.createNotificationChannel(channel);
}
}
}
}
Wekkerservice.java
package com.example.wekkerapp;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import androidx.annotation.Nullable;
public class WekkerService extends IntentService {
public static MediaPlayer mediaPlayer;
public WekkerService() {
super("WekkerService");
}
#Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d("test", "onHandleIntent: ");
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.alarmpie);
if (MainActivity.FULL_SCREEN_ACTION.equals(intent.getAction()))
mediaPlayer.setLooping(true);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
MainActivity.CreateFullScreenNotification(getApplicationContext());
}
}
Mainactivity2.java
package com.example.wekkerapp;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button stopbutton = findViewById(R.id.button2);
stopbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WekkerService.mediaPlayer.stop();
}
});
}
}
I would suggest you use a BroadcastReceiver and then start the service from its onReceive method.
So in your MainActivity's onClick listener you should change the following pending intent
as follows:
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
to
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
and the intent you pass in should launch a BroadcastReceiver.
Immediately after the BroadcastReceiver is launched by the alarm manager, you should start the service from its onReceive method.
Remember that due to the recent changes the OS won't just let you start a service or background service just whenever and however you want!
If the app is closed and you want to start the service, you SHOULD start it as a ForgroundService and show a notification(you have 5 seconds to make this call) otherwise it will throw RemoteServiceException and that's why the code in your service will not run.
I highly encourage you to take a look at this answer:
https://stackoverflow.com/a/56471104/9023032
Here is also another useful answer which might become handy:
https://stackoverflow.com/a/54035247/9023032
I know that this type of question asked but they are unable to solve my problem, Hence I am asking it again for having exact solution to my problem, I am using android studio 3.0.1 for creating simple notification application, when i run this application it shows me errors as show as follow:
Error:(40, 25) error: PendingIntent() is not public in PendingIntent; cannot be accessed from outside package
and my MainActivity.java as follow
package com.example.ram.notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 45612;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
public void ClickNotification(View view){
//build the notification
notification.setSmallIcon(R.drawable.myimage);
notification.setTicker("this is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Here is the title");
notification.setContentText("I am the body of your notificattion");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = new PendingIntent().getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
//build notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
}
Please help me what should i do?
Simply delete "new" keyword in 40 row
must be
pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
I'm trying to get the Major ID from an iBeacon as a string and pass it to an activity called "LoginActivity.java" so that I can then pass it to my PHP script via Volley POST along with login info username and password, the script will first check if the beacon value is NULL, if so return an error that a beacon is not in range so they cannot log in.
So far I've gotten the Major ID and converted it to a string but I'm getting an error when creating the intent "Cannot resolve constructor". I marked the line where I'm getting the error with <<<<ERROR below. (It's near the end).
package com.mcrlogs.pp.test;
/**
* Created by myuser on 15/01/2017.
*/
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothClass;
import android.content.Context;
import android.content.Intent;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import java.util.List;
import java.util.UUID;
public class BeaconChecker extends Application {
private BeaconManager beaconManager;
public void showNotification(String title, String message) {
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0,
new Intent[] { notifyIntent }, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.security)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
}
#Override
public void onCreate() {
super.onCreate();
beaconManager = new BeaconManager(getApplicationContext());
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
beaconManager.startMonitoring(new Region(
"monitored region",
UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D"),
null, null));
}
});
beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() {
#Override
public void onEnteredRegion(Region region, List<Beacon> list) {
String iBeaconID = convertIBeaconIDToString(list.get(0).getMajor());
System.out.println(iBeaconID);
showNotification(
"MCR Beacon Detected!",
"Login enabled.");
}
private String convertIBeaconIDToString (int major) {
String iBeaconID = "";
iBeaconID = iBeaconID.concat(Integer.toString(major));
return iBeaconID;
Intent i = new Intent(this, LoginActivity.class); <<<<ERROR
i.putExtra("iBeaconID",iBeaconID);
}
#Override
public void onExitedRegion(Region region) {
// could add an "exit" notification too if you want (-:
}
});
}
}
Try changing:
Intent i = new Intent(this, LoginActivity.class);
To:
Intent i = new Intent(BeaconChecker.this, LoginActivity.class);
This clarifies that the this you refer to is the Application class that satisfies the requirements of the constructor for Intent.
I am trying to build a simple app that sends notifications to the device but only on a specific day/time. I have been able to get the notification part to work but cant seem to get the day & time problem solved. Any ideas?
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class NotificationsActivity extends Activity {
int notificationID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
displayNotification();
}
protected void displayNotification()
{
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.ic_launcher,
"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
notif.vibrate = new long[] { 100, 250, 100, 500};
nm.notify(notificationID, notif);
}
}
You need to use an AlarmManager to schedule these events. Then, from the callbacks, you show the notifications.
See for example Creating a Notification at a particular time through Alarm Manager
Be careful, as AlarManager will be cleared when the device reboots (you may need to re-register then on boot completed if necessary).
See this link Notification in Android Using AlarmManager, BoradCastReceiver & Services
It may be help you.
I'm hoping this issue is simply something to do with the emulator, basically ive got a Service that sets a timer, as soon as the timertask runs the following code is supposed to execute:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
int icon = R.drawable.androidapplogo;
CharSequence tickerText = "Ticker Text";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My Notification";
CharSequence contentText = "Hello World!";
//Do i need this?
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, null);
mNotificationManager.notify(1, notification);
The issue i have, is that when the notification gets called, it appears in the status bar, but when i click on the icon, it just has a blue circle. I dont own an android phone so im guessing that means its trying to load something.
Btw, ive pretty much lifted the code from here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
So my question is two fold:
- What is happening, is it failing to load something?
- Any ideas on how to fix it, or would it be worth finding a new form of notification
EDIT: Im sorry guys, found the issue was that you needed to drag down the Notification Window - i rarely use android x)
package com.androidtest.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SimpleNotification extends Activity {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Notification notifyDetails = new Notification(R.drawable.android,
"New Alert, Click Me!", System.currentTimeMillis());
Button start = (Button) findViewById(R.id.notifyButton);
Button cancel = (Button) findViewById(R.id.cancelButton);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence contentTitle = "TITLES....";
CharSequence contentText = "TEXT FOR DETAIL";
Intent notifyIntent = new Intent(
android.content.Intent.ACTION_VIEW, Uri
.parse("CONTACT NO / OR ANY OTHER ACTION WHICH YOU WANT ON NOTIfic. ICON TAP"));
PendingIntent intent = PendingIntent.getActivity(
SimpleNotification.this, 0, notifyIntent,
android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle,
contentText, intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
notifyDetails);
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
}
});
}
}
XML Test file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/notifyButton"
android:text="#string/notify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
></Button>
<Button
android:id="#+id/cancelButton"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
></Button>
</LinearLayout>
pending intent to call some intent on notification tap..gve ans frm whtevr i understand ur quest
leave comment if any prob with the code...