How to pass BroadcastReceiver content to an Activity within same Java class - android

i working on a custom dailer. So far i am able make the user select the dailer he wants to use but when he chooses my dailer the number he wants to call is not dailed; instead my activity is shown.
I want it to show make the call based on the selected number and show my activity.
public class myActivity extends TabsActivity {
private OneActivity bb;
private String oldNumber2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
class OneActivity extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
final String Number1 = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, Number1, Toast.LENGTH_LONG).show();
Intent dial = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + Number1));
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dial);
}
}
When i checked the log, i found that the phone number is loaded into the BoradcastReceiver but not dailed out. Please Help

Try this
Intent dial = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + Number1));
dial.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dial);
Add the following to manifest
<uses-permission android:name = "android.permission.CALL_PHONE"/>

you can use setter/getter methods for such purpose.
see this example, first create a separate class file
public class passData
{
private String number;
public void setNumber ( String number )
{
this.number = number;
}
public String getNumber ()
{
return number;
}
}
Now you need to set your Number1 variable in to this class's method using set method, and you can get its value in to any other class or in activity, from whole project.

Related

Get variable from MainActivity in OnHandleIntent

I´m pretty new in android. I have made communication between two Apps with BroadcastReceiver and intentServices .
The thing is, I want to send information to the app2 from app1. In app1 I need to access a variable which is in MainActivity.class , I need to send it to servicev.class (the service where the intent is handled) but the variable "res" is null when I access it, why does that happen? (App2 calls app1 onHandleIntent and it breaks in res.getOtp() ) I try to create an extra setter getter class and also an intent but getIntent() does not work inside onHandleIntent... how can I achieve to pass res.getOTP (string) ? I really dont want to use SQLite
servicev:
public class servicev extends IntentService {
private static final int RESULT_OK = 1;
protected ResultReceiver mReceiver;
public servicev() {
super("yeah");
}
#Override
protected void onHandleIntent(Intent intent) {
//I receive here the intent from app2 and I need to response with res.getOTP()
helper h = new helper();
String val = intent.getStringExtra("foo");
Intent in = new Intent("com.banorte.bem.movil.veriToken.SendBroadcast");
in.putExtra("resultCode", this.RESULT_OK);
in.putExtra("resultValue", "My Result Value. Passed in: " + h.getRes().getOtp()); //h here is null... setter and getter approach does not work... maybe sqlite could work but it is necesary?
sendBroadcast(in);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
VTTokenAPI api;
TextView textView;
Button button;
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidSetup.getInstance().init(this);
helper h = new helper();
api = new VTTokenAPI("FFFFFF");
res = api.getStatus();
res.getOtp(); //correct value
h.setRes(res);
setContentView(R.layout.activity_main);
}
}
helper:
public class helper {
public VTResult getRes() {
return res;
}
public void setRes(VTResult res) {
this.res = res;
}
VTResult res;
}
You are trying to instantiate a new MainActivity which is not the same as the running activity but a new instance.
If you need your IntentService to be able to get data from a running Activity you have options such as using SharedPreferences or SQLite. Instead of keeping the data in memory try to persist it in some database in the onCreate and then try to read it from the storage during handleIntent

Static initializer per Activity (just like Fragment)

