Launch Invisible Activity To Obtain Permissions For Service - android

thanks to everyone for reading. here's an application that has a boot-receiver so it launches upon starting android device:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i1 = new Intent(context, SplashActivity.class);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i1.putExtra("permission_for_service","");
context.startActivity(i1);
}
SplashActivity.class is implemented to obtain permissions before launching MainActivity.class.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkAllRequestedPermissions()) {
ActivityCompat.requestPermissions(this, allRequestedPermissions, MY_PERMISSIONS_REQUEST);
}
else {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
private boolean checkAllRequestedPermissions() {
for (String permission : allRequestedPermissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
What I'm trying to do is to prevent launching a user interface on boot-up by using a service instead:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (!checkAllRequestedPermissions()) {
ActivityCompat.requestPermissions(this, allRequestedPermissions, MY_PERMISSIONS_REQUEST);
} else {
if (getIntent().hasExtra("permission_for_service")) {
//service init
if (!isServiceRunning(SchedulerService.class)) {
startService(new Intent(this, SchedulerService.class));
}
finish();
} else {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
Unfortunately, this crashes on BOOT_COMPLETE. Any ideas on how to make it work? Thanks a million

Related

Load app/activity when phone wakes up from sleep

I have an android activity, but when the phone goes to sleep(meaning I leave the phone there for a few seconds and then the screen goes black) and I turn it back on, the activity/app disappears(it's still active but i have to press the overview button to come back to the activity/app). How do I get it to come back automatically?
What I want to do is when the phone goes to sleep, when I turn it back on, the app/activity is there as it was when it went to sleep. I've checked up onResume, BroadcastReceivers, WakeLock, KeepScreenOn, Services, but I know I'm not doing it right.
OnResume doesn't work, WakeLock doesn't work, KeepScreenOn, just keeps the screen on and doesn't allow the phone to sleep, I haven't tried Services and BroadcastReceivers, but I thought I should ask here first.
Please help. Thanks.
I have MainActivity.java which opens initially and then starts AdminAddMerchantActivity.java. AdminAddMerchantActivity.java is a navigationView that starts 4 fragments including TimeFragment.java which has a tab layout, a view pager and a pager adapter. TimeFragment.java starts 5 fragments including PriceFragment.java.
Below is the activities lifecycle methods below.
MainActivity.java:
...
#Override
protected void onPause() {
super.onPause();
Log.d("state", "Pausing Main");
// Handle countdown stop here
}
#Override
protected void onResume() {
super.onResume();
Log.d("state", "Resuming Main");
currentActivity = sharedPreferences.getString(CURRENT_ACT, "main");
if(mAuth.getCurrentUser() != null)
{
if(currentActivity.equals("confirmFinalOrder"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, ConfirmFinalOrderActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("merchantDetails"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, MerchantDetailsActivity.class);
intent.putExtra("mid", sharedPreferences.getString("merchantid", ""));
startActivity(intent);
finish();
}
else if(currentActivity.equals("navigation")) {
isResumed++;
Intent intent = new Intent(MainActivity.this, NavigationActivity.class);
fragment = sharedPreferences.getString("fragment", "Find Food");
intent.putExtra("activity", fragment);
startActivity(intent);
finish();
}
else if(currentActivity.equals("adminaddnewmerchant"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, AdminAddNewMerchantActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("searchmerchants"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SearchMerchantsActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("settingsuser"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("settingsmerchant"))
{
isResumed++;
Intent intent = new Intent(this, SettingsMerchantActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("sellerregistration"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SellerRegistrationActivity.class);
startActivity(intent);
finish();
}
}
else{
if(currentActivity.equals("sellerregistration"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SellerRegistrationActivity.class);
startActivity(intent);
finish();
}
else if(!sharedPreferences.getString("current activity", "main").equals("login user")
&& !sharedPreferences.getString("current activity", "main").equals("login merchant"))
{
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
Paper.book().write(Prevalent.RememberMeMerchant, "false");
Paper.book().write(Prevalent.emailKey, "UserEmail");
Paper.book().write(Prevalent.passwordKey, "UserPassword");
}
}
// Handle countdown start here
}
#Override
protected void onStop() {
super.onStop();
Log.d("state","Stopping Main");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("state", "Destroyed Main");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("state", "Restarted Main");
}
#Override
protected void onStart() {
super.onStart();
Log.d("state", "Started Main");
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d("state", "onRestoreInstanceState Main");
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("state", "onSaveInstanceState Main");
}
//if the user
#Override
public void onBackPressed() {
Log.d("state", "back login");
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
}
...
AdminAddNewMerchantActivity.java:
...
#Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
// Get the Camera instance as the activity achieves full user focus
//if (mCamera == null) {
//initializeCamera(); // Local method to handle camera init
//}
}
...
PriceFragment.java:
...
#Override
public void onDestroy() {
super.onDestroy();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("scrollPrice", scrollView.getScrollY());
editor.commit();
}
#Override
public void onResume() {
Log.d("onResume", "Resumed");
super.onResume();
}
...
TimeFragment.java:
...
#Override
public void onResume() {
super.onResume();
}
...
The default Android behavior should do this automatically...
Are you doing something special on the onPause or onStop methods?
And if you're not, can you create a new project via Android Studio and test to see if this behavior persists on the new app?

How can i avoid app forcefully closing error

App is designed in the way that it will check for Firebase ID on launching. If not,he will be taken to a Registration Activity. If already registered, he will be taken to home activity instead.
Along with this I have configured for click_action of push notification in launcher activity.
On the first opening, user can complete registration completes and open homeactivity as well. But when App is once closed and opened, App crash with message "forcefully closed".
When i checked in the Logcat, error showing is "null object at string line switch (clickaction){ .
please advise how can i rectify this.
public class MainActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
String clickaction;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth=FirebaseAuth.getInstance();
FirebaseUser currentuser1 =firebaseAuth.getCurrentUser();
if (getIntent().getExtras() == null){
if (currentuser1!= null) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(homeIntent);
finish();
}
}, SPLASH_TIME_OUT);
}
else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent regintent = new Intent(MainActivity.this, Registration_Activity.class);
startActivity(regintent);
finish();
}
},SPLASH_TIME_OUT);
}
}
else
{
clickaction = (String) getIntent().getExtras().get("openactivity");
Intent intent=new Intent();
switch (clickaction){
case "Act1":
intent=new Intent(this, Activity1.class);
break;
case "Act2":
intent=new Intent(this, Activity2.class);
break;
case "Act3":
intent=new Intent(this, Activity3.class);
break;
default:
intent = new Intent(this, HomeActivity.class);
break;
}
startActivity(intent);
}
}
}

