private void Foo() {
// progressDialog = ProgressDialog.show(this, "", "Loading...");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(this, TodoDetailActivity.class);
i.putExtra("driveUri", file.getAlternateLink());
startActivityForResult(i, SAVE);
}
});
t.start();
}
I get this error:
The constructor Intent(new Runnable(){}, Class<TodoDetailActivity>) is undefined
I have tried to change to explicit declaration, but it didn't help
android.content.Intent i = new android.content.Intent.Intent(this, TodoDetailActivity.class);
though I know there is such a signature from past use.
This line
Intent i = new Intent(this, TodoDetailActivity.class);
Is inside the Anonymous Class Runnable.
Change it to
Intent i = new Intent(getBaseContext(), TodoDetailActivity.class);
Try to change
Intent i = new Intent(this, TodoDetailActivity.class); in
Intent i = new Intent(getActivity(), TodoDetailActivity.class); if you are in a Fragment, or
by
Intent i = new Intent(yourActualActivity.this, TodoDetailActivity.class); if you are in an Activity
Intent need context (of some activity of application), but in thread this (in new Intent(this, TodoDetailActivity.class);) passes the context of you thread, which is not an activity.
so just getApplicationContext() or context of activity form which thread is started like MainActivity.this
You are using Itennt() inside the Thread, so this means thread's object, which is wrong for Intent's syntax.
You should modify your code as follows,
private void Foo()
{
// progressDialog = ProgressDialog.show(this, "", "Loading...");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), TodoDetailActivity.class);
i.putExtra("driveUri", file.getAlternateLink());
startActivityForResult(i, SAVE);
}
});
t.start();
}
Related
I'm new to Android programming so I might miss something important.
What I want to do is to finish the current activity (ActivityB) and the previous activity (ActivityA).
And the users can switch between ActivityA and ActivityB using FLAG_ACTIVITY_REORDER_TO_FRONT. Now I want to finish ActivityB and the previous ActivityA and start new ActivityA.
However, seems like the previous ActivityA is still running even after finishing ActivityB.
Code is like this.
ActivityA
private void startActivityB() {
Intent intent =
new Intent(ActivityA.this, ActivityB.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
ActivityB
private void exitActivityB() {
Intent intent =
new Intent(ActivityB.this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
private void onBackPressed() {
// finish ActivityB and the previous ActivityA
Intent intent =
new Intent(ActivityB.this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
What am I wrong with this? How can I finish the previous ActivityA and start new ActivityA?
Try following way
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
Try this one:
#Override
private void onBackPressed() {
// finish ActivityB and the previous ActivityA
Intent intent =
new Intent(ActivityB.this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Try this code
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
Im making a quiz game with questions on diferent topics
For Example i have activities for these topics: Flags, Capitals, Population, Economy, Continent, etc.
And i have one single ResultActivity to obtain the Score of the quiz.
The ResultActivity has a PLAY AGAIN button.
On the FlagsActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "FlagsActivity");
startActivity(intent);
On the CapitalActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "CapitalActivity");
startActivity(intent);
etc.....
On the ResultActivity i have this code:
activity = getIntent().getStringExtra("NAME_ACTIVITY");
public void playAgain(View view){
if(activity.equals("FlagsActivity")){
Intent intent = new Intent(getApplicationContext(), FlagsActivity.class);
startActivity(intent);
}
if(activity.equals("CapitalActivity")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
if(activity.equals("PopulationActivity")){
Intent intent = new Intent(getApplicationContext(), PopulationActivity.class);
startActivity(intent);
}
if(activity.equals("EconomyActivity")){
Intent intent = new Intent(getApplicationContext(), EconomyActivity.class);
startActivity(intent);
}
if(activity.equals("ContinentActivity")){
Intent intent = new Intent(getApplicationContext(), ContinentActivity.class);
startActivity(intent);
}
}
Basically im sending an Intent with a String containing the name of the activity, then on the Result Activity evaluating with "if" the String = That activity name, start the activity.
What i want to do is someting like this:
On the Flags Activity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(FlagsActivity.class);
startActivity(intent);
On the CapitalActivity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(CapitalActivity.class);
startActivity(intent);
On the Result Activity:
activity = getIntent();
public void playAgain(View view){
Intent intent = new Intent(getApplicationContext(), activity);
startActivity(intent);
}
So that i can create as many quiz activities without having to create an "if" statement on the ResultActivity for it to work.
You can pass the class name as a string and use reflection to look up a class object for that type. Something like this:
Class classToLoad = Class.forName(getIntent().getStringExtra("NAME_ACTIVITY"));
Intent intent = new Intent(getApplicationContext(), classToLoad);
startActivity(intent);
I would pass the fully qualified class name to avoid errors.
You could pass the String of activity name to the Result activity, and get its corresponding class name using reflection:
String strActivity = "com.package.FlagsActivity";
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("activity_name", strActivity );
startActivity(intent);
String activityName = getIntent().getStringExtra("activity_name");
Class<?> myClass = Class.forName(activityName );
Intent myIntent = new Intent(getApplicationContext(), myClass);
Something like this.
In the Results Activity
public static void toActivity(Context context, final Class ActivityToOpen){
//whatever awesome code you would like to perform
Intent intent = new Intent(context, ActivityToOpen);
startActivity(intent);
}
In the originating Activity (Flags Activity for example)
ResultsActivity.toActivity(FlagsActivity.this, FlagActivity.class);
Check for typos... I kinda winged this :)
You should be able to call from any originating Activity without if statement.
When you receive the data
String activity;
Bundle bundle = getIntent().getExtras();
if (bundle != null){
activity = bundle.getString("NAME_ACTIVITY");
}
As the step value of a variable of an Activity for a TextView other Activity? Can Help?
Thank you!
((See explanation on the picture))
Intent activityTwo = new Intent(this, Activity2.class);
activityTwo.putIntExtra("key", sumSettlement);
startActivity(activityTwo);
Now, in Activity2:
if(getIntent() != null) {
textView.setText(String.valueOf(getIntent.getExtra("key"));
}
You can use of local broadcast receiver.
First register receiver in Activity B
//in onCreate Method
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event-name"));
// It will be called whenever an Intent
// with an action named "my-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
// show this message in textview
}
};
In Activity A
//broadcast this
Intent intent = new Intent("my-event-name");
intent.putExtra("message", Integer(sumSettlment).toString());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
the easiest way is to use Intent: in first Activity
Intent intent =new Intent(CurrentClass.this,DisClass.class);
intent.putExtra("myTextValue",textView.getText().toString());
startActivity(intent);
in the dist activity do the following :
String myValue=getIntent().getExtra().getString("myTextValue");
textView.setText(myValue);
I need to keep broadcast receiver running all the time after app has been started.
Here is the code that registers this receiver in the application
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenEventsReceiver();
registerReceiver(mReceiver, filter);
And code for receiver
public class ScreenEventsReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
Log.d("ScreenEventReceiver", "ON");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
Log.d("ScreenEventReceiver", "ON");
}
}
}
You can use a service
In main app start/stop the service
Intent service = new Intent(context, MyService.class);
context.startService(service);
...
Intent service = new Intent(context, MyService.class);
context.stopService(service);
service
public class MyService extends Service
{
private static BroadcastReceiver m_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
unregisterReceiver(m_ScreenOffReceiver);
m_ScreenOffReceiver = null;
}
private void registerScreenOffReceiver()
{
m_ScreenOffReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "ACTION_SCREEN_OFF");
// do something, e.g. send Intent to main app
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(m_ScreenOffReceiver, filter);
}
}
Accepted answer is not an actual answer i think. I will explain what the issue. I think you are testing your app in the Huawie, Oppo, Vivo, Xiomi,asus....... or some devices. With that devices if we close the application they will also close our broadcast receivers. So thats the problem.(To check that use a with pixel nexus emulator). I will explain how to resolve this.``
we would add our app to the protected app list. OS only allow to them to continue broadcast receiver activities.(Copy this array declaration to your code)
private static final Intent[] POWERMANAGER_INTENTS = {
new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
new Intent().setComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")),
new Intent().setComponent(new ComponentName("com.htc.pitroad", "com.htc.pitroad.landingpage.activity.LandingPageActivity")),
new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.MainActivity"))};
Put these code to your onCreate Method. Here i used shared preference for check it only first time of the app open.
`
final SharedPreferences.Editor pref = getSharedPreferences("allow_notify", MODE_PRIVATE).edit(); pref.apply(); final SharedPreferences sp = getSharedPreferences("allow_notify", MODE_PRIVATE)`;
if(!sp.getBoolean("protected",false)) {
for (final Intent intent : POWERMANAGER_INTENTS)
if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert Title").setMessage("Alert Body")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(intent);
sp.edit().putBoolean("protected",true).apply();
}
})
.setCancelable(false)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create().show();
break;
Be careful if you are using Android 4.4.x as there is a bug which kills background services when closing the app. I was testing my app in Android 4.4.2 and I had the same problem. Here there is a detailed explanation:
http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-is-on-the-way/
You cannot receive some broadcast events through components declared in manifest.
These events are
ACTION_BATTERY_CHANGED
ACTION_CONFIGURATION_CHANGED
ACTION_SCREEN_OFF (You are playing with this event)
ACTION_SCREEN_ON (You are playing with this event)
ACTION_TIME_TICK
Reference https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_ON
So in your specific events,
you will have to create a Service & you will have to register your event explicitly in service onCreate() with with Context.registerReceiver().
For other events,
entry in manifest is sufficient.
If you declare BroadcastReceiver in the Manifest, it will always be active and be called even if the application is closed/stopped
You could start a service that is running in the foreground. That's the only way to ensure (mostly) that your app will get the events. There is still a chance that your foreground service could get killed in times of crazy memory pressure from the OS (so it's not foolproof). If you start a service in the foreground, the user will see a persistent notification to know that it is always running, though.
So the moral of the story is, do you really need to monitor the screen off/on events at all times? The reason that they force you to register a receiver not in the manifest is that they don't want people to always be monitoring these events and slowing down the device. What are you trying to accomplish?
The best way I found is the Foreground Services. I registered my BroadcastReceiver from my Service only under the onStartCommand() as I want my service needs to run always, I returned START_STICKY
This way, my broadcast receiver survives even after terminating the app from stack.
Used below code in my service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("rht", "Received start id " + startId + ": " + intent);
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
This is how I started my service
Intent serviceIntent = new Intent(this, SpeechServiceForeground.class);
ContextCompat.startForegroundService(this, serviceIntent);
Does anyone know how to call an activity when a service is destroyed? I have tried with the code below, but it doesn't work and geves me a force close.
#Override
public void onDestroy() {
Intent goToAbout = new Intent(this, AboutForm.class);
startActivity(goToAbout);
}
Anyone have an idea?
public void onDestroy(){
Intent myIntent = new Intent(this,
MyACtivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);
}