How to run startActivity from outside of the main activity - java

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.

Related

Call a Function in a OnPreferenceClickListener

I am trying to call a function in a OnPreferenceClickListener which is defined in a another class. Since I have not managed to initialisation an interface in OnPreferenceClickListener. I have given an example code below:
public void onCreatePreferences(Bundle bundle, String s) {
ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(#NonNull Preference preference) {
callFunctionInMainActivity();
return false;
}
});
}
How i can call a function witch is implement in a another class?
Thank you very much
Rene
You can implement an intent for this. Where you send a broadcast from your OnPreferenceClickListener class and implement a broadcast received in the other class to listen for this intent and invoke the method that you want. Here is an example:
public void onCreatePreferences(Bundle bundle, String s) {
ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(#NonNull Preference preference) {
sendBroadcast(new Intent(Constants.ACTION_STOP_MAIN_SERVICE));
return true;
}
});
}
In your other class:
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(action.equalsIgnoreCase(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE)){
finishAffinity();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE));
}
#Override
protected void onDestroy() {
unbindService(mConnection);
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}

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

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);
}
...
}

load 100% data using services while displaying splash screen

I have an Android App, which shows a "Splash Screen" for 3 seconds. After that, the MainActivity gets loaded.
Unfortunately the MainActivity takes additional ~4 seconds to load. On first startup even longer. However when the App is loaded, everything runs smooth.
I am using Async-Task for this, but desired result is not obtained and sometimes app crashes. Can someone help me please?
SplashScreen.java
public class SplashScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Fetchdata().execute();
}
private class Fetchdata extends AsyncTask {
#Override
protected Void doInBackground(Void... voids) {
Intent intent = new Intent(SplashScreen.this,FetchApiService.class);
startService(intent);
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return null;
}
#Override
protected void onPostExecute(Void result){
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onDestroy(){
super.onDestroy();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Some heavy processing
//starting services
Intent intent = new Intent(this,FetchApiService.class);
startService(intent);
}
}

Proper way of calling Activity Method from recycler adapther in Android?

I need to call an Intent from the onBindViewHolder of the recycler adapter , on a click event from one of the views in the ViewHolder. I am unable to do so directly ..
public void onBindViewHolder(MyAdapter.MyViewHolder viewHolder, int i) {
viewHolder.button.setonClickListener(new View.onClickListener(
#Override
onClick(View v) {
Intent i=new Intent();
i.setAction("Intent.ACTION_CALL");
i.setData(Uri.parse("tel:1234567890"));
startActivity(i);
}
));
}
This did not work. It kept throwing error. I then created a public method in the Activity with the same code. Passed Activity context in the Adapter constructor. Then called the Method as follows from button click event.
((MyActivity)context).makePhoneCall("1234567890");
This did the trick. But i feel there should be a better method of doing this.
As i am primarily from C background, i am not sure.
So my question is there a better or more proper way to do this , according to Java programming conventions.
If you need to call another activity via Intent, you can use any view's Context:
v.getContext().startActivity(i);
I think this is a correct method.
Another way is to implement a listener in the recycleradapter and listen it in the activity.
So in the adapter:
public class RecyclerAdapter .... {
private MyClickListener listener;
public void onBindViewHolder(MyAdapter.MyViewHolder viewHolder, int i) {
viewHolder.button.setonClickListener(new View.onClickListener(
#Override
onClick(View v) {
listener.onClicked(true);
}
));
public void setMyClickListener(MyClickListener listener) {
this.listener = listener;
}
}
//create MyClickListener.class
public interface MyClickListener {
public void onClicked(boolean status);
}
In your Activity:
public class MainActivity ... implements MyClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
adapter.setMyClickListener(this);
}
#Override
onClick(boolean status) {
if (status){
Intent i=new Intent();
i.setAction("Intent.ACTION_CALL");
i.setData(Uri.parse("tel:1234567890"));
startActivity(i);
};
}
}
Try this
In your Adapter:
Activity mContext;
public FollowersAdapter(Activity mContext) {
this.mContext = mContext;
}
//And then your click in onBindViewHolder
holder.linear_user.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("linear click>>>>>>>>>>>>");
Intent ToImage = new Intent(mContext, UserData.class);
ToImage.putExtra("user_id", data.get(position).getFollower_id());
mContext.startActivity(ToImage);
}
});

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);
}
}

Categories

Resources