BroadcastReceiver is receiving like 1 of 10 intents

On button click I am opening activity(ActionListActivity) and sending intent to IntentService (later this service sends broadCast intent to ActionListActivity). But I am usually receiving only the first intent after launch. Is it real that intent is sent before the receiver is registred?
I want to get data providet by the intentService, and update my UI using it.
Scheme Activity->IntentService->BroadCastReceiver inside ActionListActivity
Activity:
private void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.actions:{
Intent myIntent = new Intent(this, ActionListActivity.class);
this.startActivity(myIntent);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
Intent dataIntent = new Intent(this, DatabaseWorkIntentService.class);
dataIntent.putExtra(Utils.INTENT_SERVICE_INVOKE, Utils.READ_ACTIONS_DATA);
startService(dataIntent);
progressDialog.dismiss();
}
}
}
IntentService:
private void readActionData(){
Log.e("read actions data","data");
List<Action> actionList;
actionList = Action.listAll(Action.class);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Utils.READ_ACTIONS_DATA);
broadcastIntent.putParcelableArrayListExtra(Utils.READ_ACTIONS_DATA, (ArrayList<? extends Parcelable>) actionList);
sendBroadcast(broadcastIntent);
}
ActionListActivity:
public class ActionListActivity extends BaseActivity {
boolean mIsReceiverRegistered = false;
DataBroadcastReceiver receiver;
TextView someTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_list_activity);
this.initToolbarAndDrawerWithReadableName(getString(R.string.our_actions));
someTv = (TextView)findViewById(R.id.someTv);
}
public void someTvTest(Action action){
someTv.append(action.getName());
Log.e("data",action.getName());
}
#Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mIsReceiverRegistered) {
if (receiver == null)
receiver = new DataBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Utils.READ_ACTIONS_DATA);
receiver.setMainActivityHandler(this);
registerReceiver(receiver, filter);
mIsReceiverRegistered = true;
}
}
}
class DataBroadcastReceiver extends BroadcastReceiver{
ActionListActivity activity = null;
ArrayList<Action> list;
public void setMainActivityHandler(ActionListActivity main){
activity = main;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e("reciever","reciev");
list = intent.getParcelableArrayListExtra(Utils.READ_ACTIONS_DATA);
for (Action action:list){
if(activity!=null) {
activity.someTvTest(action);
}
}
}
}
You start activity and service async.
You need to start service inside ActionListActivity and wait for response.

Killing activity in android

Here is the code for back button. I want to kill other activities by back button but its not working in one activity, but I have other activities and without one activity its working fine. Please help me out.
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Might be this code will help you:
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
You have to set Flags according to API level :
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
if(Build.VERSION.SDK_INT >= 11)
{
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
else
{
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(intent);
Hope it helps ツ
You can set android:noHistory="true" in activities tag in AndroidManifest.xml which you don't want to save in stack.
Try to define one local broadcast receiver on top most parent activity or base activity :
private final class KillReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
Intialize and register broadcast receiver in onCreate() and unregister in onDestroy() on top most parent activity or base activity :
private KillReceiver clearActivityStack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
clearActivityStack = new KillReceiver();
registerReceiver(clearActivityStack, IntentFilter.create("clearStackActivity", "text/plain"));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(clearActivityStack);
}
Now call broadcast receiver when wan to clear all previous activity :
public void onClick(View v) {
Intent clearIntent = new Intent("clearStackActivity");
clearIntent.setType("text/plain");
sendBroadcast(clearIntent);
Intent intent = new Intent(getApplicationContext(),SomeActivity.class);
startActivity(intent);
}

How to start Activity for result from IME

I'm developing an app that should return some text to the app that started the intent.
But the app that starts the intent is a IME/soft Keyboard. So StartActivityForResult is not available because an IME is a service.
How can I achieve this?
What I got so far:
Keyboard:
final Intent intent = new Intent("com.example.helloworld.GETTEXT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.putExtra("keyboard", true);
startActivity(intent);
Other App:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras == null){
return;
} else {
finish();
}
}
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("test", "PASSED");
setResult(RESULT_OK, data);
super.finish();
}
You can use ResultReceiver.
Look at this example, it's pretty clear explains how it works.
You could use a ResultReceiver for this is think.
ResultReceiver lReceiver = new KeyboardResultReceiver(aListener);
final Intent intent = new Intent("com.example.helloworld.GETTEXT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
intent.putExtra(EXTRA_RESULT_RECIEVER, lReceiver);
intent.putExtra("keyboard", true);
startActivity(intent);
private static final class KeyboardResultReceiver extends ResultReceiver {
public FileUploadResultReceiver() {
}
#Override
protected void onReceiveResult(int aResultCode, Bundle aResultData) {
//Do your thing here you can also use the bundle for your data transmission
}
}

Categories

Resources