I have looked at several questions on this site and none seem to be able to answer my question so hopefully someone can help with this. Currently for some reason when I send a message through from the PHP Website, my app doesn't receive the message. I have tried placing Log.d's in the lines of code but it doesn't appear as well. Can someone help to see if something has gone wrong?
[UPDATE] This is the result when I send from the php website
{"multicast_id":5610818169388245295,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1460536959734990%40ad5721f9fd7ecd"}]}
My manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.amosang.pushtest" >
<!-- GCM Permissions - Start here -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/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>
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" >
</activity>
</application>
<receiver
android:name=".GCMBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.amosang.pushtest" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService">
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</service>
</manifest>
My Broadcast Receiver
public class GCMBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
Log.d("TESTTEST", "TEST");
setResultCode(Activity.RESULT_OK);
}
}
My intent service
public class GCMNotificationIntentService extends IntentService{
//set ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GCM Intent Service");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
Log.d("RECEIVEDMESSAGE", messageType);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification("Message Received from Google GCM Server:nn"
+ extras.get(AppConstants.MSG_KEY));
}
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg){
Intent resultIntent = new Intent(this, HomeActivity.class);
Log.d("RECEIVEDPT2",msg);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this).setContentTitle("Alert")
.setContentTitle("You've received a new message");
//Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
//Set vibration
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("You have new notifications");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
Please help.
Related
I have an app developed in java whose function is to capture the location when the app is active, background, destroyed and when the phone restarts
I already managed to capture the location when the app is active, background and destroyed but I am trying to do it when the phone reboots and create the task to capture but it says that the task was configured well but it does not execute it every 1 minute
My Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.rutas">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Rutas"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyForegroundServices"></service>
<receiver android:name=".MyBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
My Receiver
public class MyBroadcastReceiver extends BroadcastReceiver {
GPSTracker gps;
Context alarmContext;
#Override
public void onReceive(Context context, Intent intent) {
Log.e("onReceive", " Init Receive" );
alarmContext = context;
gps = new GPSTracker(context);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.e("Location", "Lat: " + latitude + "\n Long: " + longitude);
if(intent.getAction() != null){
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
Log.e("Boot Completed", "Boot Completed");
setAlarmOnBoot();
Intent serviceIntent = new Intent(context, MyForegroundServices.class);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
context.startForegroundService(serviceIntent);
}else{
context.startService(serviceIntent);
}
}
}
}
public void setAlarmOnBoot(){
Log.e("Alarm Boot", "Initialize task");
try{
AlarmManager alarm = (AlarmManager) alarmContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(alarmContext, MyBroadcastReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(alarmContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 1000*60*1, pIntent);
Log.e("Success", "Alarm has been configured successfully");
} catch (Exception ex){
Log.e("Failed Try Receiver", ex.getMessage());
}
}
}
I am testing the app on a samsung A13 with android 12
I've tried to send a notification from server to my app on my phone and I get "success" but my phone doesn't receive anything, I'm using Google Cloud Messaging
public class GCMIntentService extends GcmListenerService{
private static final String TAG = "GCMIntentService";
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "from:" + from);
Log.d(TAG, "message:" + message);
sendNotification(message);
}
private void sendNotification(String message){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("New Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission android:name="com.example.abdul_majeed.alruthea.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.abdul_majeed.alruthea.permission.C2D_MESSAGE" />
....
<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" />
<category android:name="com.example.abdul_majeed.alruthea" />
</intent-filter>
</receiver>
<service
android:name=".GCMIntentService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
================================================
The problem “... doesn't receive anything …” may have caused by the code
below:
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){... ...
This means that if your device is lower than LOLLIPOP,then you can receive anything,
and if your device is higher than LOLLIPOP,then you can’t receive anything. Please check the Android version of the phone you are using.
Hello I am working with parse push notification for android.I developed app using the following tutorial. http://www.androidhive.info/2015/06/android-push-notifications-using-parse-com/. I can able to get the notification onl in one device which is lollipop.I didin't get notification in kitkat and other devices. I didin't find the issue.
here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_new_user.testnotification" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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="com.example.android_new_user.testnotification.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.android_new_user.testnotification.permission.C2D_MESSAGE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.android_new_user.testnotification.LoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.android_new_user.testnotification.MainActivity"
android:label="#string/app_name" />
<service android:name="com.parse.PushService" />
<receiver
android:name=".CustomPushReciver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<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.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
</application>
</manifest>
and my reciver File is looks like
package com.example.android_new_user.testnotification;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.parse.ParsePushBroadcastReceiver;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Android_new_user on 11/25/2015.
*/
public class CustomPushReciver extends ParsePushBroadcastReceiver {
private final String TAG = CustomPushReciver.class.getSimpleName();
private NotificationUtils notificationUtils;
private Intent parseIntent;
public CustomPushReciver() {
super();
}
#Override
protected void onPushReceive(Context context, Intent intent) {
super.onPushReceive(context, intent);
if (intent == null)
return;
try {
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
Log.e(TAG, "Push received: " + json);
parseIntent = intent;
parsePushJson(context, json);
} catch (JSONException e) {
Log.e(TAG, "Push message json exception: " + e.getMessage());
}
}
#Override
protected void onPushDismiss(Context context, Intent intent) {
super.onPushDismiss(context, intent);
}
#Override
protected void onPushOpen(Context context, Intent intent) {
super.onPushOpen(context, intent);
}
/**
* Parses the push notification json
*
* #param context
* #param json
*/
private void parsePushJson(Context context, JSONObject json) {
try {
boolean isBackground = json.getBoolean("is_background");
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
if (!isBackground) {
Intent resultIntent = new Intent(context, MainActivity.class);
showNotificationMessage(context, title, message, resultIntent);
}
} catch (JSONException e) {
Log.e(TAG, "Push message json exception: " + e.getMessage());
}
}
private void showNotificationMessage(Context context, String title, String message, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.putExtras(parseIntent.getExtras());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, intent);
}
}
and my Application class
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
// register with parse
ParseUtils.registerParse(this);
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
}
How can I resolve this problem. Please help Thanks in adavance
Have you added the application name to your manifest file?
And also check the following code in the manifest
<permission
android:name="yourpackagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="yourpackagename.permission.C2D_MESSAGE" />
<receiver
android:name="com.parse.ParsePushBroadcastReceiver"
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="yourpackagename" />
</intent-filter>
</receiver>
I tried to register my device into GCM service.
that's worked, I get register id of my device and store that on my server.
but when I send message to my device nothing affected and device can not recive message.
Response on google at send message:
{u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8319562714448073760L, u'results': [{u'message_id': u'0:1445751667241995%f044e3acf9fd7ecd'}]}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.ac.buqaen.rc"
android:versionCode="5"
android:versionName="1.4">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.VIBRATE"/>
<permission
android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:name=".network.AppController"
android:label="#string/app_name"
android:icon="#drawable/icon"
android:theme="#style/Theme.Main"
android:allowBackup="true">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".gcm.MessageActivity"/>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="ir.ac.buqaen.rc" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
ServerUtilities.java
public final class ServerUtilities {
private static final String TAG = "GCM";
public static void register(final Context context, final String regId){
final MySharedPreferences sp = new MySharedPreferences(context);
long teacher_id = sp.sharedPreferences.getLong("teacher_id", -1);
TeacherHelper teacherHelper = new TeacherHelper(context);
teacherHelper.teacher = teacherHelper.findById(teacher_id);
Map<String, String> params = new HashMap<String, String>();
Log.d("regid", "---- regId:" + regId);
params.put("reg_id", regId);
params.put("name", teacherHelper.teacher.getStringName());
params.put("email", teacherHelper.teacher.getStringEmail());
params.put("user_id", teacherHelper.teacher.getStringUsername());
params.put("device_id", Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
CustomRequest request = new CustomRequest(context, Globals.UrlGCMRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
try {
int vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
if (data.getBoolean("status")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
sp.saveToPreferences("gcm_reg_id", regId);
GCMRegistrar.setRegisteredOnServer(context, true);
} else if (data.getString("msg").equals("already registered")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
GCMRegistrar.setRegisteredOnServer(context, true);
sp.saveToPreferences("gcm_reg_id", regId);
} else {
Log.e(TAG, "registering device failed");
}
} catch (JSONException e) {
Log.e("Response Error _ " + context.getClass().getSimpleName(), "----" + e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
/**
* Unregister this account/device pair within the server.
*/
public static void unregister(final Context context, final String regId) {
final MySharedPreferences sp = new MySharedPreferences(context);
Map<String, String> params = new HashMap<String, String>();
params.put("reg_id", regId);
CustomRequest request = new CustomRequest(context, Globals.UrlGCMUnRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
if (data.getBoolean("status")) {
int vc = 1;
try {
vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
sp.editor.remove("gcm" + vc);
sp.editor.remove("gcm_reg_id");
sp.editor.commit();
GCMRegistrar.setRegisteredOnServer(context, false);
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(Globals.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
ServerUtilities.register(context, registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
ServerUtilities.unregister(context, registrationId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("tes", "~~~" + intent.getExtras());
Log.i(TAG, "Received message");
MessageHelper messageHelper = new MessageHelper(context);
try {
JSONObject data = new JSONObject(intent.getExtras().getString("message"));
messageHelper.message = new Message(
null, data.getInt("type"), data.getInt("status"), data.getString("content"),
data.getString("title"), data.getString("date")
);
messageHelper.Save();
createNotification(context, messageHelper.message);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
private void createNotification(Context context, Message message) {
Intent notificationIntent;
notificationIntent = new Intent(this, Message.class);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationIntent.putExtra("message_id", message.id);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, message.id.intValue(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.bu_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bu_logo))
.setTicker(getString(R.string.new_message))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://ir.ac.buqaen.rc/raw/notification"))
.setContentTitle(message.title)
.setContentText(message.getContentText(context));
Notification notification = builder.build();
notificationManager.notify(message.id.intValue(), notification);
}
}
MainActivity
try {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(getApplicationContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(getApplicationContext());
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(getApplicationContext());
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(getApplicationContext(), Globals.SENDER_ID);
} else {
// Try to register again if device is not registered on GCM
if (!GCMRegistrar.isRegisteredOnServer(getApplicationContext())) {
ServerUtilities.register(getApplicationContext(), regId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I dont khow why this code not worked! I use this code in another project and get messages on my app, but this code in this application on receive messages.
Can problem from my package name? :)
ir.ac.buqaen.rc
Please help me hoe to fix this problem.
According to Set up a GCM Client App on Android
For existing apps that extend a WakefulBroadcastReceiver, Google
recommends migrating to GCMReceiver and GcmListenerService. To
migrate:
In the app manifest, replace your GcmBroadcastReceiver with "com.google.android.gms.gcm.GcmReceiver", and replace the current
service declaration that extends IntentService to the new
GcmListenerService
Remove the BroadcastReceiver implementation from your client code
Refactor the current IntentService service implementation to use GcmListenerService
Then, you can refer to my following manifest file. Hope this helps!
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gcmclient" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service android:name=".service.GcmService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name=".service.LoggingService" android:exported="false" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:clearTaskOnLaunch="false"
android:finishOnTaskLaunch="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am trying to catch a bluetooth device disconnection intent filter.
I added a log to the onReceive but it never reaches it and is not displayed in the logcat.
I suspect that the problem is with my manifest.xml configuration:
manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.company.MyReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
<action android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
</intent-filter>
</receiver>
<activity
android:name=".BTActivity"
android:label="BTActivity" >
</activity>
</application>
</manifest>
MyReceiver extends BroadcastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
Log.i("got-in", "got-in-");
// String action = intent.getAction();
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("disconnect", device.getName());
Intent i = new Intent(context, BTActivity.class);
Bundle b = new Bundle();
b.putString("deviceName", device.getName());
intent.putExtras(b); // Put your id to your next Intent
context.startActivity(i);
// finish();
}
Use this code for receiving a disconnect (when Bluetooth is still turned on):
<intent-filter> <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
Also you have to register a service that then registers a broadcast receiver for Bluetooth status change, so your app knows when Bluetooth was turned off and therefore discards all active devices, as you won't receive a ACL_DISCONNECT when Bluetooth is simply turned off.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothTurnedOnOff, filter);
return START_STICKY;
}
private final BroadcastReceiver bluetoothTurnedOnOff = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
[...]
For new users. it will works . Your manifest file looks
<receiver android:name="(package name).BluetoothReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
</receiver>
and your receiver will look like
else if (intent.getAction().equals(`enter code here`
BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
// connection lost
Try removing the <category .../> from the intent-filter and try again.
Try android.bluetooth.device.action.ACL_DISCONNECTED action in intent filter. It should solve your problem.