Notifications won't appear - java

When I launch my app, I set the time in my activity and I wait for the notification, it doesn't appear, it doesn't work.
Here's my activity, if you find the error tell me please.. Thanks for your help :)
package app.alexdickson.com.workout1;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
ImageButton botoFlexio;
ImageButton botoAbdominals;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
int hourDefinitivaFlexio;
int minuteDefinitvaFlexio;
int hourDefinitivaAbs;
int minuteDefinitivaAbs;
PendingIntent pendingIntent1;
PendingIntent pendingIntent2;
Context context;
AlarmManager alarmManager1;
AlarmManager alarmManager2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.context = this;
botoFlexio = (ImageButton) findViewById(R.id.botoFlexio);
botoAbdominals = (ImageButton) findViewById(R.id.botoAbdominals);
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
}
private void alarmMethod1(){
Intent myIntent1 = new Intent(this, NotifyService1.class);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent1 =PendingIntent.getService(this,0,myIntent1,0);
Calendar calendari1 = Calendar.getInstance();
calendari1.set(Calendar.MINUTE, minute_x);
calendari1.set(Calendar.HOUR,hour_x);
alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP,calendari1.getTimeInMillis(),
1000 * 60 * 60 * 24, pendingIntent1);
}
private void alarmMethod2(){
Intent myIntent2 = new Intent(this, NotifyService2.class);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent2 =PendingIntent.getService(this,0,myIntent2,0);
Calendar calendari2 = Calendar.getInstance();
calendari2.set(Calendar.MINUTE,minute_x);
calendari2.set(Calendar.HOUR, hour_x);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP,calendari2.getTimeInMillis(),
1000 * 60 * 60 * 24, pendingIntent2);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.botoFlexio:
botoFlexio.setBackgroundResource(R.drawable.flexioclicat);
showDialog(DIALOG_ID);
hourDefinitivaFlexio = hour_x;
minuteDefinitvaFlexio = minute_x;
alarmMethod1();
break;
case R.id.botoAbdominals:
botoAbdominals.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
alarmMethod2();
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new TimePickerDialog(Main2Activity.this, kTimePickerListener, hour_x, minute_x, true);
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(Main2Activity.this, hour_x + ": " + minute_x, Toast.LENGTH_LONG).show();
}
};
}
Here's where the intent goes: (There are two of them but they are the same, it only changes the numbers)
package app.alexdickson.com.workout1;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
public class NotifyService1 extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onCreate(){
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager nNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),Main3Activity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new Notification.Builder(this)
.setContentTitle("Hora d'entrenar!")
.setContentText("Clica per començar entrenament de pit i braços")
.setSmallIcon(R.mipmap.logo)
.setContentIntent(pIntent)
.setSound(sound)
.build();
nNM.notify(1,mNotify);
}
}
And here's my manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:theme="#style/MyTheme">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".Main3Activity" />
<activity android:name=".Main4Activity"></activity>
</application>

You have to register NotifyService1 and NotifyService2 in AndroidManifest.xml.

Related

background service is not running at all with and without firebase

