Is there a solution that access MainActivity from other Activity class? - java

I want to call function below.
mobileView.loadUrl("javascript:setUserId () ");
And mobileView is in MainActivity.
public class MainActivity extends AppCompatActivity {
private WebView mobileView;
}
I want to call function above after SecondActivity is finished.
public class SecondActivity extends AppCompatActivity {
...
private void getUserId () {
...
finish();
}
}
And SecondActivity starts from AReceiver.
public class AReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
...
Intent i = new Intent(context, SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
context.startActivity(i);
}
}
And AReceiver is called by below code...
class MainActivity {
...
private void userId () {
...
intent = new Intent(MainActivity.this, AReceiver.class);
pendingIntent = PendingIntent.getBroadcast(
MainActivity.this,
alarmID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
alarmManager.set(
AlarmManager.RTC_WAKEUP,
mCalendar.getTimeInMillis(),
pendingIntent
);
...
}
...
}
But I don't know how to access mobileView from SecondActivity.
Is there any solution?
What I've tried...
change variable from
private webView mobileView
to
public webView mobileView
2.
call from SecondActivity Using
MainActivity.mobileView
It doesn't work for me.

You can try This option
Intent
..............
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
it work only if you start the second activity from main activity

I solved this problem using local broad cast manager! :D
Thank you #Shripad Jadhav who help this answer.
Below description is solution! Hope it helpes somebody. :D
MainActivity.java
public class MainActivity extends AppCompatActivity {
private WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LocalBroadcastManager.getInstance(this)
.registerReceiver(mBroadcastReceiver, new IntentFilter("webview-filter"));
...
}
...
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mv.loadUrl("javascript: loadMainData ()");
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private void someFunction () {
sendMessage ();
}
...
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("webview-filter");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
...
}

Related

Intent problem: how to use MainActivity from another class "Adapter" to pass data to SecondActivity

This is in Adapter.Java
public void onClick(View v) {
String name=listItemData.get(i).getName();
Intent intent = Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("NAME", name);
}
I have now idea how to use MainActivity.this when I'm not in MainActivity class..
Try following code.
Solution 1
You have to pass context while you initialized Adapter in MainActivity.
In MainActivity.this:
XyzAdapter adapter = new XyzAdapter(MainActivity.this, .. ..)
In your Adapter:
private Context mContext;
public XyzAdapter(Context context .. ..){
mContext = context;
}
And then you can do like below:
public void onClick(View v) {
String name=listItemData.get(i).getName();
Intent intent = Intent(mContext, SecondActivity.class);
intent.putExtra("NAME", name);
mContext.startActivity(intent);
}
Solution 2
Another option is interface
Create one interface like below:
public interface AdapterInterface {
public void buttonPressed();
}
Now in your adapter:
AdapterInterface buttonListener;
public XyzAdapter(Context context, AdapterInterface buttonListener)
{
super(context,c,flags);
this.buttonListener = buttonListener;
}
public void onClick(View v) {
buttonListener.buttonPressed()
}
In your Activity:
AdapterInterface buttonListener;
public MainActivity extends AppCompactActivity implements AdapterInterface{
in onCreate
buttonListener = this;
XyzAdapter adapter = new XyzAdapter(MainActivity.this, buttonListener .. ..)
#Override
public void buttonPressed(){
// here you have to do once your click perform
}
You can have a member variable of type Activity in your Adapter class (e.g. private Activity mActivity;) and pass your MainActivity instance to your Adapter class in the constructor of your Adapter class and assign it to mActivity. Some thing like this:
public Adapter(Activity activity) {
this.mActivity = activity;
}
Then in your onClick method:
public void onClick(View v) {
String name=listItemData.get(i).getName();
Intent intent = new Intent(mActivity, SecondActivity.class);
intent.putExtra("NAME", name);
mActivity.startActivity(intent);
}

Toggle Background/Foreground Modes

I'm trying to make it so that when you press the power button to turn off the android, my app goes into background mode. When you press the power button to turn on the android, my app should go into foreground mode.
The error I get is:
java.lang.RuntimeException: Error receiving broadcast Intent {
act=android.intent.action.SCREEN_ON flg=0x50000010 }
The error comes from the intent with FLAG_ACTIVITY_CLEAR_TOP
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver(MainActivity.this, this);
registerReceiver(mReceiver, filter);
moveTaskToBack(true);
}
}
Here's the BroadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, ScreenReceiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}
I'm using code from the following tutorial:
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
The mistake was passing ScreenReceiver.class instead of MainActivity.class into the intent. Here's the corrected version:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}

