My app keeps crashing after splash activity finishes - java

my app when I run it only shows the splash screen then crashes.
at first it was giving me "app keep on stopping" when I run it but now it runs the splash screen then crashes.
Splash screen.
public class SplashActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
private boolean mIsBackButtonPressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
sharedPreferences=getSharedPreferences(Constants.pref_name,MODE_PRIVATE);
new Handler().postDelayed(new Runnable() {
public void run() {
if (!mIsBackButtonPressed) {
if(getIntent().hasExtra("action_type")){
Intent intent= new Intent(SplashActivity.this, MainActivity.class);
String action_type=getIntent().getExtras().getString("action_type");
String receiverid=getIntent().getExtras().getString("senderid");
String title=getIntent().getExtras().getString("title");
String icon=getIntent().getExtras().getString("icon");
intent.putExtra("icon",icon);
intent.putExtra("action_type",action_type);
intent.putExtra("receiverid",receiverid);
intent.putExtra("title",title);
startActivity(intent);
finish();
}
else
GPSStatus();
}
}
}, 2000);
}
public void onBackPressed() {
// set the flag to true so the next activity won't start up
mIsBackButtonPressed = true;
super.onBackPressed();
}
public void GPSStatus(){
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!GpsStatus)
{
Toast.makeText(this, "On Location in High Accuracy", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),2);
}else {
GetCurrentlocation();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2){
GPSStatus();
}
}
private void GetCurrentlocation() {
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
enable_location();
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// if we successfully get the location of the user then we will save the locatio into
//locally and go to the Main view
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Constants.Lat,""+location.getLatitude());
editor.putString(Constants.Lon,""+location.getLongitude());
editor.commit();
startActivity(new Intent(SplashActivity.this, MainActivity.class));
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
}
else {
if(sharedPreferences.getString(Constants.Lat,"").equals("") || sharedPreferences.getString(Constants.Lon,"").equals("") ){
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Constants.Lat,"33.738045");
editor.putString(Constants.Lon,"73.084488");
editor.commit();
}
startActivity(new Intent(SplashActivity.this, MainActivity.class));
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
}
}
});
}
private void enable_location() {
EnableLlocationFragment enable_llocationFragment = new EnableLlocationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left,R.anim.in_from_left,R.anim.out_to_right);
getSupportFragmentManager().popBackStackImmediate();
transaction.replace(R.id.splash, enable_llocationFragment).addToBackStack(null).commit();
}
}
I believe it must be something with my MainActivity that is causing the problem,
this is the main activity code
main activity:
public class MainActivity extends AppCompatActivity {
long mBackPressed;
public static SharedPreferences sharedPreferences;
public static String user_id;
public static String user_name;
public static String image;
public static String image1;
public static String birthday;
public static String about;
public static String purchased;
public static String token;
BaseApp baseApp;
LinearLayout llsearch;
DatabaseReference rootref;
AboutModels modelAbout;
public static String title="none";
EditText search;
public static MainActivity mainActivity;
private FragmentManager fragmentManager;
BottomNavigationView navigation;
int previousSelect = 0;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
HomeFragment homeFragment = new HomeFragment();
navigationItemSelected(0);
loadFrag(homeFragment, getString(R.string.menu_home), fragmentManager);
llsearch.setVisibility(View.VISIBLE);
return true;
case R.id.property:
PropertyFragment propertyFragment = new PropertyFragment();
navigationItemSelected(1);
loadFrag(propertyFragment, getString(R.string.menu_property), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
case R.id.favourite:
FavouriteFragment matchFragment = new FavouriteFragment();
navigationItemSelected(2);
loadFrag(matchFragment, getString(R.string.menu_favourite), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
case R.id.chat:
MessageFragment messageFragment = new MessageFragment();
navigationItemSelected(3);
loadFrag(messageFragment, getString(R.string.menu_chat), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
case R.id.user:
ProfileFragment profileFragment = new ProfileFragment();
navigationItemSelected(4);
loadFrag(profileFragment, getString(R.string.menu_profile), fragmentManager);
llsearch.setVisibility(View.GONE);
return true;
}
return false;
}
};
private BaseApp FirebaseInstanceId;
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mAdViewLayout = findViewById(R.id.adView);
BannerAds.ShowBannerAds(getApplicationContext(), mAdViewLayout);
fragmentManager = getSupportFragmentManager();
llsearch = findViewById(R.id.llsearch);
baseApp = BaseApp.getInstance();
navigation = findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
modelAbout = new AboutModels();
HomeFragment homeFragment = new HomeFragment();
loadFrag(homeFragment, getString(R.string.menu_home), fragmentManager);
mainActivity =this;
sharedPreferences = getSharedPreferences(Constants.pref_name, MODE_PRIVATE);
user_id = sharedPreferences.getString(Constants.uid, "null");
user_name = sharedPreferences.getString(Constants.f_name, "") + " " + sharedPreferences.getString(Constants.l_name, "");
image =sharedPreferences.getString(Constants.u_pic,"null");
image1 =sharedPreferences.getString("image1","null");
token=sharedPreferences.getString(Constants.device_token, FirebaseInstanceId.getInstance().getToken());
rootref= FirebaseDatabase.getInstance().getReference();
search = findViewById(R.id.search);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String sSearch= search.getText().toString().trim();
if (TextUtils.isEmpty(sSearch)) {
Toast.makeText(MainActivity.this, "Column Can't be Empty", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
intent.putExtra("searchtext", sSearch);
startActivity(intent);
return true;
}
return false;
}
});
PackageInfo packageInfo = null;
try {
packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Constants.versionname=packageInfo.versionName;
}
#Override
protected void onStart() {
super.onStart();
if (baseApp.getIsLogin()) {
rootref.child("Users").child(user_id).child("token").setValue(token);
} else {
rootref.child("Users").child(user_id).child("token").setValue("null");
}
}
#Override
protected void onResume() {
super.onResume();
Check_version();
}
#Override
public void onBackPressed() {
int count = this.getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
if (mBackPressed + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
clickDone();
}
} else {
super.onBackPressed();
}
}
public void clickDone() {
new AlertDialog.Builder(this)
.setIcon(R.mipmap.ic_launcher)
.setTitle(getString(R.string.app_name))
.setMessage("Are you sure you want to exit?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
public void Check_version(){
VersionChecker versionChecker = new VersionChecker(this);
versionChecker.execute();
}
public void loadFrag(Fragment f1, String name, FragmentManager fm) {
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.Container, f1, name);
ft.commit();
}
public void navigationItemSelected(int position) {
previousSelect = position;
}
}
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.otacodes.goestate">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="com.android.vending.BILLING" />
<application
android:name="com.otacodes.goestate.Constants.BaseApp"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-1300058369369222~7049892454"/>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.otacodes.goestate.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name="com.otacodes.goestate.Activity.SplashActivity"
android:screenOrientation="fullSensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.otacodes.goestate.Activity.LoginFormActivity"
android:screenOrientation="fullSensor"
android:theme="#style/Login_phone_A"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.RegisterActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPropByCatActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPropActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPopularActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.AllPropByCityActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.SearchActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.MyPropertyActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.PropertyDetailActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.FilterSearchActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.PicklocationActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
<activity
android:name="com.otacodes.goestate.Activity.MainActivity"
android:screenOrientation="portrait" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity
android:name="com.soundcloud.android.crop.CropImageActivity"
android:screenOrientation="portrait"
android:theme="#style/noActionBar"
/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_launcher" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/coloraccent" />
<service android:name="com.otacodes.goestate.Utils.NotificationReceive"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name="com.otacodes.goestate.Activity.AboutActivity" />
<activity android:name="com.otacodes.goestate.Activity.PrivacyActivity" />
<activity android:name="com.otacodes.goestate.Activity.BlockActivity" />
<activity android:name="com.otacodes.goestate.Activity.FullImageActivity" />
<activity android:name="com.otacodes.goestate.Activity.AddPropertyActivity" />
</application>
</manifest>
logcat
2022-01-05 01:50:49.624 4111-8222/? I/ExperimentPackageManage: Package com.google.android.os.statsd name not found! Using module version.
2022-01-05 01:50:49.626 4111-8222/? I/ExperimentPackageManage: Package com.google.android.os.statsd name not found! Using module version.
2022-01-05 01:50:49.631 4111-8222/? I/ayxc: updateFromConfigurations DeviceConfig for namespace virtualization_framework_native [CONTEXT service_id=204 ]
2022-01-05 01:50:49.572 3623-3623/? V/SettingsProvider: Notifying for 0: content://settings/config/app_standby/Phenotype_flags
2022-01-05 01:50:49.635 3623-3623/? V/SettingsProvider: Notifying for 0: content://settings/config/virtualization_framework_native/Phenotype_flags
2022-01-05 01:50:51.048 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.gms.feedback.internal.IFeedbackService cmp=com.google.android.gms/.chimera.GmsBoundBrokerService }
2022-01-05 01:50:52.610 1768-5915/? E/GnssHAL_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2022-01-05 01:50:52.787 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.mdd.service.START cmp=com.google.android.gms/.chimera.GmsBoundBrokerService }
2022-01-05 01:50:53.138 4111-6600/? W/Nearby: Failed attempt #3 out of 3 for RestoreDeviceName [CONTEXT service_id=49 ]
java.lang.IllegalStateException: BluetoothAdapter not ready yet!
at aswl.d(:com.google.android.gms#214815031#21.48.15 (100700-414534850):2)
at aswj.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at cmvg.call(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at cmvl.a(:com.google.android.gms#214815031#21.48.15 (100700-414534850):2)
at cmvl.b(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at aswk.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):5)
at java.lang.Thread.run(Thread.java:919)
at xtk.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):5)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at xzm.run(:com.google.android.gms#214815031#21.48.15 (100700-414534850):0)
at java.lang.Thread.run(Thread.java:919)
2022-01-05 01:50:55.826 3623-3647/? E/memtrack: Couldn't load memtrack module
2022-01-05 01:50:55.826 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.gms.common.download.START cmp=com.google.android.gms/.chimera.GmsBoundBrokerService }
2022-01-05 01:50:55.826 3623-3647/? W/android.os.Debug: failed to get memory consumption info: -1
2022-01-05 01:50:55.869 6662-6662/? D/BoundBrokerSvc: onUnbind: Intent { act=com.google.android.gms.ocr.service.internal.START cmp=com.google.android.gms/.chimera.GmsInternalApiService }
2022-01-05 01:50:55.974 7623-7658/? I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_STATUS_SMS_TIME_OUT
2022-01-05 01:50:55.976 7623-7623/? I/Dialer: RetryPolicy - discarding deferred status: configuration_state=4
2022-01-05 01:50:55.979 7623-7623/? I/Dialer: VvmTaskExecutor - no more tasks, stopping service if no task are added in 5000 millis
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: VvmTaskReceiver - task received
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: VvmTaskReceiver - TaskExecutor already running
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: Task.createTask - create task:com.android.voicemail.impl.ActivationTask
2022-01-05 01:50:55.980 7623-7623/? I/Dialer: RetryPolicy - retry #1 for com.android.voicemail.impl.ActivationTask#d3f6d93 queued, executing in 5000
2022-01-05 01:50:55.981 7623-7623/? I/Dialer: VvmTaskExecutor - com.android.voicemail.impl.ActivationTask#d3f6d93 added
2022-01-05 01:50:55.981 7623-7623/? I/Dialer: VvmTaskExecutor - minimal wait time:5000
2022-01-05 01:50:55.981 7623-7623/? I/Dialer: VvmTaskExecutor - sleep for 5000 millis
2022-01-05 01:50:58.350 4111-8109/? E/GCM: Missing checkin config file
2022-01-05 01:50:58.350 4111-8109/? W/GCM: GCM FAILED TO INITIALIZE - missing checkin
2022-01-05 01:50:58.609 1768-5915/? E/GnssHAL_GnssInterface:
L_GnssInterface: gnssSvStatusCb: b: input svInfo.flags is 8
2022-01-05 01:51:00.984 7623-7658/? I/Dialer: VvmTaskExecutor - executing task com.android.voicemail.impl.ActivationTask#d3f6d93
2022-01-05 01:51:00.984 7623-7658/? I/Dialer: PreOMigrationHandler - ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, ***, UserHandle{0} already migrated
2022-01-05 01:51:01.021 7671-7685/? I/VoicemailNotifier: receivers for android.intent.action.PROVIDER_CHANGED :[]
2022-01-05 01:51:01.024 7623-7658/? I/Dialer: VvmActivationTask - VVM content provider configured - vvm_type_cvvm
2022-01-05 01:51:01.025 7623-7658/? I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_ACTIVATING
2022-01-05 01:51:01.040 7671-7687/? I/VoicemailNotifier: receivers for android.intent.action.PROVIDER_CHANGED :[]
2022-01-05 01:51:01.047 3894-4110/? I/LocationAccessPolicy: Allowing com.android.dialer fine because it doesn't target API 29 yet. Please fix this app. Called from getServiceStateForSubscriber
2022-01-05 01:51:01.050 3894-4110/? I/LocationAccessPolicy: Allowing com.android.dialer coarse because it doesn't target API 29 yet. Please fix this app. Called from getServiceStateForSubscriber