We are encouraged to use static initializer (a.k.a. the newInstance() pattern) per Fragment when we are passing arguments. In case of Activity, there is no mentioning of such. And every time we are going to start an activity, we have to first create an Intent first, like below:
public class FirstActivity extends Activity {
...
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
...
}
And if there are some parameters we would like to pass, this gets even more complicated, since we need to give each parameter a name, like below:
public class FirstActivity extends Activity {
...
int age = 10;
int count = 20;
String message = "hello";
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Age", age);
intent.putExtra("Count", count);
intent.putExtra("Message", message);
startActivity(intent);
...
}
and in the SecondActivity we should retrieve these parameters with the same name:
public class SecondActivity extends Activity {
...
int mAge;
int mCount;
String mMessage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAge = getIntent().getIntExtra("Age", 0);
mCount = getIntent().getIntExtra("Count", 0);
mMessage = getIntent().getStringExtra("Message");
}
...
}
Furthermore, these names we have used, "Age", "Count" and "Message" is hard-coded and error-prone. Most of the time we use a helper class, called something like IntentExtraKeys and use names from that class, like below:
public class IntentExtraKeys{
public static final String AGE_KEY = "age_key";
public static final String COUNT_KEY = "count_key";
public static final String MESSAGE_KEY = "message_key";
}
and in the activities:
public class FirstActivity extends Activity{
...
intent.putExtra(IntentExtraKeys.AGE_KEY, age);
...
}
and
public class SecondActivity extends Activity{
...
mAge = getIntent().getIntExtra(IntentExtraKeys.AGE_KEY, 0);
...
}
Instead of this, we could have something like below:
public class FirstActivity extends Activity{
....
SecondActivity.startActivity(this, age, count, message);
...
}
and
public class SecondActivity extends Activity{
...
private static final String AGE_KEY = "age_key";
private static final String COUNT_KEY = "count_key";
private static final String MESSAGE_KEY = "message_key";
public static void startActivity(Context context, int age, int count, String message){
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(AGE_KEY, age);
intent.putExtra(COUNT_KEY, count);
intent.putExtra(MESSAGE_KEY, message);
context.startActivity(intent);
}
...
}
This way, we save ourselves from writing code for creating an Intent every time we want to start the activity and if we are going to pass some parameters, we don't need to give them name. Only the activity we are starting knows their name, and it looks a lot cleaner, just like in fragments.
Is this bad design? Why is this uncommon?
The static initializer pattern is used in fragments because even though you instantiate the fragment yourself for the first time the default constructor must exist so the platform can instantiate it again on it's own when the activity is rebuilt because of a configuration change.
Activities on the other hand are always instantiated by the system and they must not need any special factory method nor constructor in order to retain their ability to be exported as intents for use by other apps and the system itself; that's why static initializers don't make a whole lot of sense on Activities. They are quite valid though and you can use them if you want but they might complicate having custom initialization code for activities that perform the same function in various slightly-different ways and they create a false sense of coupling.
For fragment
There are some reasons to use static function to create Fragment
Having single point to create Fragment instances. This makes sure the multi Fragment initializing having the same input arguments handling, etc.
It helps developers avoid to create Non-static Nested fragment. Fragment & Activity must be de-coupling.
The utility function can be invoked multi times. For example: The fragment is being used in TabLayout, ViewPager.
For Activity
You can create utility like you did. No problem. It is hard to say it is bad code or uncommon code.
If you will use the function More than one Or the Activity has input arguments. You can create the Utility function like you did.

Intent's intended class can't read extended information from said intent

I am trying to send information from my main activity class to another class in my app package. The information is used to update an AlertDialog automatically. Here is the code I've been working with:
//This is in MainActivity.class
//Tests to see if SyncDialog will update itself with new intents.
public void testLoop() {
int n = 0;
Intent intent = new Intent(this, SyncDialog.class);
while (n != 10) {
intent.putExtra(TEST_NUMBER, n);
n++;
}
}
//This is in SyncDialog.class
//This method should get the int value from MainActivity
protected void onNewIntent(Intent intent) {
int n = intent.getIntExtra(TEST_NUMBER, 0);
showNextDialog(n);
}
TEST_NUMBER is defined as a public constant at the top of MainActivity, and I even tried importing MainActivity into SyncDialog.class.
Is there any way to fix this?
You will have to make it a static constant if you want to access it in the way you are attempting. In MainActivity:
public static String TEST_NUMBER = "test";
and in SyncDialog:
intent.getExtra(MainActivity.TEST_NUMBER, 0)

pass UI Controls from activity to a class