How to run startActivity from outside of the main activity

I have a MainActivity class which has a NotificationsListener (seperate class). When a notification appears, it calls my gethtml class. They both extend Activity but the startActivity in my gethtml class doesn't work... (If I copy and test this code in my MainActivity, it works fine)... Anyone have an idea why it isn't working?
This is the main class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
startService(new Intent(MainActivity.this, NLService.class));
Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
This is the notification listener:
public class NLService extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
new Thread(new Runnable() {
public void run(){
Looper.prepare();
int cangethtml = 1;
try{
if(cangethtml==1){
cangethtml = 0; //only runs once
new html();
}
}finally{Looper.loop();}
};
}).start();
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {}
}
This is the final class which doesn't open the website through the startActivity:
public class html extends Activity{
public html() {
try {
Intent i2 = new Intent("android.intent.action.MAIN");
i2.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
i2.addCategory("android.intent.category.LAUNCHER");
i2.setData(Uri.parse("https://wwww.google.com"));
startActivity(i2);
} finally{}
}
}
With reference to the developer's forum:
You should write
Context.startActivity(i2);
instead of
startActivity(i2);
Plus, make sure you don't forget to have a corresponding <activity> declaration in your package's AndroidManifest.xml.
For instance:
Check in AndroidManifest.xml for all the classes defined by you. You have:
<activity android:name="packageName.className"/>
If your html class is not defined in AndroidManifest.xml, you can not access the methods and layouts defined in it.
You need the context of the Activity. startActivity will be called in the context of Activity.

How to destroy previous activity when you jumped to next activity

I have activity A, having timer thread. after 5 sec it jumps to activity B via intent. how to destroy activity A when you are on activity B so that back button don't let you go back to activity A.
You have to clear the activity backstack.
intent = new Intent(this, Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
StartActivity(intent);
just call finish() when you make the intent from A to B
Try this...
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Waiting(5);
}
public class Waiting {
Timer timer;
public Waiting(int seconds) {
timer = new Timer();
timer.schedule(new WaitingTask(), seconds * 1000);
}
class WaitingTask extends TimerTask {
#Override
public void run() {
System.out.println("Hi, I'm waiting here!");
Intent intent = new Intent(MainActivity.this,
MainActivity1.class);
MainActivity.this.finish();
startActivity(intent);
timer.cancel();
}
}
}
}
MainActivity1.java
public class MainActivity1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
}
}

how to extract the string value in Android services from an activity?

how to extract the string value in Android services from an activity?
My activity has a edit text, the entered string must be received in my services.
TempLaunch.java :
public class TempLaunch extends Activity {
private EditText text;
private Button okbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.templaunch);
addListenerOnButton();
}
public void addListenerOnButton() {
text = (EditText) findViewById(R.id.edittext_newid);
okbtn = (Button) findViewById(R.id.button_newid);
okbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TempLaunch.this, "In Temp launch class ",Toast.LENGTH_SHORT).show();
Toast.makeText(TempLaunch.this, text.getText(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Toast.makeText(TempLaunch.this, "I am in Main activity class ",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
Intent i = new Intent(this, MusicService.class);
i.putExtra("DD_URL", text.getText().toString());
//startActivity(i);
}
}
MusicService.java
public class MusicService extends Service {
#Override
public void onCreate() {
super.onCreate();
String url = null;
Intent intent = getIntent();
String id = intent.getStringExtra("DD_URL");
System.out.println("Rosh :" + id);
Toast.makeText(MusicService.this, "I am in Service:"+ id,Toast.LENGTH_SHORT).show();
...
Please help me out with this regard.
Thanks in advance
You may use sendBroadcast(intent); which will broadcast the EditText from your Activity A.
Then you need to call onReceive(Context context, Intent intent) within your Service class. This method is called when the BroadcastReceiver is receiving an Intent broadcast, in your case will be sent from Activity A.
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// Do something
}
};
//Register your receiver in onResume:
#Override
protected void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
registerReceiver(receiver, filter);
}
//Unregister the receiver in onPause:
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}

Categories

Resources