I am creating a intent service,and inside this intent service I am creating new class like this:
public class ConnectionIntent extends IntentService {
final Connection connection=new Connection();
public ConnectionIntent() {
super("ConnectionIntent");
}
...
I am calling this service for multiple times.How can I create new Connection() class for once ? I mean if this service is calling for first create a new Connection() class if this service calling for secondly don't create new Connection() class use the old Connection() class.
How can I achive this ?
Save it as static variable in your App class, and do something like this:
public class App extends Application {
private static Connection connection;
public Connection getConnectionInstance() {
if (connection == null)
connection = new Connection();
return connection;
}
}
And in your intent service do:
((App)getApplication()).getConnectionInstance();
Don't forgot to declare this class as your application class.
<application
android:name="your.package.name.App"
android:label="#string/app_name"
android:theme="#style/AppTheme">
Related
I am trying to use a BroadcastReceiver as an inner class to track the network state but I got the exception in the title. What should I do to fix this problem?
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
setupData();
Log.d("Netowk Available ", "Flag No 1");
}
}
}
Your
inner Broadcast receiver must be static ( to be registered through Manifest)
OR
Non-static broadcast receiver must be registered and unregistered inside the Parent class
for this.
I was using an Inner broadcast reciver, without registering it within the class. Either make it static and register in Manifest , or Make it non static and register and unregister inside the parent class .
A non-static inner class cannot be registered via the AndroidManifest.xml. You can either:
Register it dynamically as outlined in this thread, and remove the empty constructor.
Or,
Make your inner class static, and register it in the AndroidManifext.xml.
just make your Receiver Class static like:
public [static] class ReceiverClass extends BroadcastReceiver
e~~I just meet that problem,and I refactor the class NetworkChangeReceiver to an another place
My Discovery class extends Service class. When I try to get its singletone from other class this way:
Discovery discovery = Discovery.getInstance();
I get a NullPointerException. This is the Discovery code:
public static Discovery getInstance(){
if (discovery == null){
discovery = new Discovery();
discovery.initDiscovery ();
}
Log.i(TAG, "get discovery instance");
return discovery;
}
public Discovery() {
}
private void initDiscovery(){
mDiscoveredDevices = new ArrayList<String>();
BluetoothManager bluetoothManager = (BluetoothManager) discovery.getSystemService(Context.BLUETOOTH_SERVICE);<--NullPointerException
....
}
This is not Android my friend.
To create a service you need to declare it in manifest:
<service
android:name=".DiscoveryService" />
After which you can instantiate it but never using operator new. Instead you need to call:
startService(context, new Intent(context, DiscoveryService.class);
There are other ways of firing a service intent but this will suffice for now.
The service's construction code should be placed at onCreate:
class DiscoveryService extends Service {
#Override
public void onCreate() {
service construction code here
}
}
And its request handling code in onStartCommand:
public int onStartCommand(Intent intent, int flags, int startId) {
handle incoming intent
}
Now, if you do need to access a service instance probably the simplest way
of achieving it would be to declare and maintain a static instance reference within
the service. Do it like this:
class DiscoveryService extends Service {
private static DiscoveryService inst; // <-----------------
public DiscoveryService getInstance() {
return inst;
}
#Override
public void onCreate() {
service construction code here
inst = this;
}
#Override
public void onDestroy() {
cleanup code here
inst = null;
}
}
This approach has its shortcomings, but unlike yours, it will work. Still use with care.
Finally - years of writing & reviewing Android code have led me to the conclusion
that what most novice developers want when they ask for Service, is in fact an IntentService..
Please read the docs and make sure you got your class right.
Good luck.
I have a function with an increment counter and I call it when the user click a button.
I want to make a new button when user press it call this function every second.
I used alarm manager and works fine.But when I try to call this function from broadcast receiver give me error because is not static.What can i do?
public class MyStartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Send ....",Toast.LENGTH_LONG).show();
//Intent service = new Intent(context, AlarmService.class);
//context.startService(service);
//String msg = intent.getStringExtra("data");
//String msg="data";
a1class.function1();
}
public void function1(){
counter++;
//Toast.MakeText( counter );
}
Either make function1() static or, assuming a1class is the class its in, create an instance of the class and call the function that way
a1class a1class = new a1class();
a1class.function1();
If you want to call a non static method you need a instance of the class to call it on.
You can make a static method that returns the instance like this
private static ClassName instance;
public static ClassName getInstance(){
if (instance == null){
instance = new ClassName();
}
return instance;
}
You can also set the instance in the onCreate method.
I just changed my external broadcast receiver class to my service since..some android method could not be used in static context. Now i receive an error Unable to instantiate activity ComponentInfo{com...}: java.lang.NullPointerException. How is it possible to fix? Below is my code for nested BroadcastReceiver class.
public class ServiceX extends Service {
private SharedPreferences settings = getSharedPreferences(PREFS, 0);
private SharedPreferences.Editor editor = settings.edit();
private static void setEnableNotification(int command) {
if (command == 1)
enableNotification = true;
else
enableNotification = false;
editor.putBoolean("enableNotification", enableNotification);
editor.commit();
}
public static class ReceiverX extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int enableNotification = intent.getIntExtra("EnableNotification", 0);
if (enableNotification == 0)
context.
setEnableNotification(0);
else if (enableNotification == 1)
setEnableNotification(1);
}
}
Below is how i instansiated the inner class:
public class ActivityX extends Activity{
private BroadcastReceiver receiver = security365Service.new NotifyServiceReceiver();
Here below is my mainfest which i changed after looking at some sources online:
<receiver android:name="com.milanix.services.ServiceX$ReceiverX" android:enabled="true">
</receiver>
Sorry if my question is dumb.
You cannot use a regular inner class here. It would need to be a static inner class, which will get you back to your original problem. So, you need to solve your "some android method could not be used in static context" problem one way or another.
I have an activity which displays some data fetched from the server. If no connection is available, activity displays some cached data; if connection is available, activity fetches data and displays it. It all works as expected.
Now, I would like to make my activity reload the data as soon as the connection occurs. I am using a simple Receiver that extends the BroadcastReceiver:
public class ConnectionChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
//what to do here?
}
}
}
Broadcast receiver is declared in my manifest file as follows:
<receiver android:name=".ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
In my activity, I register the receiver:
ConnectionChangeReceiver receiver = new ConnectionChangeReceiver();
this.registerReceiver(receiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
Now, I am confused as what to do next. When onReceive method is executed, how to make my activity aware of that? I know I could start a new activity, but that's not really what I want. Should I declare ConnectionChangeReceiver as a private class of my activity? Or is there any other solution?
I think building the receiver as a private subclass of your activity is the way to go here. This way you can control events and data from your activity. Then you can just create one instance of it and register the receiver from code as you did above.
Note that you don't have to register your receiver in both the manifest and code. One of these is enugh - the manifest is basically a "static" registration while doing it in code allows dynamic registration at runtime. Also when you register in the manifest, a new instance of your receiver will automatically be created from the system, executed and terminated. Doing the reg in code allows to point to one specific instance.
Interface Approach!
You can communicate via an interface as well. This approach works even
if your BroadcastReceiver is in a seperate file. You will not even
have to access UI elements of Activity in the Broadcast.
Its pretty Straightforward. Just follow these 3 simple steps.
1) Create an interface
public interface MyListerner{
public void performSomething(String arg);
}
2) Initialize the Listener in ConnectionChangeReceiver
public class ConnectionChangeReceiver extends BroadcastReceiver {
private MyListerner listener;
#Override
public void onReceive(Context context, Intent intent) {
listener = (MyListerner )context; // initialse
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null) {
listener.performSomething("Some data"); // Call listener method
}
}
}
3) Implement the interface and Override the method in your Activity
public class YourActivity implements MyListerner{
// Activity relate stuff onCreate() etc
public void updateUI(String result){
// Your code to update UI
}
#Override
public void performSomething(String arg){
updateUI(arg);
}
}
Relevant Links:
You can read in detail Why using an interface is a preferred approach in this case