here is my manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="sam.ulf.myapplication3">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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.MyApplication3"
tools:targetApi="31">
<activity
android:name=".NotificationActivity"
android:exported="false" />
<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=".FirebaseBackgroundService"
android:exported="false"
android:process=":remote" >
<intent-filter>
<action android:name="sam.ulf.myapplication3.FirebaseBackgroundService"/>
</intent-filter>
</service>
<receiver android:name=".StartFirebaseAtBoot"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
and here is my mainactivity
package sam.ulf.myapplication3;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import java.io.Serializable;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button on,on2;
Button off,off2;
TextView distance;
DatabaseReference dref;
String status;
//FirebaseFirestore firestore;
//Button btn3 ,btn4;
TextView sens1,sens2,sens3,sens4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseApp.initializeApp(this);
// startService(new Intent(FirebaseBackgroundService.class.getName()));
startService(new Intent(this, FirebaseBackgroundService.class));
//FirebaseBackgroundService s= new FirebaseBackgroundService();
// s.addDataToDatabase();
sens1=(TextView)findViewById(R.id.sensor1);
sens2=(TextView)findViewById(R.id.sensor2);
sens3=(TextView)findViewById(R.id.sensor3);
sens4=(TextView)findViewById(R.id.sensor4);
status="";
on2=(Button)findViewById(R.id.on2);
off2=(Button)findViewById(R.id.off2);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
distance = (TextView) findViewById(R.id.distance);
dref= FirebaseDatabase.getInstance().getReference();
dref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkService();
status=dataSnapshot.child("database").getValue().toString();
distance.setText(status);
status=dataSnapshot.child("sensor1").getValue().toString();
sens1.setText(status);
status=dataSnapshot.child("sensor2").getValue().toString();
sens2.setText(status);
status=dataSnapshot.child("sensor3").getValue().toString();
sens3.setText(status);
status=dataSnapshot.child("sensor4").getValue().toString();
sens4.setText(status);
String msg="ched lheme";
//NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,"my notifcation").setSmallIcon(R.drawable.ic_msg)
// .setContentTitle("balesh che8el").setContentText(msg).setAutoCancel(true);
//Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.putExtra("message",msg);
//PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
// builder.setContentIntent(pendingIntent);
//NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// NotificationManagerCompat managerCompat =NotificationManagerCompat.from(MainActivity.this);
// managerCompat.notify(1,builder.build());
// NotificationChannel channel = new NotificationChannel("My Notifcation","My Notifcation",NotificationManager.IMPORTANCE_DEFAULT);
// NotificationManager manager =getSystemService(NotificationManager.class);
//manager.createNotificationChannel(channel);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
on.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS");
myRef.setValue("1");
}
});
on2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS2");
myRef.setValue("1");
}
});
off.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS");
myRef.setValue("0");
}
});
off2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("LED_STATUS2");
myRef.setValue("0");
}
});
}
public void checkService(){
if(isServiceRunning(getApplicationContext(),FirebaseBackgroundService.class)){
Toast.makeText(getApplicationContext(),"service is running",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(),"service is not running",Toast.LENGTH_LONG).show();
}
public boolean isServiceRunning(Context c,Class<?>serviceClass) {
ActivityManager activityManager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())) {
return true;
}
;
}
return false;
}
}
and this is my firebasebackground service class
package sam.ulf.myapplication3;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.firebase.*;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.DatabaseRegistrar;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.ktx.Firebase;
public class FirebaseBackgroundService extends Service {
private Context mContext;
private DatabaseReference data;
//private Firebase f = new firebase("https://somedemo.firebaseio-demo.com/");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference orders = database.getReference();
private ValueEventListener handler;
#Override
public IBinder onBind(Intent arg0) {
// FirebaseApp.initializeApp(this);
return null;
}
// #Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// // FirebaseApp.initializeApp(this);
// mContext=getApplicationContext();//Get the context here
// FirebaseDatabase database2 = FirebaseDatabase.getInstance();
//
// DatabaseReference orders2 = database2.getReference("test");
// orders2.setValue("kolol");
// // addDataToDatabase();
// Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
//
// new Thread(new Runnable() {
// #Override
// public void run() {
// while(true){
//
// Log.e("service","service is running");
// }
// }
// });
// // return super.onStartCommand(intent, flags, startId);
// return START_STICKY;
// }
#Override
public void onCreate() {
super.onCreate();
// FirebaseApp.initializeApp(this);
addDataToDatabase();
showToast();
Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"test", Toast.LENGTH_SHORT).show();
orders.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postNotif("ntebeh");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
handler = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot arg0) {
postNotif(arg0.getValue().toString());
Log.e("service","service eners change");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
orders.addValueEventListener(handler);
}
void postNotif(String notifString) {
Log.e("service","service is running2");
Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"test", Toast.LENGTH_SHORT).show();
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"test", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("My message")
.setContentText("Subject")
.setSmallIcon(R.drawable.ic_msg)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText("")).build();
// .addAction(R.drawable.line, "", pIntent).build();
n.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, n);
}
void showToast() {
if (mContext != null) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, "Display your message here", Toast.LENGTH_LONG).show();
}
});
}
}
public void addDataToDatabase() {
//setValue method is used to add value to RTFD
orders.setValue("kol",1
);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
}
}
and this is startfirebaseatboot class
package sam.ulf.myapplication3;
import android.content.BroadcastReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.firebase.FirebaseApp;
/**
* Start the service when the device boots.
*
* #author vikrum
*
*/
public class StartFirebaseAtBoot extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, FirebaseBackgroundService.class));
}
}
and this is build.gradle
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.10'
//classpath 'com.google.gms:google-services:4.0.1'
//classpath 'com.google.gms:google-services:4.2.0'
}
}
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.2.1' apply false
id 'com.android.library' version '7.2.1' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
i get this error 2022-06-20 03:49:18.983 1417-1417/sam.ulf.myapplication3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: sam.ulf.myapplication3:remote, PID: 1417
java.lang.RuntimeException: Unable to create service sam.ulf.myapplication3.FirebaseBackgroundService: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process sam.ulf.myapplication3:remote. Make sure to call FirebaseApp.initializeApp(Context) first.
i tried to initialize firebase in mainactivity and also tried to initialize it in service class but it didnt work , im trying to send notification when firebase data change even if the app is not running or terminated.
i know firebase has cloud function but they are not free so im trying to use background service i found this code on github https://gist.github.com/vikrum/6170193