Sorry because I can't comment, you should rebuild app, then open logcat and select error flag to view error log (default is verbose)
With only codes above, we can't help anything

Related

AlarmManager alarm not working if exits app

I have an alarm clock app. When I create an alarm, it works well (If you do not exit the application), but if you exit, then the alarm does not work.
I want the alarm to work even when the application is turned off and the phone is in sleep mode. Here is my code:
AlarmFragment (From which the alarm is set):
package org.vitaliy.numbell.Fragments;
public class AlarmFragment extends Fragment {
ImageButton add_btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarm, container, false);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
add_btn = view.findViewById(R.id.add_btn);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cur_time = Calendar.getInstance();
MaterialTimePicker materialTimePicker = new MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_24H)
.setHour(cur_time.get(Calendar.HOUR_OF_DAY))
.setMinute(cur_time.get(Calendar.MINUTE))
.build();
materialTimePicker.addOnPositiveButtonClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.MINUTE, materialTimePicker.getMinute());
calendar.set(Calendar.HOUR_OF_DAY, materialTimePicker.getHour());
//Set alarm clock
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(), getAlarmInfoPendingIntent());
alarmManager.setAlarmClock(alarmClockInfo, getAlarmActionPendingIntent());
}
});
materialTimePicker.show(getActivity().getSupportFragmentManager(),"tag_picker");
}
});
return view;
}
private PendingIntent getAlarmInfoPendingIntent() {
Intent alarmInfoIntent = new Intent(getActivity(), StartActivity.class);
alarmInfoIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getActivity(getActivity(),0,alarmInfoIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent getAlarmActionPendingIntent() {
Intent intent = new Intent(getActivity(), AlarmActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getActivity(getActivity(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.vitaliy.numbell">
<uses-permission android:name="android.permission.INTERNET" />
<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.Numbell">
<activity android:name=".AlarmActivity" />
<receiver
android:name=".Widget"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
<activity
android:name=".AppActivity"
android:configChanges="colorMode|keyboardHidden|screenSize|orientation|locale"
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".StartActivity"
android:configChanges="colorMode|keyboardHidden|screenSize|orientation|locale"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
AlarmActivity (Activity that opens when the alarm goes off):
package org.vitaliy.numbell;
public class AlarmActivity extends AppCompatActivity {
Ringtone ringtone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(this, notificationUri);
if(ringtone==null){
notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
ringtone = RingtoneManager.getRingtone(this, notificationUri);
}
if(ringtone != null){
ringtone.play();
}
}
#Override
protected void onDestroy() {
if(ringtone != null && ringtone.isPlaying()){
ringtone.stop();
}
super.onDestroy();
}
}
A better approach to this can be to show alarm via notifications (Broadcast Receiver) when app is not in background and when phone is locked or on standby you can call an activity there.
First off all add these two lines to Manifest to show activities on lockscreen:
<activity
android:name=".AppActivity"
android:configChanges="colorMode|keyboardHidden|screenSize|orientation|locale"
android:exported="false"
android:screenOrientation="portrait"
android:showOnLockScreen="true"
android:showWhenLocked="true" />
After this you can use KeyGuardManager and PowerManager to check in which state your phone is:
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (pm.isInteractive() && pm.isScreenOn() && keyguardManager.isKeyguardLocked() && keyguardManager.isDeviceLocked()) {
// This will be helpful to show your activity or notification on lock screen
}

Android broadcast reciever called but doesn't starts foreground service

I set up broadcast reciever for restarting my foreground service after reboot.
I have two devices and it works on Meizu M1 note (android 5.1) but doesn't work on Samsung A8 (android 9). Looking for reason in restrictions after Oreo and seems like it ok, but just in case https://developer.android.com/about/versions/oreo/background.html
On the second one broadcast reciever called, but service not started after reboot.
Service tracks location and uses startForeground() with Notification for correct work.
Also tried to add Worker to restart service after reboot, but seems like work missing after that.
Please, geve any suggestions why my reciever doesn't run service.
Thanks.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tracker">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".ui.di.App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:isolatedProcess="true"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name="com.example.tracker.ui.broadcast.ServiceRestart">
<intent-filter>
<action android:name="restartService" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name="com.example.tracker.ui.service.TrackerService"
android:enabled="true" />
<service
android:name="com.example.tracker.ui.worker.RestartIntentService"
android:enabled="true" />
<activity android:name=".ui.screen.main.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Reciever:
public class ServiceRestart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Broadcast: ServiceRestart launched " + intent.getAction(), Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, TrackerService.class));
} else {
context.startService(new Intent(context, TrackerService.class));
}
}
}
Service:
public class TrackerService extends Service implements LocationListener {
public static final String TAG = "TrackerService";
private static final int PROCESS_ID = 1024;
private static final int INTERVAL = 120; //seconds
private ConnectivityManager connectivityManager;
private PeriodicWorkRequest workRequest;
private PeriodicWorkRequest restartTrackerRequest;
private DbFirebaseModel dbFirebaseModel = new DbFirebaseModel();
private ServiceHandler mServiceHandler;
private static final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message message) {
}
}
public void onCreate() {
super.onCreate();
HandlerThread mHandlerThread = new HandlerThread("TrackerService.HandlerThread");
mHandlerThread.start();
mServiceHandler = new ServiceHandler(mHandlerThread.getLooper());
}
public TrackerService() {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
addNotificationAndStartForeground();
addWorkers();
mServiceHandler.post(() -> {
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
runLocationTransfer();
});
Log.d(TAG, "===== SERVICE START");
return START_STICKY;
}
private void addWorkers() {
workRequest = new PeriodicWorkRequest.Builder(
FirebaseWorker.class, 15, TimeUnit.MINUTES, 2, TimeUnit.MINUTES)
.build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
FirebaseWorker.TAG,
ExistingPeriodicWorkPolicy.REPLACE,
workRequest);
restartTrackerRequest = new PeriodicWorkRequest.Builder(
TrackerRestartWorker.class, 15, TimeUnit.MINUTES, 2, TimeUnit.MINUTES
).build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
TrackerRestartWorker.TAG,
ExistingPeriodicWorkPolicy.REPLACE,
restartTrackerRequest);
}
private void addNotificationAndStartForeground() {
String name = getString(R.string.app_name);
String description = "Service running...";
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
Integer.toString(PROCESS_ID), "Tracker", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Notify me when location tracking");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notificationBuilder = new Notification.Builder(this, Integer.toString(PROCESS_ID));
notificationBuilder.setContentTitle(name)
.setContentText(description)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent);
notificationManager.notify(PROCESS_ID, notificationBuilder.build());
} else {
notificationBuilder = new Notification.Builder(this);
notificationBuilder.setContentTitle(name)
.setContentText(description)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent);
}
startForeground(PROCESS_ID, notificationBuilder.build());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "===== SERVICE STOP");
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
WorkManager.getInstance(this).cancelWorkById(workRequest.getId());
WorkManager.getInstance(this).cancelWorkById(restartTrackerRequest.getId());
Log.d(TAG, "===== WORKERS STOP");
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(TAG, "TASK REMOVED");
Toast.makeText(this, "LOCATION TASK REMOVED", Toast.LENGTH_SHORT).show();
super.onTaskRemoved(rootIntent);
}
private void runLocationTransfer() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
locationRequest.setInterval(INTERVAL * 1000);
locationRequest.setFastestInterval(INTERVAL * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
try {
getFusedLocationProviderClient(this).requestLocationUpdates(locationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(#NonNull Location location) {
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
stopSelf();
Log.d(TAG, "====== SERVICE STOPPED by itself");
} else if (connectivityManager.getActiveNetworkInfo() != null
&& connectivityManager.getActiveNetworkInfo().isConnected()) {
dbFirebaseModel.saveLocation(location);
// test using sound notifications
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "LOCATION ------ LATITUDE: " + location.getLatitude() + " LONGITUDE: " + location.getLongitude(), Toast.LENGTH_SHORT).show();
} else {
saveToLocalStorage(location);
}
}
private void saveToLocalStorage(Location location) {
Hawk.init(this).build();
String userId = Objects.requireNonNull(
FirebaseAuth.getInstance().getCurrentUser()
).getUid();
LocationData locationData = new LocationData(userId, location);
long count = 0;
if (Hawk.count() > count) {
count = Hawk.count();
}
while (Hawk.contains(String.valueOf(count))) {
count++;
}
Hawk.put(String.valueOf(count), locationData);
Log.d(TAG, "HAWK /// Saved to local storage. COUNT = " + Hawk.count());
}
}
Following steps helped me solve it:
Remove and reinstall app
Change manifest according to this
<receiver android:name="com.foxminded.tracker.ui.broadcast.ServiceRestart"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="restartService" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Here added "android.intent.action.LOCKED_BOOT_COMPLETED" and android:exported="true" android:enabled="true"

