How to display NDEF message after NDEF discovered/activity launched? - java

Have read through a number of questions similar to mine - I can only apologise if I have missed the solution to my woes, but I really can't work this out!
I have managed to get my nfc activity working - tapping the tag launches the correct activity of my app - but the ndef message is not displayed and I can't figure out why...
The tag is a Mifare Ultralight with a Plain Text message encoded. (mimetype: plain/text)
Here's my code, thank you all for your help, this forum should have a 'donate a beer' button!
package com.example.prototype02;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.Toast;
public class nfcActivity extends Activity {
private static final String TAG = "NFCReadTag";
private NfcAdapter mNfcAdapter;
private IntentFilter[] mNdefExchangeFilters;
private PendingIntent mNfcPendingIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfclayout);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
IntentFilter nfcIntent = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
nfcIntent.addDataScheme("text/plain");
mNdefExchangeFilters = new IntentFilter[] { nfcIntent };
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mNfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(mNfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}}
else if (rawMsgs == null){
Toast.makeText(getApplicationContext(), "No NDEF Message Read", Toast.LENGTH_LONG).show();
}
if(messages[0] != null) {
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
for (int b = 1; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
Toast.makeText(getApplicationContext(), "Safe Location Registered - " + result, Toast.LENGTH_SHORT).show();
}
}
else Toast.makeText(getApplicationContext(), "Intent Error...", Toast.LENGTH_LONG).show();
}
}

If your activity is started by the NFC intent, then onNewIntent() will not be called (it will only be called when you scan the tag when the activity is already in the foreground). Try doing something like calling onNewIntent(getIntent()) in onCreate().

Try something like this: (taken from StickyNotes NFC sample)
#Override
protected void onResume() {
super.onResume();
mResumed = true;
// Sticky notes received from Android
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
NdefMessage[] messages = getNdefMessages(getIntent());
byte[] payload = messages[0].getRecords()[0].getPayload();
setNoteBody(new String(payload));
setIntent(new Intent()); // Consume this intent.
}
enableNdefExchangeMode();
}
#Override
protected void onPause() {
super.onPause();
mResumed = false;
mNfcAdapter.disableForegroundNdefPush(this);
}
#Override
protected void onNewIntent(Intent intent) {
// NDEF exchange mode
if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] msgs = getNdefMessages(intent);
promptForContent(msgs[0]);
}
// Tag writing mode
if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(getNoteAsNdef(), detectedTag);
}
}

Related

how to show received sms in textview instead of toast

I am currently working on a simple android application to read an SMS and print it in TexView instead of Toast. but in receiver activity, we do not initialise "findbyid" so we can't print the SMS in textView. now I am showing SMS in Toast to test but I do not want it in a toast. I am also read questions/answer and also other articles but can't find what I want.
receiver activity,
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class read_sms extends BroadcastReceiver {
// Get the object of SmsManager
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReciver", "senderNum: " + senderNum + ", message: " + message);
//ourSMS.getSmsDetails(senderNum, message);
// Show SMS notification
//Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, Toast.LENGTH_LONG).show();
if(message.equals("Milind")){
Toast.makeText(context, "sms matched", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context, "not matched", Toast.LENGTH_LONG).show();
}
} // end of for loop
} // bundle
} catch (Exception e) {
// TODO: handle exception
Log.e("SmsReciver", "Exception smsReciver" + e);
}
}
}
my home activity is empty because I can't find which code placed here.
public class home extends AppCompatActivity {
TextView SMS_textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
SMS_textview = (TextView) findViewById(R.id.sms_text);
}
}
change that TextView to
public static TextView SMS_textview;
add method
public void recivedSms(String message)
{
try
{
SMS_textview.setText(message);
}
catch (Exception e)
{
}
}
in read_sms class add the following code when you recieve sms
home Sms = new home();
Sms.recivedSms(message );
Register your Receiver in your activity whenever you Receive a text in receiver
use this code in your Receiver class
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("your key", your Value);
broadcastIntent.setAction("link from you have recieve a text");
context.sendBroadcast(broadcastIntent);
after this register a broadcast Receiver in your activity like this
private void registerSmsReciever() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("link from you have recieve a text");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("onReceive", "Sms recieved in progress");
String message= intent.getStringExtra("key");
textView.setText(intent.getStringExtra("key"));
}
};
registerReceiver(broadcastReceiver, intentFilter);
}

