I am using two different Layouts for same Activity, On orientation change the activity state is not maintained. Please suggest how to do that?
You can easily store your "activity state" using onSavedInstanceState. For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(saveInstanceState != null) {
if(savedInstanceState.getBoolean("running") == true) {
// previously is running
} else {
// previously not running
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(condition) {
outState.putBoolean("running", true);
}
}
You seem to do some work in an AsyncTask and then you're changing the orientation.
Move the task you're doing from AsyncTask in an IntentService. Once the job is executed, send a broadcast with the result. In your activity, register a BroadcastReceiver in onCreate and de-register it in onDestroy.
That receiver will handle the result of your operation. You could also send from IntentService some intermediary data/progress update that can be received and processed by the same Receiver.
EDIT: to show some code.
The first search result on Google for IntentService tutorial. But I would strongly recommend reading more about Services. Also Vogella has a nice article about this.
About BroadcastReceivers.
If you want something to get you started here's a sample project I built in 15 mins:
The activity:
package com.adip.droid.sampleandroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class FrontActivity extends FragmentActivity {
private TextView labelData;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WorkerService.WORK_PROGRESS_ACTION.equals(action)) {
publishProgress(intent.getStringExtra(WorkerService.WORK_KEY_PROGRESS));
} else if (WorkerService.WORK_END_ACTION.equals(action)) {
workInProgress = false;
publishResult(intent.getStringExtra(WorkerService.WORK_KEY_RESULT));
}
}
};
protected void publishProgress(String data) {
showMessage(data);
}
protected void publishResult(String data) {
showMessage(data);
}
private void showMessage(String data) {
labelData.setText(data);
}
/**
* Maybe you need this in order to not start the service once you have an ongoing job ...
* */
private boolean workInProgress;
#Override
protected void onCreate(Bundle instanceState) {
super.onCreate(instanceState);
setContentView(R.layout.front_layout);
if (instanceState != null) {
workInProgress = instanceState.getBoolean("WORK_IN_PROGRESS", false);
}
labelData = (TextView) findViewById(R.id.labelData);
findViewById(R.id.btnWorker).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTheJob();
}
});
IntentFilter filter = new IntentFilter(WorkerService.WORK_END_ACTION);
filter.addAction(WorkerService.WORK_PROGRESS_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}
protected void doTheJob() {
if (workInProgress) {
return;
}
Intent serviceIntent = new Intent(this, WorkerService.class);
serviceIntent.setAction(WorkerService.WORK_START_ACTION);
startService(serviceIntent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("WORK_IN_PROGRESS", workInProgress);
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
}
its layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnWorker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Start the work" />
<TextView
android:id="#+id/labelData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btnWorker"
android:layout_centerHorizontal="true"
android:layout_marginBottom="35dp"
android:freezesText="true"
android:text="No data yet"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
and the IntentService:
package com.adip.droid.sampleandroid;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
public class WorkerService extends IntentService {
public static final String WORK_START_ACTION = "WORK_START_ACTION";
public static final String WORK_END_ACTION = "WORK_END_ACTION";
public static final String WORK_KEY_RESULT = "WORK_KEY_RESULT";
public static final String WORK_PROGRESS_ACTION = "WORK_PROGRESS_ACTION";
public static final String WORK_KEY_PROGRESS = "WORK_KEY_PROGRESS";
public WorkerService() {
super("WorkerService");
}
#Override
protected void onHandleIntent(Intent intent) {
if (WORK_START_ACTION.equals(intent.getAction())) {
startProgress();
}
}
private void startProgress() {
publishProgress("Starting the job");
synchronized (this) {
try {
wait(2500);
} catch (InterruptedException ignored) {
}
}
publishProgress("Progress Point A");
synchronized (this) {
try {
wait(2500);
} catch (InterruptedException ignored) {
}
}
publishJobDone();
}
public void publishProgress(String data) {
Intent progressIntent = new Intent(WORK_PROGRESS_ACTION);
progressIntent.putExtra(WORK_KEY_PROGRESS, data);
LocalBroadcastManager.getInstance(this).sendBroadcast(progressIntent);
}
public void publishJobDone() {
Intent progressIntent = new Intent(WORK_END_ACTION);
progressIntent.putExtra(WORK_KEY_RESULT, "Job done!");
LocalBroadcastManager.getInstance(this).sendBroadcast(progressIntent);
}
}
Also don't forget to update your manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adip.droid.sampleandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FrontActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".WorkerService"
android:exported="false" >
</service>
</application>
</manifest>
Related
In this case two activities A and B should interact in that way that A calls B for a result.
But A never gets any data back from B.
This code looks like any tutorial or SO question I have seen.
The debugging session confirmed that setResult is called.
This problem is robbing me of my motivation, would be nice if someone could point out what I am missing.
EDIT: The code doesn't work when executed on my physical target device, but runs find on a nexus 5 device. What could I try to find out why?
MainActivity.java
package iifym.apps.rnoennig.de.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
Intent in = new Intent(this, SecondActivity.class);
in.putExtra("mau", "bar");
startActivityForResult(in, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// data is null ;(
Toast.makeText(this, String.valueOf(data), Toast.LENGTH_SHORT).show();
}
}
SecondActivity.java
package iifym.apps.rnoennig.de.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Toast.makeText(this, String.valueOf(getIntent()), Toast.LENGTH_SHORT).show();
}
public void onClick(View view) {
setResult(RESULT_OK, new Intent().putExtra("foo", "bar"));
finish();
}
}
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="center_horizontal"
android:onClick="onClick"
/>
</LinearLayout>
layout/second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2"
android:layout_gravity="center_horizontal"
android:onClick="onClick"
/>
</LinearLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="iifym.apps.rnoennig.de.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
Works for me. (Same layouts and Manifest).
Main
public class MainActivity extends AppCompatActivity {
public static final int MAIN_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
Intent in = new Intent(MainActivity.this, SecondActivity.class);
in.putExtra("mau", "start 2nd");
startActivityForResult(in, MAIN_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAIN_REQUEST) {
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this, data.getStringExtra("foo"), Toast.LENGTH_SHORT).show();
}
}
}
}
Second
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent sent = getIntent();
if (sent != null) {
Toast.makeText(SecondActivity.this, sent.getStringExtra("mau"), Toast.LENGTH_SHORT).show();
}
}
public void onClick(View v) {
setResult(RESULT_OK, new Intent().putExtra("foo", "finish 2nd"));
finish();
}
}
I have an the following android application that prints the copied text by the user...
MainActivity.java
package com.example.backgroundrunning;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Intent;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements ClipboardManager.OnPrimaryClipChangedListener{
ClipboardManager clipBoard;
TextView tv;
EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.note);
edit=(EditText)findViewById(R.id.edit);
clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( this );
startService(new Intent(this,ExampleService.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onPrimaryClipChanged() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
String test=clipboard.getText().toString();
tv.setText(test);
}
}
ExampleService.java
package com.example.backgroundrunning;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class ExampleService extends Service {
#Override
public void onCreate() {
// The service is being created
}
public int onStartCommand(Intent intent, int flags, int startId) {
// handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
i want to make my program that run at the background silently,
means it doesn't close when the user presses back button
I found this code and added that to my program just like the above code,
But it doesn't work...
What is the problem?
And here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.backgroundrunning"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.backgroundrunning.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
#Override
public void onBackPressed()
{
Intent i= new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
or
Intent i= new Intent(Intent.ACTION_ALL_APPS);
startActivity(i);
}
I am working on a simple android app to do Internet-of-Things functions using the WunderBar Relayr toolkit to have sensors send data back to the android app so as to display the data. I am trying to emulate the sample temperature display app as shown in the wunderbar relayr website as well as the relayr GitHub repository so as to understand how the sensor and app communicate.
I am able to activate the master module as well as the humidity/temperature sensor, but even though the sensors work fine, the readings in the app is shown to be constant for example: 22*C. My app does not seem to be collecting the data
I can log in using my credentials, but then instead of my name being displayed, it displays another name.How can I resolve this issue?
The code is shown below.
ThermometerDemoActivity.java:
package com.vasansdomain.pavan.thermometer;
//import the Android classes we will need
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
//import the relayr SDK
import io.relayr.RelayrSdk;
import io.relayr.model.DeviceModel;
import io.relayr.model.Reading;
import io.relayr.model.Transmitter;
import io.relayr.model.TransmitterDevice;
import io.relayr.model.User;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.Subscriptions;
public class ThermometerDemoActivity extends ActionBarActivity
{
private TextView mWelcomeTextView;
private TextView mTemperatureValueTextView;
private TextView mTemperatureNameTextView;
private TransmitterDevice mDevice;
private Subscription mUserInfoSubscription = Subscriptions.empty();
private Subscription mTemperatureDeviceSubscription = Subscriptions.empty();
/**
* Once the Activity has been started, the onCreate method will be called
* #param savedInstanceState
*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View view = View.inflate(this, R.layout.activity_thermometer_demo, null);
mWelcomeTextView = (TextView) view.findViewById(R.id.txt_welcome);
mTemperatureValueTextView = (TextView) view.findViewById(R.id.txt_temperature_value);
mTemperatureNameTextView = (TextView) view.findViewById(R.id.txt_temperature_name);
setContentView(view);
//we use the relayr SDK to see if the user is logged in by caling the isUserLoggedIn function
if (RelayrSdk.isUserLoggedIn())
{
updateUiForALoggedInUser();
}
else
{
updateUiForANonLoggedInUser();
logIn();
}
}
/**
* When Android is ready to draw any menus it initiates the
* "prepareOptionsMenu" event, this method is caled to handle that
* event.
* #param menu
* #return
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//remove any previous items from the menu
menu.clear();
//Check to see if the user is logged in
if (RelayrSdk.isUserLoggedIn())
{
//if the user is logged in, we ask Android to draw the menu
//we defined earlier in the thermometer_demo_logged_in.xml
//file
getMenuInflater().inflate(R.menu.thermometer_demo_logged_in, menu);
}
else
{
//otherwise we return the
//thermometer_demo_not_logged_in.xml file
getMenuInflater().inflate(R.menu.thermometer_demo_not_logged_in, menu);
}
//we must return this, so that any other classes interested in
//the prepare menu event can do something.
return super.onPrepareOptionsMenu(menu);
}
/**
* When a menu item is selected, we see which item was called and
* decide what to do according to the item.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//if the user selected login
if (item.getItemId() == R.id.action_log_in)
{
//we call the login method on the relayr SDK
logIn();
return true;
}
else if (item.getItemId() == R.id.action_log_out)
{
//otherwise we call the logout method defined later in this class
logOut();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* The LogIn method definition
*/
private void logIn() {
RelayrSdk.logIn(this).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<User>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Toast.makeText(ThermometerDemoActivity.this, R.string.unsuccessfully_logged_in, Toast.LENGTH_SHORT).show();
updateUiForANonLoggedInUser();
}
#Override
public void onNext(User user) {
Toast.makeText(ThermometerDemoActivity.this, R.string.successfully_logged_in, Toast.LENGTH_SHORT).show();
invalidateOptionsMenu();
updateUiForALoggedInUser();
}
});
}
/**
* Called when the user logs out
*/
private void logOut()
{
unSubscribeToUpdates();
//call the logOut method on the relayr SDK
RelayrSdk.logOut();
//call the invalidateOptionsMenu this is defined in the
//Activity class and is used to reset the menu option
invalidateOptionsMenu();
//use the Toast library to display a message to the user
Toast.makeText(this, R.string.successfully_logged_out, Toast.LENGTH_SHORT).show();
updateUiForANonLoggedInUser();
}
private void updateUiForANonLoggedInUser()
{
mTemperatureValueTextView.setVisibility(View.GONE);
mTemperatureNameTextView.setVisibility(View.GONE);
mWelcomeTextView.setText(R.string.hello_relayr);
}
private void updateUiForALoggedInUser()
{
mTemperatureValueTextView.setVisibility(View.VISIBLE);
mTemperatureNameTextView.setVisibility(View.VISIBLE);
loadUserInfo();
}
private void loadUserInfo()
{
mUserInfoSubscription = RelayrSdk.getRelayrApi().getUserInfo().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<User>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Toast.makeText(ThermometerDemoActivity.this, R.string.something_went_wrong, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
#Override
public void onNext(User user) {
String hello = String.format(getString(R.string.hello), user.getName());
mWelcomeTextView.setText(hello);
loadTemperatureDevice(user);
}
});
}
private void loadTemperatureDevice(User user)
{
mTemperatureDeviceSubscription = RelayrSdk.getRelayrApi().getTransmitters(user.id).flatMap(new Func1<List<Transmitter>, Observable<List<TransmitterDevice>>>() {
#Override
public Observable<List<TransmitterDevice>> call(List<Transmitter> transmitters) {
// This is a naive implementation. Users may own many WunderBars or other
// kinds of transmitter.
if (transmitters.isEmpty())
return Observable.from(new ArrayList<List<TransmitterDevice>>());
return RelayrSdk.getRelayrApi().getTransmitterDevices(transmitters.get(0).id);
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List<TransmitterDevice>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Toast.makeText(ThermometerDemoActivity.this, R.string.something_went_wrong, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
#Override
public void onNext(List<TransmitterDevice> devices) {
for (TransmitterDevice device : devices) {
if (device.model.equals(DeviceModel.TEMPERATURE_HUMIDITY.getId())) {
subscribeForTemperatureUpdates(device);
return;
}
}
}
});
}
#Override
protected void onPause()
{
super.onPause();
unSubscribeToUpdates();
}
private void unSubscribeToUpdates()
{
if (!mUserInfoSubscription.isUnsubscribed())
mUserInfoSubscription.unsubscribe();
if (!mTemperatureDeviceSubscription.isUnsubscribed())
mTemperatureDeviceSubscription.unsubscribe();
if (mDevice != null)
RelayrSdk.getWebSocketClient().unSubscribe(mDevice.id);
}
#Override
protected void onResume()
{
super.onResume();
if (RelayrSdk.isUserLoggedIn())
{
updateUiForALoggedInUser();
}
else
{
updateUiForANonLoggedInUser();
}
}
private void subscribeForTemperatureUpdates(TransmitterDevice device)
{
mDevice = device;
RelayrSdk.getWebSocketClient().subscribe(device).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Reading>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Toast.makeText(ThermometerDemoActivity.this, R.string.something_went_wrong, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
#Override
public void onNext(Reading reading) {
if (reading.meaning.equals("temperature"))
mTemperatureValueTextView.setText(reading.value + "˚C");
}
});
}
}
ThermometerDemoApplication.java:
package com.vasansdomain.pavan.thermometer;
import android.app.Application;
import io.relayr.demo.thermometer.RelayrSdkInitializer;
public class ThermometerDemoApplication extends Application
{
#Override
public void onCreate()
{
super.onCreate();
RelayrSdkInitializer.initSdk(this);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/thermometer"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".ThermometerDemoApplication" >
<activity
android:name=".ThermometerDemoActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
activity_demo_thermometer.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ThermometerDemoActivity"
android:background="#FFFFFF"
android:gravity="center">
<TextView
android:id="#+id/txt_welcome"
android:text="#string/hello_relayr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20dp" />
<TextView
android:id="#+id/txt_temperature_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="60sp"
android:paddingTop="25dp"
android:paddingBottom="25dp"/>
<TextView
android:id="#+id/txt_temperature_name"
android:text="#string/title_temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_gravity="center"
android:paddingBottom="25dp"/>
</LinearLayout>
strings.xml
<resources>
<string name="app_name">Thermometer</string>
<string name="action_settings">Settings</string>
<string name="hello_relayr">Hello Relayr!!!</string>
<string name="hello">Hello %s!</string>
<string name="action_log_in">Log in</string>
<string name="action_log_out">Log out</string>
<string name="successfully_logged_in">You were successfully logged in!</string>
<string name="successfully_logged_out">You were successfully logged out!</string>
<string name="unsuccessfully_logged_in">There was a problem in the log in.</string>
<string name="something_went_wrong">Oops! Something went wrong</string>
<string name="title_temperature">Temperature</string>
</resources>
This is the code for the mock mode of the app:debug->java->io->relayr->demo->thermometer
package io.relayr.demo.thermometer;
import android.content.Context;
import io.relayr.RelayrSdk;
public abstract class RelayrSdkInitializer {
public static void initSdk(Context context) {
new RelayrSdk.Builder(context).inMockMode(true).build();
}
}
This is the code for the release mode of the app:release->java->io->relayr->demo->thermometer
package io.relayr.demo.thermometer;
import android.content.Context;
import io.relayr.RelayrSdk;
public class RelayrSdkInitializer {
public static void initSdk(Context context) {
new RelayrSdk.Builder(context).inMockMode(false).build(); }
}
Is the answer possibly related to tweaking the RelayrSdkInitializer class in the debug file of the app
Build a release version of the app and try again. The debug version only provides mock data.
Because if you see another name (Hugo Domenech) than you are building the app in debug mode and that's why you see mocked data.
I am trying to detect if the WiFi is connected or not by listening to the "SUPPLICANT_CONNECTION_CHANGE_ACTION" as shown below in the code. But the problem is
when i run the App i receive no notificatio from the broadCast Receiver i am registered to!!
why that is happening and how to solve it?
code:
IntentFilter intentFilter2 = new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityModule();
}
protected void ConnectivityModule() {
// TODO Auto-generated method stub
Log.d(TAG, "#interNetConnectivityModule: called");
registerReceiver(SupplicantReceiver, intentFilter2);
}
BroadcastReceiver SupplicantReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
}
}
};
Here is Example :
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// broadcast a custom intent.
public void broadcastIntent(View view)
{
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
My Broadcast Receiver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
This is how you should declare Broadcast Receiver in your Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="#+id/btnStartService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/broadcast_intent"
android:onClick="broadcastIntent"/>
</LinearLayout>
Your receiver looks correctly registered (at runtime, not based on Manifest, but whatever, should be good anyway).
I'm guessing.. have you tried putting logs in onReceive method like
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "Reached this point, receiver is working");
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
SupplicantState supplicantState = (SupplicantState)intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (supplicantState == (SupplicantState.COMPLETED)) {
Log.d(TAG, "#SupplicantReceiver: connected");
}
if (supplicantState == (SupplicantState.DISCONNECTED)) {
Log.d(TAG, "#SupplicantReceiver: not connected");
}
Log.d(TAG, "Checking for an error in retrieving data!");
boolean myTest = intent.getBooleanExtra(EXTRA_SUPPLICANT_CONNECTED, false);
if (myTest) Log.d(TAG, "This way it worked!");
else Log.d(TAG, "This does not mean it didn't work at all! Might just be the correct value as a DISCONNECTED status");
} else Log.d(TAG, "Bizzarre error, action received was different from the one receiver was registered to! [ " + action + " ] ");
}
My guess is that you might be trying to retrieve the information in a wrong way, and with logs so strictly defined you can't see enough of what happens, but the receiver works fine
I want to start my app when a user press the power button. I m following This code
but its not showing any Log and toast.
here is my complete code.
MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
// perform what you want here
}
}
menifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.powerbuttontest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" >
</action>
<action android:name="android.intent.action.SCREEN_ON" >
</action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" >
</action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" >
</action>
<action android:name="android.intent.action.ACTION_SHUTDOWN" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.java
package com.example.powerbuttontest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I think i m committing a mistake in my menifest file. please have a look on this. thanks.
First, unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! so You need to make a service which will keep on running like this
public static class UpdateService extends Service {
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new Receiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// your code
} else {
// your code
}
}
}
and your receiver can be something
public class Receiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Here is my complete code. Hope this helps. I was basically making a look screen app. This will disable your default lock screen. and on power button press it will start a service and runs to look for power button press event.
Layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/toggleButton1"
android:layout_marginTop="72dp"
android:enabled="false"
android:text="Settings" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="72dp"
android:checked="true"
android:textOff="Disable"
android:textOn="Enable" />
</RelativeLayout>
MainActivity.java
package com.example.powerbuttontest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton btnToggleLock;
Button btnMisc;
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMisc = (Button) findViewById(R.id.button1);
btnToggleLock = (ToggleButton) findViewById(R.id.toggleButton1);
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
btnToggleLock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btnToggleLock.isChecked()) {
toast.cancel();
toast.setText("Unlocked");
toast.show();
Log.i("Unlocked", "If");
Context context = getApplicationContext();
KeyguardManager _guard = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock _keyguardLock = _guard
.newKeyguardLock("KeyguardLockWrapper");
_keyguardLock.disableKeyguard();
MainActivity.this.startService(new Intent(
MainActivity.this, UpdateService.class));
} else {
toast.cancel();
toast.setText("Locked");
toast.show();
Context context = getApplicationContext();
KeyguardManager _guard = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock _keyguardLock = _guard
.newKeyguardLock("KeyguardLockWrapper");
_keyguardLock.reenableKeyguard();
Log.i("Locked", "else");
MainActivity.this.stopService(new Intent(MainActivity.this,
UpdateService.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Log.i("onConfigurationChanged", "Called");
}
}
MyReciever.java
package com.example.powerbuttontest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.example.powerbuttontest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
// Toast.makeText(getApplicationContext(), "Sleep",
// Toast.LENGTH_LONG)
// .show();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Menifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.powerbuttontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" />
<service android:name=".UpdateService" />
</application>
</manifest>
Here this one is the complete code, which will open your application as soon you presss power button. I am also doing the same project, where i want to open my Application directly after i press power button (turn on).
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_power_offon);
startService(new Intent(getApplicationContext(), LockService.class));
}//EOF Oncreate
}//EOF Activity
LockService.java
public class LockService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder
{
LockService getService() {
return LockService.this;
}
}//EOF SERVICE
ScreenReceiver.java
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB","onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
// do whatever you need to do here
wasScreenOn = false;
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ","shutdown now");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
// and do whatever you need to do here
wasScreenOn = true;
Log.e("Screen ","awaked now");
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
Log.e("LOB","userpresent");
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
}
}//EOF SCREENRECEIVER.JAVA
Now this is xml file, Please copy paste and just change the package name you are using
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.userpresent.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.userpresent.LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>