I stuck at this issue many times and I passed the problem in different ways and I'm not sure that I made it in the right way.
I simplified the problem in a the following example. I know that I can pass only the data to the class but I do want to pass the editText cause I have this problem with more difficult UI controls.
mainactivity.java
public class mainactivity extends Activity {
public EditText clickEditText;
int count =0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
newTxt();
}
public void newTxt() {
txt = new MyText(context);
txt.updateTextEdit("Main Activity");
}
}
myText.java
public class MyText
{
private Context _context;
// constructor
public MyText(Context context)
{
_context = context;
}
public void updateTextEdit(String str)
{
private EditText strEditText;
strEditText= (EditText)findViewById(_context.R.id.editTextClick); // ????
strEditText.setText(str + " and myTxt");
}
}
if you could explain me how to fix the updateTextEdit function. i passed the context of the main activity. How can I change the editText? Thank you very much!!!
If you really want to do this this way, you need to save a reference to Activity, not Context. Like this:
public class MyText
{
private Activity _activity;
// constructor
public MyText(Activity activity)
{
_activity= activity;
}
public void updateTextEdit(String str)
{
private EditText strEditText;
strEditText= (EditText)activity.findViewById(R.id.editTextClick);
strEditText.setText(str + " and myTxt");
}
}
and in newTxt() you will need to change:
txt = new MyText(context);
to:
txt = new MyText(this);
But wouldn't it be easier to just put this method inside your activity? Why do you want it in another class? If it really needs to be in another class, you could make that class an inner class of your activity and you would still have access to the activity's methods and member variables.
There's a similar question here
How to access Activity UI from my class?
You didn't say how you obtained the context, you should use this and get the mainactivity in the other class. not context.
then you can call runOnUIThread to perform UI updates.

Share the object on real-time, singeltond pattern

I simply have not found a solution to share a real-time data between the activitys. My first activity receives real-time object (type double, a random numbers). And i want to pas this numbers to second activity. It all works, only the second Activity shows only one time the data. I have to refresh the activity by going back to first activity and only then the second activity show the latest data. I implemented a Singelton pattern:
public class FirstActivity extends Activity{
public double xAxis;
public double yAxis;
public static FirstView instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int data1 = msg.arg1;
xAxis = (double) data1;
dataX.setText(String.valueOf(xAxis));
int data2 = msg.arg2;
yAxis = (double) data2;
dataY.setText(String.valueOf(yAxis));
}
};
secondview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(nextScreen);
}
});
}
public static void initInstance(){
if(instance == null)
{
instance = new FirstActivity();
}
}
public static FirstActivity getInstance(){
return instance;
}
}
SecondView class
public class SecondActivity extends Activity{
private double valueX;
private double valueY;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linegraph);
valueX = FirstActivity.getInstance().xAxis;
valueY = FirstActivity.getInstance().yAxis;
}
}
Application class
package com.bluetoothcomm;
import android.app.Application;
public class MyApplication extends Application {
#Override
public void onCreate(){
super.onCreate();
initSingeltons();
}
public void initSingeltons(){
FirstActivity.initInstance();
}
}
You may implement a background service capable of providing the real time data to Activity1 and also to Activity2. I am guessing that your problem ocurrs if you are passing data from Activity1 to Activity2 through an Intent with putExtras, on this way it will only do this at the moment you start Activity2.
I have found my problem and the solution is to use Application. Only this dose not solves my problem. The problem is that the static variable instance public static FirstView instance is bound to the class loader, the first class that initilize that. So when the static variable inside any class has been initilized by an Activity and when the second Activity is started the first Activity is destroyed, so this means the static variable is also uninitilized. Thats why the SecondActivity dose not gets the up to date data or real time data, it catches only static constant data.
I changed my code a littele bit with the combination of Singelton and Application, couse this way the static variable should never be uninitilized when SecondActivity is activated. But i still get the same results, the static variable instance is uninitilized when i swtich to Second Activity. I am doing somethink wrong, does any one sees it. I added my code.
#Max Rasguido, #Orabig
You should use the intent process. docs
How is your data supposed to change when activity2 is shown, if you say that it's received by activity1 ?
However, I would use a preference, or an attribute of your application class (which is a singleton itself), but you give too little informations to fully understand your needs...

Categories

Resources