Firebase Database not fetching data from Firebase Database Reference

Everything is working fine but DatabaseReference is not fetching data, it's like just ignoring my code to run and like my internet is not working please help i'm new here in this community below are my codes and images.
Previously it was working, but as i just changed some code to make only currentVersion >= vCode so that user can continue even if the value in database is < currentVersion but, after building it my app was not fetching data from firebase and the i tried to uninstall it, installed again from play store the older version it also was not fetching data please help. I don't know what wrong i did. Thus i am planning to install ParrotOS so maybe then it'll work but it's better to ask first from the experts
firebase database image
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView appName;
FirebaseUser firebaseUser;
String currentVersionName;
long currentVersionCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appName = findViewById(R.id.appName);
currentVersionName = BuildConfig.VERSION_NAME;
currentVersionCode = BuildConfig.VERSION_CODE;
animateAppName();
netConn();
FirebaseAuth.getInstance();
}
public void applyScreenChange(){
String sharedPerfId = "MyAppPref";
SharedPreferences sharedPreferences = getSharedPreferences(sharedPerfId,0);
boolean isAdvertiserLoggedIn = sharedPreferences.getBoolean("isAdvertiserLoggedIn",false);
boolean isCreatorLoggedIn = sharedPreferences.getBoolean("isCreatorLoggedIn",false);
if (isAdvertiserLoggedIn){
skipSetupToAdvertiser();
}
else if (isCreatorLoggedIn){
skipSetupToCreator();
}
else {
newActivity();
}
}
public void animateAppName(){
appName.setTranslationY(-1000f);
appName.animate().translationYBy(1000f).setDuration(500);
}
public void netConn(){
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()){
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("Connect to Network and Then try again");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
netConn();
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}else {
// Check older version
// applyScreenChange();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Version");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String vName = (String) snapshot.child("latestVersionName").getValue();
long vCode = (long) snapshot.child("latestVersionCode").getValue();
if (currentVersionName.equals(vName) && currentVersionCode >= vCode){
applyScreenChange();
// TODO: 16-08-2020 add condition to open app if version is higher
}else {
Toast.makeText(MainActivity.this, "Old Version", Toast.LENGTH_SHORT).show();
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("You're on Older Version");
alertDialog.setMessage("This Version is no more supported, Kindly update your App to Continue");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.super.onBackPressed();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.app_link))));
Toast.makeText(MainActivity.this, "Kindly Search Sponso on PlayStore and Update", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
public void newActivity(){
Intent intent = new Intent(MainActivity.this, AdvertiserCreatorChooser.class);
startActivity(intent);
finish();
}
public void skipSetupToAdvertiser(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser!=null) {
Intent intent = new Intent(MainActivity.this, AdvertiserHome.class);
startActivity(intent);
finish();
}else{
Intent intent = new Intent(MainActivity.this, AdvertiserLoginRegister.class);
startActivity(intent);
finish();
}
}
public void skipSetupToCreator(){
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser!=null) {
Intent intent = new Intent(MainActivity.this, CreatorHome.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(MainActivity.this, CreatorLoginRegister.class);
startActivity(intent);
finish();
}
}
}
manifest.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.webroose.sponso">
<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:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:allowBackup="true"
android:theme="#style/AppTheme">
<activity android:name=".Advertiser.AdvertiserCampaignUpdate"/>
<activity android:name=".Advertiser.ui.main.AdvertiserSettings" />
<activity android:name=".Creator.CreatorRecentlyChat" />
<activity android:name=".Advertiser.AdvertiserRecentlyChat" />
<activity android:name=".Advertiser.AdvertiserChatActivity" />
<activity android:name=".Creator.CreatorChatActivity" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="#string/app_id" />
<activity android:name=".Creator.CreatorUserDetails" />
<activity android:name=".Creator.CreatorList" />
<activity android:name=".Common.AboutUs" />
<activity
android:name=".AdvertiserHome"
android:label="#string/title_activity_advertiser_home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Advertiser.AdvertiserLoginRegister"
android:label="#string/title_activity_advertiser_login_register"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Common.PrivacyPolicy" />
<activity android:name=".Common.ChangePassword" />
<activity android:name=".Creator.CreatorSettings" />
<activity android:name=".Common.ChangeEmail" />
<activity android:name=".Advertiser.AdvertiserUserDetails" />
<activity android:name=".Advertiser.AdvertiserList" />
<activity
android:name=".CreatorHome"
android:label="#string/title_activity_creator_home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Creator.CreatorLoginRegister"
android:label="#string/title_activity_creator_login_register"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".AdvertiserCreatorChooser" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
dependency
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'com.google.android.material:material:1.2.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment:2.3.0'
implementation 'androidx.navigation:navigation-ui:2.3.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.google.firebase:firebase-auth:19.3.2'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
implementation 'com.google.android.gms:play-services-ads:19.3.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.google.firebase:firebase-analytics:17.5.0'
implementation 'com.google.firebase:firebase-messaging:20.2.4'
implementation 'com.facebook.android:audience-network-sdk:5.10.1'
}
Change
DatabaseReference databaseReference =FirebaseDatabase.getInstance().getReference("Version");
To
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Version");
And the actual problem was with Firebase Database
Check below image with firebase database

