I am using parse push notification for my app , the notification comes fine but on clicking the notification I need to show them in a list view , I searched for tutorials but I could not find any . Please help me . Please explain with code , I am new to android . Thanks in advance.
here is my custom receiver.
public class CustomReciever extends BroadcastReceiver {
NotificationCompat.Builder mBuilder;
Intent resultIntent;
int mNotificationId = 001;
Uri notifySound;
String alert;
#Override
public void onReceive(Context context, Intent intent) {
try{
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
alert = json.getString("alert").toString();
}catch (JSONException e){
}
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(alert));
mBuilder.setPriority(Notification.PRIORITY_HIGH);
mBuilder.setSmallIcon(R.drawable.syncytium);
mBuilder.setContentText(alert);
mBuilder.setContentTitle("Syncytium");
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setAutoCancel(true);
resultIntent = new Intent(context, com.omc.sunny.syncytium.syncytium.Notification.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(context,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId,mBuilder.build());
}
}
here is my Notification class
public class Notification extends AppCompatActivity {
TextView notifTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
notifTv = (TextView)findViewById(R.id.notif);
}
#Override
protected void onNewIntent(Intent intent) {
String message = getIntent().getExtras().getString("alert");
notifTv.setText(message);
}
}
At first add this to your manifest
-->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="YOURPACKAJE.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="YOURPACKAJE.permission.C2D_MESSAGE" />
add it to application tag
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name="YOURPACKAJE.notifications.MyReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="YOURPACKAJE" />
</intent-filter>
</receiver>
then create class in packaje YOURPACKAJE.notifications.MyReceiver
import java.util.List;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.TextView;
import com.parse.ParseAnalytics;
import com.parse.ParsePushBroadcastReceiver;
public class MyReceiver extends ParsePushBroadcastReceiver {
protected void onPushReceive(Context mContext, Intent intent) {
Log.e("ParsePush", "RECIVED");
if (intent.hasExtra("com.parse.Data")){
String jsonString=intent.getExtras().getString("com.parse.Data");
Log.e("", "json " + jsonString);
JSONObject json = new JSONObject(jsonString);
String title= json.getString("title");
String message= json.getString("message");
// then call your method to create manually your custom notification with pending intent
//in intent putExtra("title",title), putExtra("message",message)
//and the after opening in Activity catch this intent
}
}
}
in wersite parse.com send notification like JSON
{"title":"your tittle is here","message":"your message"}
dont use getIntent() , use intent in method:
#Override
protected void onNewIntent(Intent intent) {
String message = intent.getExtras().getString("alert");
notifTv.setText(message);
}
Related
Right now I want to choose a specific time and send a notification to the user, but the app only sends a notification when running in the background. How can I send a notification when the application is completely closed?
This is my MainActivity.java class
package com.vortex.notification;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,4);
calendar.set(Calendar.MINUTE,48);
calendar.set(Calendar.SECOND,3);
Intent intent = new Intent(getApplicationContext(),Notification_reciver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
});
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "LemubitReminderChanel";
String description = "Chanel for Lemubit Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyLemubit", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
This is my Notification_reciver.java class
package com.vortex.notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
public class Notification_reciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repating_intent = new Intent(context,Repating_activity.class);
repating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"notifyLemubit")
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("Bildirim Başlığı")
.setContentText("Bildirim Yazısı")
.setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
}
And this my Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.vortex.notification">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Notification_reciver" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</receiver>
</application>
</manifest>
I had same issue and I solved it by changing this line
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
To this:
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,0);
And in manifest change your receiver from this
<receiver android:name=".Notification_reciver" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</receiver>
To this:
<receiver android:name=".Notification_reciver"
android:enabled="true"
android:exported="true"
android:process=":remote" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</receiver>
I implemented FCM Push Notifications. The main problem is when app is closed, notifications not arrive when this happen on device.
I tried a lot of thigs for that works; when notification sent the server response with "success", but I never received.
This is full code. Android, Manifiest and server.
Android:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.accionait.canje365.R;
import com.accionait.canje365.activities.ChatActivity;
import com.accionait.canje365.activities.HomeActivity;
import com.accionait.canje365.constants.Constants;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage);
}
private void showNotification(RemoteMessage remoteMessage) {
Uri uriDefaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_notification)
.setLargeIcon((((BitmapDrawable)getResources().getDrawable(R.mipmap.ic_notification)).getBitmap()))
.setContentTitle("TITLE")
.setContentText("MESSAGE")
.setContentInfo("0")
.setAutoCancel(true)
.setTicker("Canje365")
.setSound(uriDefaultSound);
Intent home = new Intent(this, HomeActivity.class);
home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(this, 0, home, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(intent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
}
Server:
var message = {
to: token,
data: {valor: 'test'}
};
fcm.send(message, function(err, response){
if(err) {
console.log('Error: ' + err);
}
else {
console.log('Notificacion enviada: ', response);
}
});
Manifiest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.accionait.canje365">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".sync.RunIntentService" />
<service android:name=".sync.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".sync.FirebaseIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="MY_API_KEY" />
<activity
android:name=".activities.MainActivity"
android:theme="#style/SplashScreenTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.HomeActivity"
android:label="#string/title_activity_login"
android:screenOrientation="portrait">
</activity>
</application>
</manifest>
What to do with this?
In my case I have a Huawei P8 Lite and to allow to be run on the background.
This is the link where You can to find detail abount this case.
Solution on Huawei devices
I faced the same problem. Its a problem in many phone models. I'm just writing this so that out there if anyone faces the same problem can waste a little less time searching for this problem because I wasted a lot!
Android M and above devices have battery optimization enabled by default for all apps, which usually stops the background services of our apps. We just have to ask user to disable them, if user choose not to disable them, then I'm sorry..i don't think user is really happy with your app functionality. In order to ask user to enable that--->
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (pm != null && pm.isIgnoringBatteryOptimizations(packageName))
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
}
}
startActivity(intent);
I am implementing GCM. I have registered my application on Google developer Console, enabled the GCM API services, place google-services.json in app folder, put following in manifest :
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="<my-package-name>.permission.C2D_MESSAGE" />
<application>..
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- GCM -->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="android.net.conn." />
<category android:name="<my-pakage-name>" />
</intent-filter>
</receiver>
<service
android:name=".notifications.GCMListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".notifications.InstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name=".notifications.RegistrationIntentService"
android:exported="false"></service>
</application>
App level build.gradle
apply plugin: 'com.google.gms.google-services'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.google.android.gms:play-services-gcm:8.1.0'
}
project level build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.google.gms:google-services:1.4.0-beta3'
}
Therefore my query is, I don't know what is wrong with above that I amot getting registration token. Please help me to get registration token
You need to create your own Receiver and Service and use it like this.
Receiver:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class GCMMessageReciever extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Service:
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import com.appdupe.uberforxserviceprovider.R;
import com.google.android.gcm.GCMBaseIntentService;
import com.uber.driver.MyMainFragmentActivity;
import com.uber.driver.constants.Constants;
import com.uber.driver.gcm.ServerUtilities;
import com.uber.driver.util.Utils;
public class GCMIntentService extends GCMBaseIntentService {
private NotificationManager mNotificationManager;
public GCMIntentService() {
super(Constants.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
Intent i = new Intent(Constants.PUSHNOTIFICATION);
i.putExtra(Constants.DB_PHONE_GCM_ID, registrationId);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
ServerUtilities.register(context, "name", "email", registrationId);
}
#Override
protected void onMessage(Context context, Intent intent) {
String jsonString = intent.getExtras().getString("message");
try {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Editor editor = preferences.edit();
JSONObject jsonObject = new JSONObject(jsonString);
if (jsonObject.getString("id").equals("1")) {
editor.putFloat(Constants.USER_LATTITUDE,
Float.parseFloat(jsonObject.getString("lattitude")));
editor.putFloat(Constants.USER_LOGITUDE,
Float.parseFloat(jsonObject.getString("logitude")));
editor.putString(Constants.USER_RANDOM_ID,
jsonObject.getString("random_id"));
editor.putBoolean(Constants.IS_USER_SET, true);
editor.putString(Constants.PHONE_CLIENT,
jsonObject.getString("client_contact"));
editor.putString(Constants.PHONE_OPEARTOR,
jsonObject.getString("operator_contact"));
// editor.putBoolean(Constants.IS_USER_SET, true);
editor.putString(Constants.CLIENT_NAME,
jsonObject.getString("client_name"));
sendNotification(jsonString);
} else {
editor.putBoolean(Constants.DB_IS_JOB_DONE, true);
editor.putInt(Constants.FRAGMENT_POSITION,
Constants.FRAGMENT_MAP);
editor.putString(Constants.USER_RANDOM_ID, "");
}
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
Utils.log("Received message.. " + jsonString);
Intent i = new Intent(Constants.PUSHNOTIFICATION);
i.putExtra("json", jsonString);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
}
#Override
protected void onDeletedMessages(Context context, int total) {
}
#Override
public void onError(Context context, String errorId) {
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
#Override
protected void onUnregistered(Context arg0, String arg1) {
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MyMainFragmentActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(
getResources().getString(R.string.text_uber_driver))
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText(getResources().getString(
R.string.text_job_assigned)))
.setDefaults(
Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager
.notify(Constants.NOTIFICATION_ID, mBuilder.build());
}
}
Android manifest:
<application>..
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- GCM -->
<receiver
android:name=".GCMMessageReciever"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="android.net.conn." />
<category android:name="<my-pakage-name>" />
</intent-filter>
</receiver>
<service
android:name=".GCMIntentService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".notifications.InstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name=".notifications.RegistrationIntentService"
android:exported="false"></service>
</application>
I am working with notification using Parse for Android Platform. I have successfully received the push notification.
I want a callback method to stop this notification while the application is running.
As of now I have tried to find, but I don't know if there is any call back method which will call on activity if notification comes. Please help me out!
In Manifest file add this in Application Tag.
<service android:name="com.parse.PushService" />
<receiver
android:name="yourPackageName.receiver.ParsePushBroadcast"
android:exported="false" >
<intent-filter>
<action android:name="yourPackageName.UPDATE_STATUS" />
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.OPEN" />
<action android:name="com.parse.push.intent.DELETE" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<!--
IMPORTANT: If you change the package name of this sample app,
change "com.parse.tutorials.pushnotifications" in the lines
below to match the new package name.
-->
<category android:name="yourPackageName" />
</intent-filter>
</receiver>
Add this lines above application tag in manifest file.
<permission
android:name="yourPackageName.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="yourPackageName.permission.C2D_MESSAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
Than After Create one Broadcast Receiver ParsePushBroadcast.
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.util.Log;
import com.parse.ParsePushBroadcastReceiver;
public class ParsePushBroadcast extends ParsePushBroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(final Context context, Intent intent) {
try {
String action = intent.getAction();
#SuppressWarnings("unused")
String channel = intent.getExtras().getString("com.parse.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
String title = "New alert!";
if (json.has("alert"))
title = json.getString("alert");
if (MainActivity.isActivityOpen == true) {
if (MainActivity.ACTION.equals(action))
displayAlert(context, title);
} else {
generateNotification(context, R.drawable.notification_icon, title);
}
} catch (Exception e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
#Override
protected void onPushReceive(Context context, Intent intent) {
super.onPushReceive(context, intent);
}
#SuppressWarnings("deprecation")
public static void generateNotification(Context context, int icon, String message) {
// Show the notification
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.vibrate = new long[] { 500, 500 };
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, notification);
}
private void displayAlert(Context context, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder((MainActivity) context);
builder.setTitle("Title");
builder.setMessage(title).setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
if (!alert.isShowing())
alert.show();
}
}
isActivityOpen is a static variable that I have created in Main activity. The purpose for this variable is for activity is open or not.
Important: If you have this tag in manifest Remove this tag in manifest.
<receiver android:name="com.parse.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
In your Activity class in onResume method add that.
ParsePushBroadcast parsePushBroadcast = new ParsePushBroadcast();
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(parsePushBroadcast, filter);
add this constant in Activity
public static final String ACTION = "com.parse.push.intent.RECEIVE";
I need to start an app when the [Android] phone starts.
I compiled this code, and the app doesn't crash but doesn't show me anything either!
Now I'm trying with Toast but it still isn't found.
Can someone help me?
This is the main activity:
package com.example.simplenotification;
import android.app.Activity;
import android.app.AlarmManager;
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.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int MY_NOTIFICATION_ID = 0;
private int mNotificationCount;
private final CharSequence tickerText ="this is tickerText";
private final CharSequence contentTitle="this contentTitle";
private final CharSequence contentText="this coontentText";
private Intent mNotificationIntent;
private PendingIntent mContentIntent;
RemoteViews mContentView = new RemoteViews("com.example.simplenotification.StatusBarWithCustomView", R.layout.custom_view);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotificationIntent = new Intent(getApplicationContext(),AppGet.class);
mContentIntent = PendingIntent.getActivity(getApplicationContext(), 0, mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v){
startNotification();
}
});
}
public void startNotification(){
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setTicker(tickerText)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContentTitle("titolo content")
.setContentText("content text")
.setContentIntent(intent);
NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(getApplicationContext());
mNotificationManager.notify(MY_NOTIFICATION_ID,notificationBuilder.build());
}
}
This the Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simplenotification"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
I don't know how debug the app autorun on emulator. I'm sorry
EDIT: I put in another class the reciever and changed the 'android name'
package com.example.simplenotification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent();
i.setAction("android.intent.action.MAIN");
context.startService(i);
Toast.makeText(context , "saranno 3?" , Toast.LENGTH_SHORT).show();
}
}
}
Not 100% sure, but try changing this
Toast.makeText(context , "saranno 3?" , Toast.LENGTH_SHORT).show();
into
Toast.makeText(context.getApplicationContext() , "saranno 3?" , Toast.LENGTH_SHORT).show();
Make a separate class for BootUpReceiver. And in manifest pass correct path of ur package name in android:name while defining receiver
<receiver android:name=".receivers.BootUpReceiver"
Update->
Also use this permission in your manisfest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>