Sorry for bad english!!!
I am developing my final year project where i need a chat box. i have successfully develop the chat system. but there is little bit of problem with notification. When my app is running on device it receives all the notifications but after killing or closing the application no notification arrived on y device. i have tested it on many devices but all in vain. Please help on this because i have to submit this on next monday.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getNotification()!=null){
String title=remoteMessage.getNotification().getTitle();
String body=remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(),title,body);
}
}
}
public class NotificationHelper {
public static void displayNotification(Context context,String title,String body){
Intent intent=new Intent(context,ChatActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context, ChatActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notifications)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManagerCompat=NotificationManagerCompat.from(context);
notificationManagerCompat.notify(1,mBuilder.build());
}
}
Related
This is my receiver class
public class LocationAlarmReceiver extends BroadcastReceiver {
private static final String TAG = "LocationAlarmReceiver";
#Override
public void onReceive(Context context, Intent intent) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (AppClass.networkConnectivity.isNetworkAvailable()) {
if (AppClass.isUserLoggedIn()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, UpdateLatLngBackgroundService.class));
} else {
context.startService(new Intent(context, UpdateLatLngBackgroundService.class));
}
}
}
}
}
}
Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification:
Exception is coming
If you are starting a background service as by using startForegroundService
it will be consider as a Foreground service. For Foreground service you have to create a notification to display. see for more detiails
And while creating notification from oreo(8.0) onwards you have to create a channel and register with NotificationManager. More details how to create notification channel
make sure that you added attribute -> name=".the name of the class that you created channels in"
inside tag in manifest file.
I have an app that get notification from signal R.In foreground I dont have problem and it works.When the app is in background I want to have background service that always listen to signal R notification.(Signal R notifications fail if the user is offline). Packages in react native dont do it .I try with Headless but it does not work properly.
This is my service.
enter code here public class Service extends HeadlessJsTaskService {
#Nullable
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"service",
Arguments.fromBundle(extras),
5000);
}
return null;
}
}
And in MainApplication inside create method i call it.
enter code here Intent serviceIntent = new Intent(context, com.Myservice.Service.class);
serviceIntent.putExtra("hasInternet", hasInternet);
context.startService(serviceIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
Hey i want when user is trying to un-install an app ,there comes password to unlock. Im following this code :
android: require password when uninstall app
but there comes an error in manifest "android:description="#string/descript""
Kindly help me.im badly stuck in it.there's no answer availble on google too
it would not help on 4.3 or higher but I am posting a link where you can find the solution and reason of why you can not do it.
Here is the link. Hope it would help you in understanding the real milestone in this context.
try the following code in your service
public static final String UNINSTALLER ="com.android.packageinstaller.UninstallerActivity";
private ActivityManager activityManager = null;
private ExecutorService executorService;
#Override
public void onCreate() {
super.onCreate();
executorService = Executors.newSingleThreadExecutor();
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
LockerThread thread = new LockerThread();
executorService.submit(thread);
}
private void protactApp(String packname) {
Intent pwdIntent = null;
pwdIntent = new Intent("uninstaller.receiver");
sendBroadcast(pwdIntent);
}
class LockerThread implements Runnable {
private String lastname;
public LockerThread() {
}
#Override
public void run() {
ComponentName act = activityManager.getRunningTasks(1).get(0).topActivity;
String packname = act.getPackageName();
if (act.getClassName().equals(UNINSTALLER)) {
Log.d("Tag", "package to be uninstalled");
protactApp(UNINSTALLER);
}
}
and from receiver you can get action while uninstall the app so whatever screen you prepare for password or pattern that you can start before uninstall like applock application
I'm making kind-of an audio player. Currently I have a MediaPlayer running in the Activity itself (which I know is bad). There is a SeekBar on the screen which gets updated as the music plays, like so:
private Runnable mUpdateTimeTask = new Runnable() {
public void run()
{
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
songTotalDurationLabel.setText("" + utils.millisecondsToTimer(totalDuration));
songCurrentDurationLabel.setText("" + utils.millisecondsToTimer(currentDuration));
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
songProgressBar.setProgress(progress);
if(mp.isPlaying())
mHandler.postDelayed(this, 100);
else
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
Once the user presses the back button or kills it from the recent apps list, the music stops.
Now I want the music to run in the background, so looking around the internet I found to run it in a Service, and calling startService() from Activity. Also I have a notification come up when music is playing and removed when it is paused.
I understand from a service I'll get the music to play even when app gets closed. But what I didn't understand is, if the user taps on the notification given the service is running, the activity restarts with the SeekBar at progress = 0.
How do I get the UI to update the SeekBar to the correct value from the Service after the activity restarts?
Figured it out!
The solution is to get the running services using the ActivityManager and find your service like this
private boolean fooRunning()
{
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if("com.name.packagename.foo".equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
If this method returns true, bind to the service and get the current position from the MediaPlayer object
public void bindToService()
{
if(fooRunning())
{
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
serviceExists = true;
}
else
serviceExists = false;
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder serviceBinder)
{
bar binder = (bar) serviceBinder;
mService = binder.getService();
if(serviceExists)
{
int getProgress = mService.mp.getCurrentPosition();
// mp is the MediaPlayer object in the service
seekbar.setProgress(getProgress);
}
}
#Override
public void onServiceDisconnected(ComponentName className)
{
}
};
The Service class is like this:
public class foo extends Service
{
private MediaPlayer mp = new MediaPlayer();
private final IBinder mBinder = new bar();
public class bar extends Binder
{
public foo getService()
{
return foo.this;
}
}
#Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
}
Hope this helps someone!
I am having problem with GCM, it works just fine on Nexus 7 but when I run it on any device with Gingerbread version onRegistered method is never called.
See my code implementation belowe:
GMCIntentService
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
private RestHelper restRegisterGCM;
private String userRegisterGCMUrl = "User/SetGcm";
public GCMIntentService() {
super(AppSettings.SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
// Util.displayMessage(context, "Your device registred with GCM");
if (!GCMRegistrar.isRegisteredOnServer(this)) {
restRegisterGCM = new RestHelper(userRegisterGCMUrl, RequestMethod.POST, context);
restRegisterGCM.setHeader("UserName", AppSettings.getInstance().getUsername(context));
restRegisterGCM.setHeader("Password", AppSettings.getInstance().getPassword(context));
restRegisterGCM.setParameter("regId", registrationId);
restRegisterGCM.execute();
}
}
/**
* Method called on device un registred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
}
/**
* Method called on Receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("Message");
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
Toast.makeText(context, getString(R.string.gcm_error, errorId), Toast.LENGTH_SHORT).show();
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
Toast.makeText(context, getString(R.string.gcm_recoverable_error, errorId), Toast.LENGTH_SHORT).show();
return super.onRecoverableError(context, errorId);
}
GMC registration method
private void registerGCM() {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
Boolean accountExists = false;
AccountManager am = AccountManager.get(getApplicationContext());
Account[] accounts = am.getAccounts();
for (Account account : accounts) {
if (account.type.equals("com.google")) {
accountExists = true;
break;
}
}
if (accountExists) {
// Get GCM registration id
String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, AppSettings.SENDER_ID);
} else {
// Device is already registered on GCM
if (!GCMRegistrar.isRegisteredOnServer(this)) {
restRegisterGCM = new RestHelper(userRegisterGCMUrl, RequestMethod.POST, EvadoFilipActivity.this);
restRegisterGCM.setHeader("UserName", AppSettings.getInstance().getUsername(EvadoFilipActivity.this));
restRegisterGCM.setHeader("Password", AppSettings.getInstance().getPassword(EvadoFilipActivity.this));
restRegisterGCM.setParameter("regId", regId);
restRegisterGCM.setPostExecuteMethod(2);
restRegisterGCM.execute();
}
}
} else
Toast.makeText(this, R.string.gcm_google_account_missing, Toast.LENGTH_SHORT).show();
}
UPDATE:
I have renamed packages and forget to change it in my class:
public class GCMBroadcastReceiver extends com.google.android.gcm.GCMBroadcastReceiver{
#Override
protected String getGCMIntentServiceClassName(Context context) {
return "com.mypackage.services.GCMIntentService";
}
}
I had the very same problem.My code would work on nexus4(Kitkat) but would fail to get me a notification from the appln server(via gcm server).#Fr0g is correct for versions less that 4.0.4 you should make sure that you have your google account setup on your device for gcm to work.
I had google account on my galaxy ace(2.3.4) but the mistake I made was that my Account and Sync settings in my galaxy ace was 'Off'.When I turned it ON and ran my code, i received the notification.
Ensure that you have set up a user account on the device that you are testing on. GCM requires that a google account must be setup on the device that is registering for GCM, (also I think that this requirements is for android versions < 4.0)