AndroidRuntime: FATAL EXCEPTION

Gradle sync : No error
Rebuild Project : No error
After hitting RUN >> Installing app through ADB
but unable to launch application. Forced stopped
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.bookcircuit"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
useLibrary 'org.apache.http.legacy'
manifestPlaceholders = [onesignal_app_id : "5c3d7b9b-1874-463f-8081-1c3439ccb3ea",
onesignal_google_project_number: "REMOTE"]
multiDexEnabled true
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Logcat:
2019-05-26 01:29:47.773 29431-29431/com.example.bookcircuit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bookcircuit, PID: 29431
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bookcircuit/com.example.bookcircuit.SplashActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class androidx.constraintlayout.ConstraintLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2928)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3063)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class androidx.constraintlayout.ConstraintLayout
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class androidx.constraintlayout.ConstraintLayout
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.constraintlayout.ConstraintLayout" on path: DexPathList[[zip file "/data/app/com.example.bookcircuit-UeVp2v3GMHxcnEsLL2108Q==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.bookcircuit-UeVp2v3GMHxcnEsLL2108Q==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.view.LayoutInflater.createView(LayoutInflater.java:606)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:431)
at android.app.Activity.setContentView(Activity.java:2771)
at com.example.bookcircuit.SplashActivity.onCreate(SplashActivity.java:25)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3063)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
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.example.bookcircuit">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
tools:node="replace"
android:name=".init.CustomApplication"
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/logo"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="AA_DB_NAME"
android:value="MyDatabase.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="5" />
<meta-data
android:name="AA_MODELS"
android:value="com.example.bookcircuit.db.Notification" />
<!--
Add the following to your AndroidManifest.xml to prevent the launching of your main Activity
if you are calling startActivity above.
-->
<meta-data
android:name="com.onesignal.NotificationOpened.DEFAULT"
android:value="DISABLE" />
<activity android:name=".SplashActivity"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".MainActivity"
android:theme="#style/WhiteTheme" />
<activity
android:name=".LoginActivity"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".HelpCenter"
android:theme="#style/WhiteTheme" />
<activity
android:name=".Profile"
android:theme="#style/WhiteTheme" />
<activity
android:name=".Cart"
android:theme="#style/WhiteTheme" />
<activity
android:name=".UpdateData"
android:theme="#style/WhiteTheme"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".ForgotPassword"
android:theme="#style/Theme.AppCompat.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".NotificationActivity"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Cards"
android:theme="#style/WhiteTheme" />
<activity
android:name=".IndividualProduct"
android:theme="#style/WhiteTheme" />
<activity
android:name=".Wishlist"
android:theme="#style/WhiteTheme" />
<activity
android:name=".OrderDetails"
android:theme="#style/WhiteTheme" />
<activity
android:name=".OrderPlaced"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Tshirts"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Bags"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Calendars"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Keychains"
android:theme="#style/WhiteTheme" />
<activity
android:name=".prodcutscategory.Stationary"
android:theme="#style/WhiteTheme" />
<activity android:name=".WelcomeActivity"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
MainActivity :
public class MainActivity extends AppCompatActivity {
private SliderLayout sliderShow;
private Drawer result;
private CrossfadeDrawerLayout crossfadeDrawerLayout = null;
//to get user session data
private UserSession session;
private HashMap<String, String> user;
private String name, email, photo, mobile;
private String first_time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface typeface = ResourcesCompat.getFont(this, R.font.blacklist);
TextView appname = findViewById(R.id.appname);
appname.setTypeface(typeface);
//check Internet Connection
new CheckInternetConnection(this).checkConnection();
//retrieve session values and display on listviews
getValues();
//Navigation Drawer with toolbar
inflateNavDrawer();
//ImageSLider
inflateImageSlider();
if (session.getFirstTime()) {
//tap target view
tapview();
session.setFirstTime(false);
}
}
private void tapview() {
new TapTargetSequence(this)
.targets(
TapTarget.forView(findViewById(R.id.notifintro), "Notifications", "Latest offers will be available here !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true) // Whether to draw a drop shadow or not
.cancelable(false) // Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.first),
TapTarget.forView(findViewById(R.id.view_profile), "Profile", "You can view and edit your profile here !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true) // Whether to draw a drop shadow or not
.cancelable(false) // Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.third),
TapTarget.forView(findViewById(R.id.cart), "Your Cart", "Here is Shortcut to your cart !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true)
.cancelable(false)// Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.second),
TapTarget.forView(findViewById(R.id.visitingcards), "Categories", "Product Categories have been listed here !")
.targetCircleColor(R.color.colorAccent)
.titleTextColor(R.color.colorAccent)
.titleTextSize(25)
.descriptionTextSize(15)
.descriptionTextColor(R.color.accent)
.drawShadow(true)
.cancelable(false)// Whether tapping outside the outer circle dismisses the view
.tintTarget(true)
.transparentTarget(true)
.outerCircleColor(R.color.fourth))
.listener(new TapTargetSequence.Listener() {
// This listener will tell us when interesting(tm) events happen in regards
// to the sequence
#Override
public void onSequenceFinish() {
session.setFirstTime(false);
Toasty.success(MainActivity.this, " You are ready to go !", Toast.LENGTH_SHORT).show();
}
#Override
public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) {
}
#Override
public void onSequenceCanceled(TapTarget lastTarget) {
// Boo
}
}).start();
}
private void getValues() {
//create new session object by passing application context
session = new UserSession(getApplicationContext());
//validating session
session.isLoggedIn();
//get User details if logged in
user = session.getUserDetails();
name = user.get(UserSession.KEY_NAME);
email = user.get(UserSession.KEY_EMAIL);
mobile = user.get(UserSession.KEY_MOBiLE);
photo = user.get(UserSession.KEY_PHOTO);
}
private void inflateImageSlider() {
// Using Image Slider -----------------------------------------------------------------------
sliderShow = findViewById(R.id.slider);
//populating Image slider
ArrayList<String> sliderImages = new ArrayList<>();
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/Business_stationery_home_banner.jpg");
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/calendar-diaries-home-banner.jpg");
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/calendar-diaries-banner.jpg");
sliderImages.add("https://www.printstop.co.in/images/flashgallary/large/free-visiting-cards-home-banner.JPG");
for (String s : sliderImages) {
DefaultSliderView sliderView = new DefaultSliderView(this);
sliderView.image(s);
sliderShow.addSlider(sliderView);
}
sliderShow.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
}
private void inflateNavDrawer() {
//set Custom toolbar to activity -----------------------------------------------------------
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the AccountHeader ----------------------------------------------------------------
//Profile Making
IProfile profile = new ProfileDrawerItem()
.withName(name)
.withEmail(email)
.withIcon(photo);
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.gradient_background)
.addProfiles(profile)
.withCompactStyle(true)
.build();
//Adding nav drawer items ------------------------------------------------------------------
PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.home).withIcon(R.drawable.home);
PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.myprofile).withIcon(R.drawable.profile);
PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.wishlist).withIcon(R.drawable.wishlist);
PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4).withName(R.string.cart).withIcon(R.drawable.cart);
PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5).withName(R.string.logout).withIcon(R.drawable.logout);
SecondaryDrawerItem item7 = new SecondaryDrawerItem().withIdentifier(7).withName("Offers").withIcon(R.drawable.tag);
SecondaryDrawerItem item8 = new SecondaryDrawerItem().withIdentifier(8).withName(R.string.aboutapp).withIcon(R.drawable.credits);
SecondaryDrawerItem item9 = new SecondaryDrawerItem().withIdentifier(9).withName(R.string.feedback).withIcon(R.drawable.feedback);
SecondaryDrawerItem item10 = new SecondaryDrawerItem().withIdentifier(10).withName(R.string.helpcentre).withIcon(R.drawable.helpccenter);
SecondaryDrawerItem item12 = new SecondaryDrawerItem().withIdentifier(12).withName("App Tour").withIcon(R.drawable.tour);
SecondaryDrawerItem item13 = new SecondaryDrawerItem().withIdentifier(13).withName("Explore").withIcon(R.drawable.explore);
//creating navbar and adding to the toolbar ------------------------------------------------
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withHasStableIds(true)
.withDrawerLayout(R.layout.crossfade_drawer)
.withAccountHeader(headerResult)
.withDrawerWidthDp(72)
.withGenerateMiniDrawer(true)
.withTranslucentStatusBar(true)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(
item1, item2, item3, item4, item5, new DividerDrawerItem(), item7, item8, item9, item10,new DividerDrawerItem(),item12,item13
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
switch (position) {
case 1:
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
}
break;
case 2:
startActivity(new Intent(MainActivity.this, Profile.class));
break;
case 3:
startActivity(new Intent(MainActivity.this, Wishlist.class));
break;
case 4:
startActivity(new Intent(MainActivity.this, Cart.class));
break;
case 5:
session.logoutUser();
finish();
break;
case 7:
startActivity(new Intent(MainActivity.this, NotificationActivity.class));
break;
case 8:
new LibsBuilder()
.withFields(R.string.class.getFields())
.withActivityTitle(getString(R.string.about_activity_title))
.withAboutIconShown(true)
.withAboutAppName(getString(R.string.app_name))
.withAboutVersionShown(true)
.withLicenseShown(true)
.withAboutSpecial1(getString(R.string.domain))
.withAboutSpecial1Description(getString(R.string.website))
.withAboutSpecial2(getString(R.string.licence))
.withAboutSpecial2Description(getString(R.string.licencedesc))
.withAboutSpecial3(getString(R.string.changelog))
.withAboutSpecial3Description(getString(R.string.changes))
.withShowLoadingProgress(true)
.withAboutDescription(getString(R.string.about_activity_description))
.withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
.start(MainActivity.this);
break;
case 9:
new EasyFeedback.Builder(MainActivity.this)
.withEmail("beingdevofficial#gmail.com")
.withSystemInfo()
.build()
.start();
break;
case 10:
startActivity(new Intent(MainActivity.this, HelpCenter.class));
break;
case 12:
session.setFirstTimeLaunch(true);
startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
finish();
break;
case 13:
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
}
tapview();
break;
default:
Toast.makeText(MainActivity.this, "Default", Toast.LENGTH_LONG).show();
}
return true;
}
})
.build();
//Setting crossfader drawer------------------------------------------------------------
crossfadeDrawerLayout = (CrossfadeDrawerLayout) result.getDrawerLayout();
//define maxDrawerWidth
crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));
//add second view (which is the miniDrawer)
final MiniDrawer miniResult = result.getMiniDrawer();
//build the view for the MiniDrawer
View view = miniResult.build(this);
//set the background of the MiniDrawer as this would be transparent
view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background));
//we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
miniResult.withCrossFader(new ICrossfader() {
#Override
public void crossfade() {
boolean isFaded = isCrossfaded();
crossfadeDrawerLayout.crossfade(400);
//only close the drawer if we were already faded and want to close it now
if (isFaded) {
result.getDrawerLayout().closeDrawer(GravityCompat.START);
}
}
#Override
public boolean isCrossfaded() {
return crossfadeDrawerLayout.isCrossfaded();
}
});
}
#Override
protected void onStop() {
sliderShow.stopAutoCycle();
super.onStop();
}
#Override
public void onBackPressed() {
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
public void viewProfile(View view) {
startActivity(new Intent(MainActivity.this, Profile.class));
}
public void viewCart(View view) {
startActivity(new Intent(MainActivity.this, Cart.class));
}
#Override
protected void onResume() {
//check Internet Connection
new CheckInternetConnection(this).checkConnection();
sliderShow.startAutoCycle();
super.onResume();
}
public void Notifications(View view) {
startActivity(new Intent(MainActivity.this, NotificationActivity.class));
}
public void cardsActivity(View view) {
startActivity(new Intent(MainActivity.this, Cards.class));
}
public void tshirtActivity(View view) {
startActivity(new Intent(MainActivity.this, Tshirts.class));
}
public void bagsActivity(View view) {
startActivity(new Intent(MainActivity.this, Bags.class));
}
public void stationaryAcitivity(View view) {
startActivity(new Intent(MainActivity.this, Stationary.class));
}
public void calendarsActivity(View view) {
startActivity(new Intent(MainActivity.this, Calendars.class));
}
public void keychainsActivity(View view) {
startActivity(new Intent(MainActivity.this, Keychains.class));
}
}
Just add in your app(the one which says Module:app) level build.gradle
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
in you log data, we can clearly see
"Caused by: android.view.InflateException: Binary XML file line #2: Binary
XML file line #2: Error inflating class
androidx.constraintlayout.ConstraintLayout"
after implementing the constraint-layout library, just sync and clean your project.