Bluetooth disconnects when scanning barcode

I am using a Bluetooth printer and zxing barcode scanner for this project. My problem is that after I have the Bluetooth printer connected and I try to scan a barcode, using zxing, it disconnects the Bluetooth printer. Here is my code.
package com.zj.printdemo;
import com.zj.printdemo.R;
import android.app.Fragment;
import android.content.Intent;
import com.zj.btsdk.BluetoothService;
import com.zj.btsdk.PrintPic;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.view.View.OnClickListener;
import android.util.Log;
import android.view.ViewGroup;
public class PrintDemo extends Activity {
Button btnSearch;
Button btnSendDraw;
Button btnSend;
//Button btnClose;
Button clearBtn;
Button btnBarcode;
EditText edtContext;
EditText edtContextQTY;
EditText edtPrint;
private static final int REQUEST_ENABLE_BT = 2;
BluetoothService mService = null;
BluetoothDevice con_dev = null;
private static final int REQUEST_CONNECT_DEVICE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
//Button clearBtn = (Button)findViewById(R.id.btnClear);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//edtContext = (EditText) findViewById(R.id.txt_content);
mService = new BluetoothService(this, mHandler);
if( mService.isAvailable() == false ){
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
clearBtn = (Button)findViewById(R.id.btnClear);
OnClickListener ClearOnClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
edtContext.setText("");
edtContextQTY.setText("");
}
};
clearBtn.setOnClickListener(ClearOnClickListener);
btnBarcode = (Button) findViewById(R.id.btnBarcode);
OnClickListener BarcodeOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnBarcode) {
IntentIntegrator integrator = new IntentIntegrator(PrintDemo.this);
integrator.initiateScan();
}
}
};
btnBarcode.setOnClickListener(BarcodeOnClickListener);
}
public void onStart() {
super.onStart();
if( mService.isBTopen() == false)
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_test);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new ClickEvent());
//btnClose = (Button) this.findViewById(R.id.btnClose);
//btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
edtContextQTY = (EditText) findViewById(R.id.txt_contentQTY);
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("������Ϣ",ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this,DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
String msg = edtContext.getText().toString();
String msgQTY = edtContextQTY.getText().toString();
if( msg.length() > 0 ){
mService.sendMessage("ItemID:"+msg+"\n","ItemQTY:"+msgQTY+"\n");
}
} //else if (v == btnClose) {
//mService.stop();}
else if (v == btnSendDraw) {
String msg = "";
String lang = getString(R.string.strLang);
//printImage();
byte[] cmd = new byte[3];
cmd[0] = 0x1b;
cmd[1] = 0x21;
if((lang.compareTo("en")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("Congratulations!\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " You have sucessfully created communications between your device and our bluetooth printer.\n\n"
+" the company is a high-tech enterprise which specializes" +
" in R&D,manufacturing,marketing of thermal printers and barcode scanners.\n\n";
mService.sendMessage(msg,"GBK");
}else if((lang.compareTo("ch")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("��ϲ����\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " ���Ѿ��ɹ��������������ǵ�������ӡ����\n\n"
+ " ����˾��һ��רҵ�����з�����������������Ʊ�ݴ�ӡ��������ɨ���豸��һ��ĸ߿Ƽ���ҵ.\n\n";
mService.sendMessage(msg,"GBK");
}
}
}
}
/**
* Handler BluetoothService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("��������","��������.....");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("StateNone","�ȴ�����.....");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
case IntentIntegrator.REQUEST_CODE:
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
//formatTxt.setText("FORMAT: " + scanFormat);
edtContext.setText(scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData = null;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, "/mnt/sdcard/icon.jpg");
sendData = pg.printDraw();
mService.write(sendData);
}
}
My goal is to connect the printer, scan a barcode, and print a tag with the ID and quantity. Manual entry works, the printer works, and the barcode scanning works. Its only when you use the barcode scanner after you connect the printer that it will disconnect the printer.

How to start service based on result from activity recognition

I am Trying to start a service if the DetectedActivity returned from Activity recognition returned is IN_VEHICLE. I have downloaded a code sample
from :
http://tutsberry.com/activity-recognition-implementation-on-android/
But i'm not sure where to put code in to start my service.
I am Trying to the check the user activity in the background using the Activity Recognition and then
start a service all in the background.
ActivityRecognitionIntentService Class
public class ActivityRecognitionIntentService extends IntentService {
//LogCat
private static final String TAG = ActivityRecognitionIntentService.class.getSimpleName();
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
//Extract the result from the Response
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity detectedActivity = result.getMostProbableActivity();
//Get the Confidence and Name of Activity
int confidence = detectedActivity.getConfidence();
String mostProbableName = getActivityName(detectedActivity.getType());
//Fire the intent with activity name & confidence
Intent i = new Intent("ImActive");
i.putExtra("activity", mostProbableName);
i.putExtra("confidence", confidence);
Log.d(TAG, "Most Probable Name : " + mostProbableName);
Log.d(TAG, "Confidence : " + confidence);
//Send Broadcast to be listen in MainActivity
this.sendBroadcast(i);
} else {
Log.d(TAG, "Intent had no data returned");
}
}
//Get the activity name
private String getActivityName(int type) {
switch (type) {
case DetectedActivity.IN_VEHICLE:
return "In Vehicle";
case DetectedActivity.ON_BICYCLE:
return "On Bicycle";
case DetectedActivity.ON_FOOT:
return "On Foot";
case DetectedActivity.WALKING:
return "Walking";
case DetectedActivity.STILL:
return "Still";
case DetectedActivity.TILTING:
return "Tilting";
case DetectedActivity.RUNNING:
return "Running";
case DetectedActivity.UNKNOWN:
return "Unknown";
}
return "N/A";
}
}
MainActivity Class
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
// LogCat
private static final String TAG = MainActivity.class.getSimpleName();
private Context mContext;
private GoogleApiClient mGApiClient;
private BroadcastReceiver receiver;
private TextView textView;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.msg);
textView.setMovementMethod(new ScrollingMovementMethod());
tv2 = (TextView) findViewById(R.id.text2);
//Set the context
mContext = this;
//Check Google Play Service Available
if (isPlayServiceAvailable()) {
mGApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//Connect to Google API
mGApiClient.connect();
} else {
Toast.makeText(mContext, "Google Play Service not Available", Toast.LENGTH_LONG).show();
}
//Broadcast receiver
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Add current time
Calendar rightNow = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a");
String strDate = sdf.format(rightNow.getTime());
;
String v = strDate + " " +
intent.getStringExtra("activity") + " " +
"Confidence : " + intent.getExtras().getInt("confidence") + "\n";
v = textView.getText() + v;
textView.setText(v);
}
};
//Filter the Intent and register broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction("ImActive");
registerReceiver(receiver, filter);
//Check for Google play services available on device
}
private boolean isPlayServiceAvailable() {
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS;
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onConnected(Bundle bundle) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecongPendingIntent = PendingIntent
.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG, "connected to ActivityRecognition");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);
//Update the TextView
textView.setText("Connected to Google Play Services \nWaiting for Active Recognition... \n");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Suspended to ActivityRecognition");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Not connected to ActivityRecognition");
//Disconnect and detach the receiver
mGApiClient.disconnect();
unregisterReceiver(receiver);
}
}
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends Activity {
IntentFilter filter;
BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filter = new IntentFilter();
mReceiver = new MyReceiver();
filter.addAction("IN_VEHICLE"); //Name the action what ever you need to.
filter.addAction("OTHER_ACTION");
filter.addAction("YET_ANOTHER_ACTION)");
registerReceiver(mReceiver, filter); //Register the receiver you define with the actions you want.
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("IN_VEHICLE_RESPONSE".equals(intent.getAction())){
//Launch other activities here
Intent i = new Intent(getApplicationContext(), InVehicleActivity.class );
startActivity(i);
}else if("OTHER_ACTION_RESPONSE".equals(intent.getAction())){
//Launch desired activity
}else if("YET_ANOTHER_ACTION_RESPONSE".equals(intent.getAction())){
//Launch desired activity
}else{
//Handle unssuported actions
}
}
}
}
MyIntentService.java
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
public class MyIntentService extends IntentService {
Bundle extras;
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
extras = intent.getExtras();
if("IN_VEHICLE".equals(intent.getAction())){
inVehicle(extras);
return;
}
if("OTHER_ACTION".equals(intent.getAction())){
//otheraction method
return;
}
if("YET_ANOTHER_ACTION".equals(intent.getAction())){
//yetanotheraction method
return;
}
}
private void inVehicle(Bundle extras) {
//do work
//do work
Intent intent = new Intent();
intent.setAction("IN_VEHICLE_RESPONSE");
//put all other desired stuff in intent
getApplicationContext().sendBroadcast(intent);
}
}
Don't forget to add your receiver to your manifest.
I would suggest that you start Activities from Activity not Service layer.

Android - Call method from another class when app is closed (Using AlarmManager)

I am trying to call a method in my MainActivity class from another class using an AlarmManager.
I found this question which helped me call the method but when the app is closed, and the AlarmManager is still running it gives a NullPointerException error.
Another solution which would work for me is to have getBatteryLevel() inside my AlarmRec class. When I try this I get the error - Cannot resolve method registerReceiver(null, android.content.IntentFilter).
My MainActivity class:
package com.ds.shutdown;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity {
int userLvl;
int batteryLvl;
static MainActivity mainActivity;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivity = this;
batteryLvl = getBatteryLevel();
String bat = Integer.toString(batteryLvl);
TextView textViewTwo = (TextView) findViewById(R.id.textBatteryLvl);
textViewTwo.setText("Battery level: " + bat);
userLvl = loadSavedPreferences();
TextView textView = (TextView) findViewById(R.id.textUserLvl);
textView.setText("User entry: " + Integer.toString(userLvl));
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().getBoolean("CALL_METHOD", false)) {
shutdown();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void shutdown() {
Toast.makeText(this, "In shutdown method", Toast.LENGTH_SHORT).show();
batteryLvl = getBatteryLevel();
String bat = Integer.toString(batteryLvl);
TextView textViewTwo = (TextView) findViewById(R.id.textBatteryLvl);
textViewTwo.setText("Battery level: " + bat);
userLvl = loadSavedPreferences();
if (batteryLvl <= userLvl) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});
process.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public int getBatteryLevel() {
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
return level;
}
//OK button onClick
public void btnPress(View v) {
EditText mEditText = (EditText) findViewById(R.id.userLvl); //Look at text box
String userLvlStr = mEditText.getText().toString(); //Take contents and set to string
if (userLvlStr.matches("")){
Toast.makeText(this, "Invalid Entry", Toast.LENGTH_SHORT).show();
return;
}
userLvl = Integer.parseInt(userLvlStr); //Convert that string to an int
saveSavedPreferences(userLvl); //Save that int
setContentView(R.layout.activity_main); //Look at main activity
TextView textView = (TextView) findViewById(R.id.textUserLvl); //Look at text view
textView.setText("User entry: " + userLvlStr); //Change text view to show user entry
batteryLvl = getBatteryLevel();
String bat = Integer.toString(batteryLvl);
TextView textViewTwo = (TextView) findViewById(R.id.textBatteryLvl);
textViewTwo.setText("Battery level: " + bat);
alarmMethod();
}
//Saves variable(s) across app close
private void saveSavedPreferences(int userLvl){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); //Create SharedPreferences object
SharedPreferences.Editor editor= sharedPref.edit(); //Now get editor
editor.putInt("userLvl", userLvl); //Put in variable
editor.commit(); //Save variable(s)
}
//Loads variable(s) across app close
private int loadSavedPreferences() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
userLvl = sharedPrefs.getInt("userLvl", 0);
return userLvl; //Using return since only one variable is needed
}
//Set alarm
private void alarmMethod() {
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); //Create Alarm Manager
Intent intent = new Intent(this, AlarmRec.class); //Set intent
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
//setRepeating() lets you specify a precise custom interval--in this case, 20 seconds
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 10, alarmIntent);
Toast.makeText(MainActivity.this, "Alarm set", Toast.LENGTH_LONG).show();
}
public void cancelAlarm(View v2) {
// If the alarm has been set, cancel it.
if (alarmMgr != null) {
alarmMgr.cancel(alarmIntent);
}
TextView textView = (TextView) findViewById(R.id.textUserLvl);
textView.setText("User entry: ");
}
public static MainActivity getInstance(){
return mainActivity;
}
}
My Alarm Receiver class:
package com.ds.shutdown;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.widget.Toast;
public class AlarmRec extends BroadcastReceiver {
//#Override
public void onReceive(Context context, Intent intent) {
//Call shutdown
Toast.makeText(MainActivity.getInstance(), "Calling shutdown", Toast.LENGTH_SHORT).show();
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().shutdown();
}
else {
Intent i = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//I also tried i.addFlags
i.putExtra("CALL_METHOD", true);
context.startActivity(i);
}
}
}
Because when your app is closed MainActivity.getInstance() returns null.
You should do methodToCall() in your BroadcastReceiver (if the method doesn't take long) or call Service from there, where you do methodToCall().
Another way is to modify your Receiver like this
Toast.makeText(context, "Calling shutdown", Toast.LENGTH_SHORT).show();
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().methodToCall();
}
else {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("CALL_METHOD", true);
context.startActivity(i);
}
And MainActivity in onCreate check for CALL_METHOD extra;
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().getBoolean("CALL_METHOD", false)) {
methodToCall();
}
Do not expose your main activity through a static method like a singleton.
Your activity getInstance() method will return null because it has probably been popped off the back stack (or if activity has been killed). Do not rely on your activity being present and is reference to be valid after you have backgrounded your app.
I don't understand what functionality you want in that method that the activity defines. You should be able to put that in the broadcast receiver. If you need UI to be shown, launch your activity again (in which case the UI would show up again).

Image should get changed when message is received in android

package com.example.nhx;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
ImageView imageView1;
ImageView imageView2;
Button ON, OFF;
String msg = "";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
if (msg.contains("LED ON")) {
Toast.makeText(context, "HELLO WORLD", Toast.LENGTH_SHORT).show();
}
if (msg.contains("LED OFF")) {
Toast.makeText(context, "HELLO", Toast.LENGTH_SHORT).show();
}
if (msg == "LED ON") {
imageView1.setVisibility(imageView1.VISIBLE);
imageView2.setVisibility(imageView2.INVISIBLE);
}
if (msg == "LED OFF") {
imageView2.setVisibility(imageView2.VISIBLE);
imageView1.setVisibility(imageView1.INVISIBLE);
}
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// str += "SMS from " + msgs[i].getOriginatingAddress();
// str += " :";
str += msgs[i].getMessageBody().toString();
str += msg;
// str += "\n";
}
}
if (msg.contains("LED ON")) {
Toast.makeText(context, "HELLO WORLD", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "HELLO", Toast.LENGTH_SHORT).show();
}
if (msg == "LED ON") {
imageView1.setVisibility(imageView1.VISIBLE);
imageView2.setVisibility(imageView2.INVISIBLE);
}
if (msg == "LED OFF") {
imageView2.setVisibility(imageView2.VISIBLE);
imageView1.setVisibility(imageView1.INVISIBLE);
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
private void startactivity(Intent i) {
}
}
package com.example.nhx;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class blinkMe extends Activity {
Button ON;
Button OFF;
ImageView imageView1;
ImageView imageView2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ON = (Button) findViewById(R.id.ON);
OFF = (Button) findViewById(R.id.OFF);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
ON.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
sendSMS("5556", "LED ON");
OFF.setClickable(true);
imageView1.setVisibility(imageView1.VISIBLE);
imageView2.setVisibility(imageView2.INVISIBLE);
}
private void sendSMS(String phoneNumber, String message) {
// TODO Auto-generated method stub
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
ON.setClickable(true);
}
});
OFF.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ON.setClickable(true);
sendSMS("5554", "LED OFF");
/* Intent i = new Intent(); */
imageView2.setVisibility(imageView2.VISIBLE);
imageView1.setVisibility(imageView1.INVISIBLE);
}
private void sendSMS(String phoneNumber, String message) {
// TODO Auto-generated method stub
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
});
}
}
In my application I have two buttons like on and off and two images overlapping each other, red and green colour. When I click on button green image should come foreword and when I click off, red image should come foreword, along with it one message should be sent to predefined number when the button is clicked means two events takes place when the button is clicked
1. corresponding image switches foreword
2. message is sent to predefined number
Now the problem arises after sending message the intended receiver sends us message now based on the message received the image should automatically get changed like if the receiver reply's on then green image should come foreword and if he reply's off then red image should come foreword.

Categories