How to fill the progress bar in the background while changing activities

I have 3 page application, in which the activities change every 10 secs (i.e., Activity1 -> Activity2 -> Activity3 -> Activity1 .......).
I have a progressbar in Activity2 which updates every 1 sec. The problem is, whenever the Activity2 is changing to Activity3 and then coming back to Activity 2 the progressbar is resetting and starting all over from zero.
I would like the progressbar to update continuously for the set time without interruptions. I tried using the services but the result is still the same.
I hope the code below helps in idenfying the issue and would really appreciate if anyone helps me out.
Activity1.java
package com.ossus.SC20;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class frame_6_activity extends Activity {
Timer timer;
private View _bg__frame_6;
private ImageView background_1;
private TextView text_view_date;
private ImageView logo_2_1;
private TextView H2Value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame_6);
startService(new Intent(frame_6_activity.this, service.class));
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
if (getIntent().getBooleanExtra("crash", false)) {
Toast.makeText(this, "App restarted after crash", Toast.LENGTH_SHORT).show();
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run(){
Intent intent = new Intent(frame_6_activity.this, frame_2_activity.class);
startActivity(intent);
finish();
}
}, 10000);
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
TextView textViewDate = findViewById(R.id.text_view_date);
textViewDate.setText(currentDate);
_bg__frame_6 = (View) findViewById(R.id._bg__frame_6);
background_1 = (ImageView) findViewById(R.id.background_1);
text_view_date = (TextView) findViewById(R.id.text_view_date);
logo_2_1 = (ImageView) findViewById(R.id.logo_2_1);
H2Value = (TextView) findViewById(R.id.H2Value);
}
}
Activity2.java
package com.ossus.SC20;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class frame_2_activity extends Activity {
private ProgressBar mProgressBar;
private TextView mLoadingText;
private int mProgressStatus = 0;
// private Handler mHandler = new Handler();
Handler handler = new Handler();
Timer timer;
private View _bg__frame_2;
private ImageView background_1;
private TextView text_view_date;
private ImageView logo_2_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame_2_new);
startService(new Intent(frame_2_activity.this, service.class));
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mLoadingText = (TextView) findViewById(R.id.LoadingCompleteTextView);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
startProgress();
}
});
thread.start();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run(){
Intent intent = new Intent(frame_2_activity.this, frame_3_activity.class);
startActivity(intent);
finish();
}
}, 10000);
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
TextView textViewDate = findViewById(R.id.text_view_date);
textViewDate.setText(currentDate);
_bg__frame_2 = (View) findViewById(R.id._bg__frame_2);
background_1 = (ImageView) findViewById(R.id.background_1);
text_view_date = (TextView) findViewById(R.id.text_view_date);
logo_2_1 = (ImageView) findViewById(R.id.logo_2_1);
//custom code goes here
}
public void startProgress(){
for (mProgressStatus = 0; mProgressStatus < 100; mProgressStatus = mProgressStatus + 1){
try{
Thread.sleep(1000);
mProgressBar.setProgress(mProgressStatus);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
mLoadingText.setText(String.valueOf(mProgressStatus + "% Completed"));
}
});
}
}
}
Service.java
package com.ossus.SC20;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
AndroidManifest.xml
<?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.ossus.SC20">
<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.SC20"
tools:targetApi="31">
<activity
android:name=".frame_3_activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:exported="true" >
</activity>
<activity
android:name=".frame_2_activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:exported="true" >
</activity>
<activity
android:name=".frame_6_activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<service android:name = ".service"/>
</application>
</manifest>