Google Play Services - Activity Recognition Freezes After a Few Results

I have tried to simplify my code as much as possible, basically hte issue is that the ActivityRecognitionIntentService appears to be called a couple of times, then stalls out. It appears to be related to the requestCode in the PendingIntent, but I am not sure, can someone please advise me as to what is going wrong? Thanks.
Dashboard.java
public class Dashboard extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private BroadcastReceiver receiver;
private TextView tvActivity;
private GoogleApiClient mGoogleApiClient;
//String Locationp = "null";
//private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tvActivity = (TextView) findViewById(R.id.tvActivity);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
//.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle arg0) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 2000, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.e("MAIN", "Connected to ActRec");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 1000, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
Log.e("MAIN", "Connection suspended to ActRec");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("MAIN", "Not Connected to ActRec");
}
ActivityRecognitionIntentService.java
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbAct = result.getMostProbableActivity();
int confidence = mostProbAct.getConfidence();
String mostProbActName = getActivityName(mostProbAct.getType());
Intent i = new Intent("com.xxx.abc.ACTIVITY_RECOGNITION_DATA");
i.putExtra("act", mostProbActName);
i.putExtra("confidence", confidence);
Log.e("ARS", mostProbActName + "," + confidence);
//sendBroadcast(i);
} else
Log.e("ARS", "Intent had no ActivityRecognitionData");
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tigerblood.com.node" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<service android:enabled="true" android:name="com.xxx.abc.ActivityRecognitionIntentService"></service>
<activity
android:name="com.tigerblood.node.Dashboard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Categories

Resources