Trouble witn creating notification in status bar from service Android - java

I need to create Service in my application for showing notifications. I have the code for service:
package com.bba.droid;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class AlertsMonitorService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int id) {
NotificationManager notifyMngr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification=new Notification(R.drawable.icon_back, "Downloading...", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0);
notification.setLatestEventInfo(this.getApplicationContext(), "YoutubeDownloader", "The video is downloading...", contentIntent);
notifyMngr.notify(0, notification);
}
}
And I have code for main Activity:
package com.bba.droid;
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.util.DisplayMetrics;
import android.util.Log;
public class DroidTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent service=new Intent();
service.setClass(this, AlertsMonitorService.class);
this.startService(service);
}
}
But service doesn't create a notification in status bar. Where have I made mistake?

I don't know if this is the only problem, but you are specifying null for the activity in your intent:
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0);
You want to specify an intent that will launch your activity:
Intent intent = new Intent(this, DroidTestActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, 0);

Related

Android studio notification unable to display

package com.example.twapp.Observer;
import android.app.Notification;
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.widget.Button;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.example.twapp.Notify;
import com.example.twapp.R;
import com.example.twapp.testReceiver;
public class ConcreteObserverA extends AppCompatActivity implements Observer {
NotificationManager notificationManager;
NotificationChannel channel;
Context context = this;
private String observerState;
private ConcreteSubject concreteSubject; // 持有指向 ConcreteSubject 物件的 reference
public ConcreteObserverA(ConcreteSubject concreteSubject) {
this.concreteSubject = concreteSubject;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void update() {
setContentView(R.layout.activity_notify);
notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
channel=new NotificationChannel("ID","com.example.twapp",NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent(context,testReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("訊息")
.setContentText("跌倒啦~")
.setChannelId("ID");
Notification notification=builder.build();
notificationManager.notify(1,notification);
}
}
I use the Observer pattern to implement notifications, but I have problems when my concreateObserver wants to print notifications.
When I delete this method. Simple print is feasible.Because I can't think of a way. So come to ask everyone android studio master.

Make Android app get bluetooth manufacturer data

I am working on an Android app android 10 and nordic nrf52840 which is advertising at channel 37,38,39 I want to get the manufacturer data from my nordic bluetooth device. Like the picture shown below. Now I can scan and find my device, but I don't know how to get manufacturer data.
package com.example.test373839;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.BatchingListUpdateCallback;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter=null;
private BluetoothManager mbluetoothManager=null;
private BroadcastReceiver mReceiver=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnScan=(Button)findViewById(R.id.button);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
}
public void StartScan(View view) {
Log.d("Button","click");
checkBTPermission();
mBluetoothAdapter.startDiscovery();
IntentFilter dicoveryDeviceIntent=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastreceiver,dicoveryDeviceIntent);
}
private void checkBTPermission(){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
int pc=this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
pc+=this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(pc!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}else {
Log.d("Bluetooth","checkBT permission");
}
}
}
final private BroadcastReceiver mBroadcastreceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
Log.d("Bluetooth",device.getAddress()+":"+device.getName());
}
}
};
}

Service does not execute when app is closed, but it does execute when it's in the background

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

PDF file not opening using Android:OnClick

So I've managed to get a button to open a pdf file using an intent, however when i run the app and press the button it says "Cannot display PDF". Can anyone help me out as to where exactly the code goes wrong?
Here is the my activity:
package com.example.android.practiceapp;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import java.io.File;
public class promotions extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions);
final Button button = (Button) findViewById(R.id.earlybird);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pictures/Early_Bird_Bonus_Rules");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(intent, "Open With");
try {
startActivity(intent1);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
});
}
}

Multiple notifications with different data