Unable to add view to a window with TYPE_PHONE params android

I am trying to create a floating view which should appear on top of everything but notification panel and settings app hide my view
I tried to use WindowManager.LayoutParams.TYPE_PHONE but its deprecated after oreo and app crashes if I try to add a view to that window with params set to WindowManager.LayoutParams.TYPE_PHONE
here is my java code
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.opengl.Visibility;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
public class FloatingMouseService extends Service {
private WindowManager mWindowManager;
private View floatingMouse;
public FloatingMouseService() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
LayoutInflater layoutInflater = (LayoutInflater) FloatingMouseService.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
floatingMouse = layoutInflater.inflate(R.layout.layoutmouse, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) FloatingMouseService.this.getSystemService(WINDOW_SERVICE);
mWindowManager.addView(floatingMouse, params);
}
}
here is MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
TextView serMess = findViewById(R.id.serMess);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
} else {
initializeView();
}
}
private void initializeView() {
Button connect = findViewById(R.id.connect);
findViewById(R.id.connect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(MainActivity.this, FloatingMouseService.class));
new Thread(new ClientServerReq()).start();
Toast.makeText(MainActivity.this, "Connected Successfully", Toast.LENGTH_SHORT).show();
connect.setText("Connected");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
if (requestCode == CODE_DRAW_OVER_OTHER_APP_PERMISSION) {
if (resultCode == RESULT_OK) {
initializeView();
} else { //Permission is not available
Toast.makeText(this,
"Draw over other app permission not available. Closing the application",
Toast.LENGTH_SHORT).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onResume() {
super.onResume();
}
}
here is my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.MFB.project.sharekey">
<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" ></uses-permission>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<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.AppCompat.DayNight.DarkActionBar">
<activity
android:name="com.MFB.project.sharekey.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="com.MFB.project.sharekey.FloatingMouseService"
android:enabled="true" />
</application>
</manifest>

Button click not switching activity

I've been trying to get this app to switch activities by simply clicking the button, but the app simply refreshes and I stay on the same activity. Nothing happens. And if I uncomment the lines of code for my second activity, the OnClick ones, I get null pointer errors. I have no idea what I could be doing wrong. Here's my code in main activity:
package com.example.commontaskslite;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.Button;
import android.widget.CompoundButton;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TimePicker alarmClock;
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
private Button search;
private Button redial;
private Button address;
boolean checked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmClock = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
search = (Button) findViewById(R.id.search);
redial = (Button) findViewById(R.id.redial);
address = (Button) findViewById(R.id.address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openSearch(view);
}
});
redial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openRedial(view);
}
});
address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openShowAddress(view);
}
});
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(isChecked){
checked = true;
onToggleClicked();
}
else{
checked = false;
onToggleClicked();
}
}
});
}
public void openSearch(View V){
Intent _intent = new Intent(MainActivity.this,Search.class);
startActivity(_intent);
}
public void openRedial(View V){
Intent _intent = new Intent(MainActivity.this,Redial.class);
startActivity(_intent);
}
public void openShowAddress(View V){
Intent _intent = new Intent(MainActivity.this,ShowAddress.class);
startActivity(_intent);
}
public void onToggleClicked(){
long time;
if(checked) {
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmClock.getHour());
calendar.set(Calendar.MINUTE, alarmClock.getMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0) {
time = time + (1000 * 60 * 60 * 12);
} else {
time = time + (1000 * 60 * 60 * 24);
}
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
}
else{
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this,"ALARM OFF", Toast.LENGTH_SHORT).show();
AlarmReceiver.ringtone.stop();
}
}
}
Here's the code in the second activity:
package com.example.commontaskslite;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class Search extends AppCompatActivity {
private PendingIntent pendingIntent;
private Button alarm;
private Button redial;
private Button address;
private SearchView searchView;
private String searchQuery;
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = getIntent();/*
address = (Button) findViewById(R.id.address2);
redial = (Button) findViewById(R.id.redial2);
alarm = (Button) findViewById(R.id.alarm);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
searchQuery = s;
return true;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
address.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openShowAddress(view);
}
});
redial.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openRedial(view);
}
});
alarm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity(view);
}
});*/
}
public void openShowAddress(View V){
Intent _intent = new Intent(this,ShowAddress.class);
startActivity(_intent);
}
public void openRedial(View V){
Intent _intent = new Intent(this,Redial.class);
startActivity(_intent);
}
public void openMainActivity(View V){
Intent _intent = new Intent(this,MainActivity.class);
startActivity(_intent);
}
}
And here's the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.commontaskslite">
<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.CommonTasksLite">
<activity
android:name=".ShowAddress"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ALL_APPS"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Redial"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.CALL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Search"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<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>
<receiver android:name=".AlarmReceiver">
</receiver>
</application>
</manifest>
summarizing the answer that was found in comments.
Change setContentView(R.layout.activity_main); to another layout other than activity_main in Search Activity.

