i want to show firebase push notification(sending firebase console) in activity's snackbar by broadcast receiver which i get from FirebaseMessagingService but i am unable to show.please help me.
Manifest:
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
firebase message service:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getData().size()>0){
Log.v("Message data", remoteMessage.getData().toString());
}
if(remoteMessage.getNotification()!=null){
Log.v("MessageNotification", remoteMessage.getNotification().getBody().toString());
}
if(remoteMessage!=null){
sendNotification(remoteMessage.toString());
}
}
private void sendNotification(String messageBody){
Intent intent=new Intent(this,NotificationShowActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("FireBaseNotification",messageBody);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.notification_icon)
.setContentTitle("Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
notificationShow Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_show);
linearLayout=(RelativeLayout)findViewById(R.id.activity_notification_show);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(MyFirebaseMessagingService.NOTIFICATION_SERVICE));
}
//broadcastReceiver
private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("FireBaseNotification");
if(message!=null){
Toast.makeText(NotificationShowActivity.this,message,Toast.LENGTH_LONG).show();
}
}
};
}
To catch FCM messages in background your should use receiver, not service.
public class NotificationsReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//handle your data
abortBroadcast(); //stop sending this broadcast to other receivers.
}
}
In your manifest (important - set priority to 999, to be first in receivers queue):
<receiver
android:name=".fcm.NotificationsReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter android:priority="999">
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
Related
In Android Oreo, I'm trying to schedule notifications at known future times. I wrote a small piece of code to test if I can schedule a notification in an hour when the app might be closed. When I try to do this, nothing happens. I really appreciate the help.
public class MainActivity extends AppCompatActivity {
private NotificationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NotificationChannel notificationChannel = new NotificationChannel("default",
"primary", NotificationManager.IMPORTANCE_DEFAULT);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
Intent notifyIntent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
long milisInFuture = 1000 * 60 * 60;
alarmManager.set(AlarmManager.RTC_WAKEUP, milisInFuture, pendingIntent);
}
public class MyNewIntentService extends JobIntentService {
#Override
protected void onHandleWork(#NonNull Intent intent) {
Notification notification = new Notification.Builder(getApplicationContext(), "default")
.setContentTitle("title")
.setContentText("body")
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setAutoCancel(true)
.build();
manager.notify(123, notification);
}
}
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
}
}
Here is the manifest if that helps.
<?xml version="1.0" encoding="utf-8"?>
<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>
<service
android:name=".MainActivity$MyNewIntentService"
android:permission="android.permission.BIND_JOB_SERVICE"></service>
</application>
</manifest>
UPDATE:
Don't forget to add the receiver in the manifest xml file.
For this question:
Add in AndroidManifest.xml inside application tag:
<receiver android:name=".MyReceiver" />
Example:
I am keeping this example, it updates the notification from Broadcast Receiver class.
Create a broadcast receiver class as shown, (Don't forget to add the receiver in the manifest xml file)
public class NotificationUpdate extends BroadcastReceiver {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
//NEED A RESCHEDULE?
updateNotification(context);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void updateNotification(Context context){
Notification notification = new Notification.Builder(context.getApplicationContext(), "default")
.setContentTitle("title")
.setContentText("body")
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setAutoCancel(true)
.build();
NotificationManager manager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
if(manager!=null) manager.notify(123, notification);
}
}
Example Call from an Activity:
public class MainActivity extends AppCompatActivity {
final long intervalPeriod=60*1000;
AlarmManager mAlarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NotificationChannel notificationChannel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel("default",
"primary", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) manager.createNotificationChannel(notificationChannel);
mAlarmManager=(AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE);
PendingIntent intent=PendingIntent.getBroadcast(getApplicationContext(),1234,
new Intent(getApplicationContext(),NotificationUpdate.class),0);
mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+intervalPeriod, intent);
}
}
I'm New in Android.
When the application is open and notification came from firebase and click the notification then it open the Notification Activity but when the application is in foreground/background and notification came and click the notification then it automatically open the mainActivity.
I'm broadcasting the data from FirebaseMessagingService.class to Main Activity.
Why?
My code is below.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager.getInstance(this)
.registerReceiver(mHandler,new IntentFilter("Pakage_name_FCM-MESSAGE"));
}
private BroadcastReceiver mHandler = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String title = intent.getStringExtra("title");
String message = intent.getStringExtra("message");
Log.d("MainActivity-title",title);
Log.d("MainActivity-message",message);
}
};
#Override
protected void onPause() {
super.onPause();
// Unregister the Broadcast receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
}
}
FirebaseNotificationIdService.Class
public class FirebaseNotificationIdService extends FirebaseInstanceIdService {
private static final String REG_TOKEN = "REG_TOKEN";
#Override // each time a new created and system call this method
public void onTokenRefresh() {
String recent_token= FirebaseInstanceId.getInstance().getToken();
Log.d(REG_TOKEN,recent_token);
}
}
FirebaseMessagingService.class
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Remote Form",remoteMessage.getFrom());
// check if the message contains data...
if (remoteMessage.getData().size()> 0){
Log.d("Message Data", "Message Data---"+remoteMessage.getData() );
String title=remoteMessage.getData().get("title");
String message=remoteMessage.getData().get("message");
Intent intent = new Intent("package_name_FCM-MESSAGE");
intent.putExtra("title",title);
intent.putExtra("message",message);
Log.d("INTENT-TITLE",title);
Log.d("INTENT-MESSAGE",message);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
//check if the message contain notification
if (remoteMessage.getNotification()!=null){
Log.d("Message Body","---"+remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
//Display the notification
private void sendNotification(String body) {
Intent intent = new Intent(this,NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0/*Request code*/,intent,PendingIntent.FLAG_ONE_SHOT);
//Set sound
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this);
notifiBuilder.setSmallIcon(R.mipmap.ic_launcher);
notifiBuilder.setContentTitle("Aadhaar Update");
notifiBuilder.setContentText(body);
notifiBuilder.setAutoCancel(true);
notifiBuilder.setSound(notificationSound);
notifiBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0/*Id of Notification*/,notifiBuilder.build());
}
}
Minifest.xml
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirebaseNotificationIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".NotificationActivity"></activity>
You should use implementation of WakefulBroadcastReceiver instead of FirebaseMessagingService
public class NotificationsReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//process data from intent
abortBroadcast();
}
}
In your manifest
<receiver
android:name=".fcm.NotificationsReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter android:priority="999">
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
I am new android I want to implement in my that when I press power button I need to open the app but the app is killed in the background from recent app tray. I am trying all the solutions which I got but I didnt get solution
MainActivity.class
public class MainActivity extends ActionBarActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
/*Toast.makeText(getApplicationContext(),"main Activity run",Toast.LENGTH_SHORT).show();
intent = new Intent(new Intent(getBaseContext(), PowerService.class));
startService(intent);*/
// /* new Handler().post(new Runnable() {
// #Override
// public void run() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
// }
// });
//*/
// Intent notificationIntent = new Intent(this, PowerService.class);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//
//
//
}
#Override
protected void onStart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onStart",Toast.LENGTH_SHORT).show();
super.onStart();
}
#Override
protected void onResume() {
Toast.makeText(getApplicationContext(),"inside mainactivity onResume",Toast.LENGTH_SHORT).show();
super.onResume();
}
#Override
protected void onRestart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onRestart",Toast.LENGTH_SHORT).show();
super.onRestart();
}
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(),"inside mainactivity onDestroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
Toast.makeText(getApplicationContext(),"inside mainactivity onStop",Toast.LENGTH_SHORT).show();
super.onStop();
}
}
Service.class
public class PowerService extends Service {
BroadcastReceiver mReceiver;
IntentFilter filter;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
cpuWakeLock.acquire();
registerReciver();
return Service.START_STICKY;
}
public class LocalBinder extends Binder {
PowerService getService() {
return PowerService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
System.out.println("inside powerservice onUnbind");
Toast.makeText(getApplicationContext(),"inside powerservice onUnbind",Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
System.out.println("inside powerservice onRebind");
Toast.makeText(getApplicationContext(),"inside powerservice onRebind",Toast.LENGTH_SHORT).show();
super.onRebind(intent);
}
#Override
public void onStart(Intent intent, int startId) {
System.out.println("inside powerservice onStart");
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
//unregisterReceiver(mReceiver);
//registerReciver();
System.out.println("inside powerservice onDestroy");
Toast.makeText(getApplicationContext(),"inside powerservice ondestroy",Toast.LENGTH_SHORT).show();
startService(new Intent(this, PowerService.class));
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/*registerReciver();
startService(new Intent(this,PowerService.class));*/
Toast.makeText(getApplicationContext(),"inside powerservice onTaskRemoved",Toast.LENGTH_SHORT).show();
/*Intent broadcastIntent = new Intent(this,AppReciever.class);
sendBroadcast(broadcastIntent);
super.onTaskRemoved(rootIntent);*/
/* Intent restartServiceTask = new Intent(this,PowerService.class);
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
startService(new Intent(this,PowerService.class));*/
super.onTaskRemoved(rootIntent);
}
public void registerReciver()
{
filter= new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_LOCKED_BOOT_COMPLETED);
mReceiver = new AppReciever();
registerReceiver(mReceiver, filter);
}
}
BroadcastReciever
public class AppReciever extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
Toast.makeText(context,"inside ACTION_SCREEN_OFF",Toast.LENGTH_SHORT).show();
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ", "shutdown now");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.e("Screen ", "awaked now");
Toast.makeText(context,"inside ACTION_SCREEN_ON",Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e("LOB", "userpresent");
Toast.makeText(context,"inside ACTION_USER_PRESENT",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
wasScreenOn = true;
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
else if(intent.getAction().equals(Intent.ACTION_LOCKED_BOOT_COMPLETED))
{
Toast.makeText(context,"inside ACTION_LOCKED_BOOT_COMPLETED",Toast.LENGTH_SHORT).show();
Log.e("LOB", "userpresent");
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
}
/* Log.v("##%#%#", "Power button is pressed.");
Toast.makeText(context, "power button clicked",Toast.LENGTH_LONG).show();*/
}
}
Manifestfile
package="com.benayah.app.sampleapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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>
<service android:name=".PowerService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false"
android:process=":my_process"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</service>
</application>
Please let me know where I am going wrong in my code and I need to run the service in background to check for the screen on even after the app is killed in background because now when I killed app I couldn't restart my app but if I didn't kill the it is working fine
Use following might be helpfull...
***in Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent= new Intent(context, ActivitySample.class);
context.startActivity(intent);
}
}
You below might be helpfull...
In Manifest
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
public class MyReceiver extends BroadcastReceiver {
static int countPowerOff=0;
private Activity activity=null;
public MyReceiver (Activity activity)
{
this.activity=activity;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
if(countPowerOff==5)
{
Intent i =new Intent(activity,NewActivity.class);
activity.startActivity(i);
}
}
}
And,
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
MyReceiver mReceiver = new MyReceiver (this);
registerReceiver(mReceiver, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The only way i know to monitor the power button is by listening to the ScreenOn and ScreenOff events. So you can try to write a service that is listening to ScreenOn or ScreenOff and then each time that this event is firing you can launch the desired app.
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ScreenOnOffService.class);
startService(intent);
}
}
Service:
public class ScreenOnOffService extends Service {
private ScreenOnOffReceiver mScreenReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
registerScreenStatusReceiver();
}
#Override
public void onDestroy() {
unregisterScreenStatusReceiver();
}
private void registerScreenStatusReceiver() {
mScreenReceiver = new ScreenOnOffReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(mScreenReceiver, filter);
}
private void unregisterScreenStatusReceiver() {
try {
if (mScreenReceiver != null) {
unregisterReceiver(mScreenReceiver);
}
} catch (IllegalArgumentException e) {}
}
}
Manifest:
<service android:name="com.benayah.app.sampleapp.ScreenOnOffService" />
BroadcastReceiver:
(here you need to put the package name of the app that you want to launch)
in my example i put your package name: com.benayah.app.sampleapp
public class ScreenOnOffReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("StackOverflow", "Screen Off");
startApp(context);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("StackOverflow", "Screen On");
startApp(context);
}
}
private void startApp(Context context) {
PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.benayah.app.sampleapp");
context.startActivity(launchIntent);
}
}
I am using the following code to start a service periodically whether the app is foreground or not .
Intent getAlertIntent = new Intent(getApplicationContext(), GetAlertAlarmReceiver.class);
PendingIntent getAlertpendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, getAlertIntent, 0);
AlarmManager getAlertmanager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
getAlertmanager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, getAlertpendingIntent);
The code for my receiver is following
public class GetAlertAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, GetAlertServiceIntent.class);
context.startService(i);
}
}
And and service
public class GetAlertServiceIntent extends IntentService {
public GetAlertServiceIntent() {
super("GetAlertServiceIntent");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
doSomething();
}
}
In my manifest file I declared everything as following
<receiver
android:name=".broadcastreceiver.GetAlertAlarmReceiver"
android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="com.surroundapps.shotorkoporibar.services.GetAlertServiceIntent" />
This code work as expected in API level below Marshmallow but in marshmallow it doesn't work .
I'm very new to Android Wear (development). I started reading and implementing the documentation.
However I'm not sure if what I want to implement is "überhaupt" possible.
I can attach custom "actions" on the push notifications I receive, but it seems it can only open a phone-activity. Why can't I open a wear-activity?
The push notifications contains text, which is initially displayed, and data about a soccer match (second page?). I want to display the names of the teams and the score without an intervention of the phone.
So is it possible?
Plus what is the default behaviour? Do I attach this to an action or via an extra page on the notification?
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification_icon3)
.setContentTitle(this.getString(R.string.notifications_title))
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(matchDetailPendingIntent)
.setAutoCancel(true)
.extend(new NotificationCompat.WearableExtender()
.addPage(CustomDesignedPage) //Is this possible?
.addAction(action)
.setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.soccer_background_big))
);
EDIT
Looking at the Messenger wear-app it seems possible?
The second screen shows a list of messages for example.
I was having the same problem. My solution was to implement an Activity and add to this activity the custom layout. Follow this step.
Step 1: Create a custom layout in your wear module. Example: customlayout.xml
Step 2: Create an Activity in the wear module:
public class WearNotificationActivity extends Activity{
private ImageView mSomeButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customlayout);
mSomeButton= (ImageView) this.findViewById(R.id.somebutton);
mSomeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do something here
}
});
}
}
Step 3. Send the data you want from your phone to your wear:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
private Button mSomeButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
mSomeButton=(Button) findViewById(R.id.somebutton);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(AppIndex.APP_INDEX_API)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mSomeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendToWear("title","description");
}
});
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
if(!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(mGoogleApiClient!=null) {
mGoogleApiClient.disconnect();
}
}
public void sendToWear(String title, String description){
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/wear");
putDataMapReq.getDataMap().putString("title", title);
putDataMapReq.getDataMap().putString("description", description);
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
}
}
Step 4. Receive the data in your wear and make the notification. For do this you have to create a class in the wear module that extends for WearableListenerService and add this class to your wear manifest.
public class NotificationUpdateService extends WearableListenerService
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
ResultCallback<DataApi.DeleteDataItemsResult> {
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent dataEvent : dataEvents) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = dataEvent.getDataItem();
if (item.getUri().getPath().compareTo("/wear") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
String title = dataMap.getString("title");
String description=dataMap.getString("description");
buildWearableOnlyNotification(title, description)
}
} else if (dataEvent.getType() == DataEvent.TYPE_DELETED) {
}
}
}
/**
* Builds a simple notification on the wearable.
*/
private void buildWearableOnlyNotification(String title, String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVibrate(new long[]{10, 10, 10, 10, 10})
.setContentTitle(title)
.setContentText(content);
Intent notificationIntent = new Intent(this, WearNotificationActivity.class);
PendingIntent pendingNotificationIntent =
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder secondpage =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.extend(new NotificationCompat.WearableExtender()
.setDisplayIntent(pendingNotificationIntent)
.setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_FULL_SCREEN)
);
mNotificationBuilder = new NotificationCompat.WearableExtender()
.addPage(secondpage.build()).extend(builder);
Notification notification=mNotificationBuilder.build();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.notify(Constants.WATCH_ONLY_ID, notification);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
And in your manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<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=".WearNotificationActivity"
android:exported="true"
android:allowEmbedded="true"
android:taskAffinity=""
android:theme="#android:style/Theme.DeviceDefault.Light"
>
</activity>
<service android:name=".NotificationUpdateService">
<intent-filter>
<action
android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
</application>
Finally you need to add all the dependencies in your phone and wear gradle.
Phone:
compile 'com.google.android.gms:play-services-wearable:7.5.0'
compile 'com.android.support:support-v4:23.1.0'
wearApp project(':wearmodule')
Wear:
compile 'com.google.android.support:wearable:1.3.0'
provided 'com.google.android.wearable:wearable:+'
compile 'com.google.android.gms:play-services-wearable:8.1.0'
I hope this was useful to you.