I have an issue with my app that i cant solve. The app takes the input(reminder) from a user and then sets it as a notification. The user can create as many notifications as he/she likes. I want the user to click the notification and get taken to a new activity(Reminder), so he/she can see the reminder in a TextView. So i have an activity(SetReminder), which let the user put his data in a text editor.Then i save his data in a hashMap. The int is the id of user's string data. Then i have a class (AlarmReceiver) which extends BroacastReceiver and generates the notification.In this class i have an id for each notification,which matches the hashMap's int from the SetReminder activity. That way i was expecting that the user would see the data of each notification.But that's doesn't happen. I have multiple Notifications(i want that), but the user sees the data of the last notification, no matter which notifications selects. I am posting the code from the three activities.
Thanks in advance.
SetReminder.class
package demo.push_not_demo;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.widget.EditText;
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
import java.util.HashMap;
public class SetReminder extends AppCompatActivity {
private SwitchDateTimeDialogFragment dateTimeFragment;
Button b1,b2,b3;
EditText editText;
public static int counter=0;
public static HashMap<Integer,String> hashMap;
private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_reminder);
hashMap= new HashMap<Integer, String>();
b1=(Button) findViewById(R.id.set_date_time);
b2=(Button) findViewById(R.id.cancel);
b3=(Button) findViewById(R.id.save);
b1.setOnTouchListener(touch);
b2.setOnTouchListener(touch);
b3.setOnTouchListener(touch);
editText=(EditText) findViewById(R.id.reminder_edit);
}
View.OnTouchListener touch= new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()){
case R.id.set_date_time:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
// Construct SwitchDateTimePicker
dateTimeFragment = (SwitchDateTimeDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_DATETIME_FRAGMENT);
if(dateTimeFragment == null) {
dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
getString(R.string.label_datetime_dialog),
getString(R.string.positive_button_datetime_picker),
getString(R.string.negative_button_datetime_picker)
);
}
dateTimeFragment.show(getSupportFragmentManager(), TAG_DATETIME_FRAGMENT);
}
break;
case R.id.cancel:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
cancelalarm();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
Intent intent = new Intent(SetReminder.this,HomeScreen.class);
startActivity(intent);
}
break;
case R.id.save:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
counter++;
hashMap.put(counter,editText.getText().toString());
alarmservice();
}
break;
}
return false;
}
};
public void alarmservice(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(alarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+ 5000,pendingIntent);
}
public void cancelalarm(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
AlertReceiver.class
package demo.push_not_demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.EditText;
import java.util.HashMap;
import static android.support.v4.app.NotificationCompat.DEFAULT_SOUND;
import static android.support.v4.app.NotificationCompat.PRIORITY_HIGH;
import static android.support.v4.app.NotificationCompat.VISIBILITY_PUBLIC;
public class AlertReceiver extends BroadcastReceiver {
public static int id=0;
#Override
public void onReceive(Context context, Intent intent) {
id++;
createNotification(context);
}
private void createNotification(Context context) {
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSmallIcon(R.drawable.offer1)
.setContentTitle("Notification Title")
.setContentText("Tap to see your reminder")
.setPriority(PRIORITY_HIGH)
.setVibrate(new long[] { 50, 1000, 500, 1000, 1000 })
.setDefaults(DEFAULT_SOUND)
.setVisibility(VISIBILITY_PUBLIC);
Intent intent = new Intent(context,Reminder.class);
PendingIntent pendingintent = PendingIntent.getActivity(context,id,intent,PendingIntent.FLAG_ONE_SHOT);
notification.setContentIntent(pendingintent);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ntfc = notification.build();
nm.notify(id,ntfc);
}
}
Reminder.class
package demo.push_not_demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import static demo.push_not_demo.AlertReceiver.id;
import static demo.push_not_demo.SetReminder.hashMap;
public class Reminder extends AppCompatActivity{
TextView txtv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder);
txtv=(TextView) findViewById(R.id.reminder_textView);
txtv.setText(hashMap.get(id));
}
}
dont use static id,in your code id is always 0. you can check it using Log!
use another way for produce different ids.
when you add notification with same id, the new notification will replace with last notification. use random integer for id

Categories