android studio do a socket connection when screen is unlock?(java) - java

I want that each time that the user unlock his phone my app automatically do a socket connection in background to see if the user had receive a message, and if yes show a notification.
the code to do a socket connection and do a notification works in the MainActivity class but I could find out to make that the android device execute the code in the UserPresentBroadcastReceiver class automatically even if the app has not been open.
android 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.notification">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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/Theme.Notification">
<receiver android:name=".UserPresentBroadcastReceiver" >
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<!--For HTC devices-->
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service android:name="UserPresentBroadcastReceiver" >
</service>
<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>
</application>
</manifest>
and the UserPresentBroadcastReceiver class
package com.example.notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class UserPresentBroadcastReceiver extends BroadcastReceiver {
private Socket client;
private PrintWriter printwriter;
private String message_sortant;
private BufferedReader in_bufferedReader;
private String message_entrant;
private InputStreamReader in_streamReader;
#Override
public void onReceive(Context arg0, Intent intent) {
/*Sent when the user is present after
* device wakes up (e.g when the keyguard is gone)
* */
if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
while(true) {
try {
//Log.d("Connexion","Demande de connexion");
Socket client = new Socket("192.168.1.13", 1580);// connect to the server
////// ENVOIE D'UN MESSAGE SORTANT ///////
Log.d("Connexion", "Envoie de A");
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write("<meet>/notification/"); // write the message to output stream
printwriter.flush();
in_bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
message_entrant = in_bufferedReader.readLine();
client.close();
} catch (Exception e) {
}
NotificationManager mNotificationManager =
(NotificationManager) arg0.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DESCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(arg0.getApplicationContext(), "YOUR_CHANNEL_ID")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle("hello") // title for notification
.setContentText(String.valueOf(message_entrant))// message for notification
.setAutoCancel(true); // clear notification after click
intent = new Intent(arg0.getApplicationContext(), MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(arg0, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(0, mBuilder.build());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*Device is shutting down. This is broadcast when the device
* is being shut down (completely turned off, not sleeping)
* */
else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
}
}
}
Thanks for helping.
I notice that they change something with android Oreo but I couldn't find out how to fix it.

Related

Autostart flutter app on BOOT_COMPLETED for flutter application based on Android 10

I have a problem in my flutter app. I want to start my app on startup for android.
I use the codes, It is working very good on Android 8 and Android 9 but It is not working on Android 10
my receiver class
Ho do I have do
package com.arge24.assistant24_mobile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.util.Log;
import android.widget.Toast;
import android.content.pm.PackageManager;
import android.net.Uri;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import com.arge24.assistant24_mobile.MainActivity;
public class BootCompleteReceiver extends BroadcastReceiver {
private static final String TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message = "Service will be start. Please wait ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);
if (Intent.ACTION_BOOT_COMPLETED.equalsIgnoreCase(intent.getAction())) {
startServiceByAlarm(context);
}
}
private void startServiceByAlarm(Context context) {
// Get alarm manager.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Create intent to invoke the background service.
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
long intervalTime = 600 * 1000;
String message = "app activied... ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
// Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// Create repeat alarm.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
}
}
I used this codes in BootCompleteReceiver class but my problem did not change
Intent thisIntent = new Intent(context, MainActivity.class);
thisIntent.setAction("android.intent.action.MAIN");
thisIntent.addCategory("android.intent.category.LAUNCHER");
thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(thisIntent);
My manifest file like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.arge24.assistant24_mobile">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" tools:ignore="ProtectedPermissions" />
<application android:name="io.flutter.app.FlutterApplication" android:label="Assistant 24" android:allowBackup="false" android:icon="#mipmap/ic_launcher" android:roundIcon="#mipmap/ic_launcher_round" android:usesCleartextTraffic="true">
<activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="#style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" android:showWhenLocked="true" android:turnScreenOn="true">
<meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="#style/NormalTheme" />
<meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="#drawable/launch_background" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="BootCompleteReceiver" android:enabled="true" android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.REBOOT" />
</intent-filter>
</receiver>
</application>
</manifest>

Listen for Time Zone Changes Even When the App is Closed

I am trying to listen for timezone changes even when my Android app is closed.
What I tried:
I found a intent action for it. It is TIME_ZONE_CHANGED. However it
is a protected intent that can only sent by system as the
documentation says and also it probably doesn't allow to make it
implicit broadcast.
I tried AlarmManager, but I couldn't find exact timezone change
events.
I used schedululeAtFixedRate in a thread in an app service. It worked perfectly.
But I don't want it to listen to every hour changes, I want only time zone timezone changes, as I mentioned above.
Edit:
MainActivity
public static final String CHANNEL_ID = "49";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
startService(new Intent(this,AppService.class));
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence c_name = getString(R.string.notification_channel_name);
String c_desc = getString(R.string.notification_channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,c_name,importance);
notificationChannel.setDescription(c_desc);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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"
android:usesCleartextTraffic="true">
<receiver
android:name=".TimeChangedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter >
<action android:name="android.intent.action.TIMEZONE_CHANGED"/>
</intent-filter>
</receiver>
<service
android:name=".AppService"
android:enabled="true"
android:exported="true" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Receiver Class
package com.example.gridview;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class TimeChangedReceiver extends BroadcastReceiver {
private static int NOTIFICATION_ID = 1;
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
StringBuilder sb = new StringBuilder("Timezone is changed
YAY!,executed for "+NOTIFICATION_ID+" times.");
if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
sb.append("\n Status: Ok.");
}
NotificationCompat.Builder builder = new
NotificationCompat.Builder(context,MainActivity.CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentText(sb.toString())
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Hey!");
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(context);
notificationManager.notify(NOTIFICATION_ID,builder.build());
NOTIFICATION_ID++;
}
}
You should register a manifest receiver for "android.intent.action.TIMEZONE_CHANGED" (AKA Intent.ACTION_TIMEZONE_CHANGED). It is one of the implicit broadcast exceptions that is not subject to the restrictions on registering manifest receivers in Android 8.0+.
A manifest receiver like this is going to be the only way to detect this type of event when your app is not running.

Why my android-notification doesn't appear?

i create an android notification with a compiled sdk version of 28 with min sdk version of 26, i actually developing android that need a notification so 1st i create an android notification separated from my FirstApplication, it works fine but when i add this notification in my FirstApplication the notification doesn't appear.
App.java
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
MainActivity.java
import android.app.Notification;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import static com.project.cms.App.CHANNEL_1_ID;
import static com.project.cms.App.CHANNEL_2_ID;
public class MainActivity extends AppCompatActivity {
private NotificationManagerCompat notificationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
notificationManager = NotificationManagerCompat.from(this);
sendchannel()
sendchannel2()
}
public void sendchannel(){
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle("Appointment Request")
.setContentText("ACCEPTED")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
public void sendchannel2(){
Notification notification = new NotificationCompat.Builder(this, CHANNEL_2_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle("Appointment Request")
.setContentText("DECLINED")
.setPriority(NotificationCompat.PRIORITY_LOW)
.build();
notificationManager.notify(2, notification);
}
}
when i open the app, the notification should appear but it doesn't work. So im asking you guys to help me and check my code if im missing something or what.
look at this what i am trying to say:-
In your application tag add
name="App" which is your class name of creating channels and also extends the Application class
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<application
android:name=".notification"
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>
<activity android:name=".Main2Activity" />
<activity android:name=".Main3Activity"/>
<service android:name=".MyService"
android:enabled="true"/>
<service android:name=".Service"
android:enabled="true"/>
<provider
android:authorities="${applicationId}.provider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>

Firebase Foreground Notifications Not Showing

For some reason my Firebase notifications are not showing in the foreground. They work fine in the background however, and I followed what Anroid Studio told me to add as well as this tutorial example on github
Judging by the Run window, it is receiving the notification but not sending in foreground
Here is my service code for sending the notification
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import static android.support.constraint.Constraints.TAG;
public class FirebaseNotificationsRecieverService extends FirebaseMessagingService {
private static final String TAG = FirebaseNotificationsRecieverService.class.getName();
public FirebaseNotificationsRecieverService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
System.out.println("RECIEVED");
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: (there was a link here)
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
//scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification(remoteMessage.getNotification().getBody());
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.wlmaclogo)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starenkysoftware.macapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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"
android:usesCleartextTraffic="true">
<service
android:name=".FirebaseNotificationsRecieverService"
android:enabled="true"
android:exported="true"></service>
<service android:name="com.google.firebase.messaging.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Replace the manifest as below:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starenkysoftware.macapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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"
android:usesCleartextTraffic="true">
<service android:name=".FirebaseNotificationsRecieverService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The intent filter com.google.firebase.MESSAGING_EVENT should be placed in your service, which you are using to get the notifications.
Remember to remove the existing messaging service from the AndroidManifest.xml. If you leave the FireBaseMessagingService in the Manifest. your newly defined service doesn't get picked up.
E.g. remove the following:
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and add the following:
<service
android:name=".MyFirebaseNotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

How to check if GcmBroadcastReceiver is running?

My app was working fine and was receiving push notifications, today I added some new layout and also change some other activity. But Now the app is not receiving any push notifications. I installed the old apk and tested, and still its not receiving any Push notifications.
So, Registered the device again with new IDs, and when i checked the Gcm manifest its shows :
{"multicast_id":7626883831612562770,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1410175055111515%ae2db952f9fd7ecd"},{"message_id":"0:1410175055111884%ae2db952f9fd7ecd"}]}
Both are newly registered ID's, but its still not working.
LogCat for the App :
09-08 16:44:58.360 7151-7244/in.wirefreeworld.wfw D/111﹕ Device registered, registration ID=APA91bF3BhiliA8Xrtkh7HfUSHlpq9UrkhbAkIPY_poWjWBcAlgnIkF2Hbd38KakR43fucTxfHOcCH4zfyLEd7Q2uLRZIupMD-erk4gUoSpX2rk1YbMIDHLIZ7cFopHUdJ8ocLQM4X2hDajLml0vJVvp4M9hodKecw
09-08 16:44:58.490 7151-7172/in.wirefreeworld.wfw D/dalvikvm﹕ GC_FOR_ALLOC freed 1322K, 8% free 15664K/17016K, paused 23ms, total 25ms
09-08 16:44:58.880 7151-7151/in.wirefreeworld.wfw D/Volley﹕ [1] 4.onResponse: MainActivity
GcmBroadcastReceiver.java Class
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
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)));
setResultCode(Activity.RESULT_OK);
}
}
GCMNotificationIntentService.java
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GCMNotificationIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCMNotificationIntentService";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
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)) {
for (int i = 0; i < 3; i++) {
Log.i(TAG,
"Working... " + (i + 1) + "/5 # "
+ SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
sendNotification("New Product: "
+ extras.get(Config.MESSAGE_KEY));
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_notif);
mBuilder.setTicker("Wire Free World");
mBuilder.setContentTitle("Wire Free World");
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg));
mBuilder.setContentText(msg);
long[] pattern = {500,500,500,500,500,500,500,500,500};
mBuilder.setVibrate(pattern);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
mBuilder.setSound(alarmSound);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wl.acquire(5000);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.listviewfeed"
android:versionCode="3"
android:versionName="1.2" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<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="info.androidhive.listviewfeed.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="info.androidhive.listviewfeed.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name=".app.AppController"
android:allowBackup="true"
android:icon="#drawable/ic_notif"
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=".product"
android:label="#string/title_activity_product"
android:parentActivityName=".MainActivity" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".Register"
android:label="#string/title_activity_register"
android:theme="#style/Theme.AppCompat">
</activity>
<receiver
android:name=".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="info.androidhive.listviewfeed" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService" />
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</manifest>

Categories

Resources