App is stopped on getContentResolver().query(...) when SMS is sent

Good day, I am programming application about catching the sent messages. Everything is working, the ContentObserver is called everytime when I try to send a SMS, but in onChange(boolean selfChange) method the application drops on the :
Cursor cur = getContentResolver().query(uriSMS, null, null, null, null)
.............................. screen http://imgur.com/a/hE94K
in TrackerService.java in mObserver. When I am debbuging that via Step Over (F8), on this line It open me a Looper.java and drops on this lines http://imgur.com/a/uh4Dl ... How to fix that for working please? I hope you will understand my problem and sorry for my bad english. Thank you so much!
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
Intent serviceIntent;
private static MyReceiver mServiceReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
Log.i("Status","Pause");
unregisterReceiver(mServiceReceiver);
super.onPause();
}
#Override
protected void onResume() {
Log.i("Status","Resume");
serviceIntent = new Intent(MainActivity.this, TrackerService.class);
startService(serviceIntent);
mServiceReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(TrackerService.mAction);
registerReceiver(mServiceReceiver, intentFilter);
super.onResume();
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.i("ServiceReceiver", "onReceive()");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TrackerService.java
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class TrackerService extends Service
{
public static final String mAction = "SMSTracker";
ContentResolver content;
ContentResolver contentResolver;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Status","Service Start");
contentResolver = this.getContentResolver();
contentResolver.registerContentObserver(Uri.parse("content://sms/"), true, new mObserver(new Handler()));
return super.onStartCommand(intent, flags, startId);
}
class mObserver extends ContentObserver {
public mObserver(Handler handler) {
super(handler);
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.i("Status","onChange");
Uri uriSMS = Uri.parse("content://sms/out/");
Cursor cur = getContentResolver().query(uriSMS, null, null, null, null);
//Log.i("SMS", "Columns: " + cur.getColumnNames());
cur.moveToNext();
String smsText = cur.getString(cur.getColumnIndex("body"));
Log.i("SMS", "SMS Lenght: " + smsText.length());
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("Status","Service Destroy");
}
#Override
public IBinder onBind(Intent intent) {
Log.i("Status","Service Bind");
return null;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wut.com.smstry">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<application
android:label="#string/app_name"
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=".TrackerService" />
</application>
</manifest>
Make sure you're registering for the right content path. Ex:-
Inbox = "content://sms/inbox"
Failed = "content://sms/failed"
Queued = "content://sms/queued"
Sent = "content://sms/sent"
Draft = "content://sms/draft"
Outbox = "content://sms/outbox"
Undelivered = "content://sms/undelivered"
All = "content://sms/all"
Conversations = "content://sms/conversations".
contentResolver.registerContentObserver(Uri.parse("content://sms/outbox"), true, new mObserver(new Handler()));
Similarly use the same path on the cursor.query

Categories