I want to get battery Current, and Voltage at an interval of 5 seconds.
But in my source, the Voltage and Current changes at an random interval.
such as 5 seconds, 10 seconds, 9 seconds, .......
I heard BroadcastReceiver requires a return value within 10 seconds.
I guess this is a cause, but I have no idea how to solve this problem.
package com.example.hubertlee.batterywearrate;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView batteryInfo;
Long avgCurrent = null, currentNow = null;
int count = 0;
float power = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BatteryManager mBatteryManager = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);
batteryInfo = (TextView) findViewById(R.id.textViewBatteryInfo);
this.registerReceiver(this.batteryinfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
avgCurrent = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
currentNow = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
}
}
private BroadcastReceiver batteryinfoReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent){
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
int icon_small = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL,0);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
boolean present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
String technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
float temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
float voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
batteryInfo.setText("Health: " + health + "\n" + "Icon small : "+icon_small+"\n" +
"Level : "+level+"\n"+"Present : "+present+"\n"+"Scale: "+
scale+"\n"+"Status :"+status+"\n"+ "Technology:"+technology+"\n"+
"Temperature :"+temp/10+"'C\n"+"Voltage:"+voltage/1000+"V\n"+"BATTERY_PROPERTY_CURRENT_AVERAGE = "
+ avgCurrent + "mAh"+"\n"+"BATTERY_PROPERTY_CURRENT_NOW = " + currentNow + "mAh"+"\n"+"count ="+count);
count++;
}
};
}
If you want to have a code run at fix interval, take a look at Alarm manager :
https://developer.android.com/reference/android/app/AlarmManager.html
Like Selvin said, the broadcast is called only when it change.
Related
so I've created an app which sets an alarm 25 mins before your departure time, based on the estimated time taken to travel from your place of departure to your destination.
I am able to build the app, but the app keeps crashing whenever I press the search button. I am guessing it has something to do with the integration of the placeautocomplete fragment, but not sure what about it.
Main Activity
package com.example.mobileassignment2.buildingblocks;
import android.app.AlarmManager;
import android.app.DialogFragment;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements TimePickerDialog .OnTimeSetListener{
String DistanceResult;
String DurationResult;
String LeaveByHour;
String LeaveByMin;
String AlarmTimeHour;
String AlarmTimeMin;
int ArriveHour;
int ArriveMin;
int AlarmHour;
int AlarmMin;
Calendar alarmCalendar;
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView textViewArriveByTime = (TextView)findViewById(R.id.textViewArriveByTime);
textViewArriveByTime.setText("Hour: "+ hourOfDay +"\n"+ "Minute: "+minute);
ArriveHour = hourOfDay;
ArriveMin = minute;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitiy_main);
Button button = (Button) findViewById(R.id.ArriveByBtn);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getFragmentManager(), "time picker");
}
});
Reset();
}
public void Reset(){
DistanceResult = "";
DurationResult = "";
TextView Distance_Output = (TextView) findViewById(R.id.DistanceResult);
TextView Duration_Output = (TextView) findViewById(R.id.DurationResult);
Distance_Output.setText("Distance: " + DistanceResult);
Duration_Output.setText("Duration: " + DurationResult);
LeaveByMin = "";
AlarmTimeMin = "";
TextView LeaveBy_Calculated = (TextView) findViewById(R.id.LeaveBy);
LeaveBy_Calculated.setText("Leave By: " + LeaveByMin);
TextView AlarmTime_Calculated = (TextView) findViewById(R.id.AlarmTime);
AlarmTime_Calculated.setText("Alarm Time: " + AlarmTimeMin);
TextView textViewArriveByTime = (TextView)findViewById(R.id.textViewArriveByTime);
textViewArriveByTime.setText("Hour: "+"\n"+ "Minute: ");
}
private static final String TAG = "MainActivity";
public void SearchDistanceCommand(View view) {
PlaceAutocompleteFragment Start_Location = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.StartLocation);
Start_Location.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
PlaceAutocompleteFragment Goal_Location = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.GoalLocation);
Goal_Location.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
Reset();
if(Start_Location.toString().isEmpty()|| Goal_Location.toString().isEmpty()){
Toast MissingTextErrorHandle = Toast.makeText(getApplicationContext(), "You need to input data into both fields!", Toast.LENGTH_SHORT);
MissingTextErrorHandle.show();
}
else
{
new AsyncTaskParseJson().execute();
}
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
EditText Start_Location = (EditText) findViewById(R.id.StartLocation);
EditText Goal_Location = (EditText) findViewById(R.id.GoalLocation);
//To convert to UTC, how to use time picker
// EditText Arrive_By = (EditText) findViewById(R.id.ArriveBy);
String FormattedStartLocation = Start_Location.getText().toString().replaceAll(" ", "+");
String FormattedGoalLocation = Goal_Location.getText().toString().replaceAll(" ", "+");
String yourServiceUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=" + FormattedStartLocation + "&destinations=" + FormattedGoalLocation
/* + "&arrival_time=" + Arrive_By*/
+ "&key=___MY___SECRET___KEY___";
#Override
protected void onPreExecute() {
ProgressBar spinner;
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
try {
httpConnect jParser = new httpConnect();
String json = jParser.getJSONFromUrl(yourServiceUrl);
JSONObject object = new JSONObject(json);
//contains ALL routes
JSONArray array = object.getJSONArray("rows");
// Get the first route
JSONObject route = array.getJSONObject(0);
// Take all elements
JSONArray elements = route.getJSONArray("elements");
//Take First Element
JSONObject element = elements.getJSONObject(0);
// Get Duration
JSONObject durationObject = element.getJSONObject("duration");
String duration = durationObject.getString("text");
DurationResult = duration;
// Get Distance
JSONObject distanceObject = element.getJSONObject("distance");
String distance = distanceObject.getString("text");
DistanceResult = distance;
//Get Leave By Time (ATTENTION!!: Need to edit for when duration > 1hr)
String sDMin = DurationResult;
//Nic: Remove Characters, Convert duration str to int, !!Assume duration is <1 Hr
sDMin = sDMin.replaceAll( " mins", "" );
int dMin = Integer.parseInt(sDMin);
int remMin = dMin % 60;
int remHour = dMin / 60;
int leaveHour = ArriveHour - remHour;
if (leaveHour < 0){
leaveHour = 23;
}
int leaveMin = ArriveMin - remMin -5;
if (leaveMin < 0){
leaveHour -= 1;
leaveMin += 60;
if (leaveHour < 0){
leaveHour = 23;
}
}
//Convert int to str for printing
String sLeaveHour = Integer.toString(leaveHour);
String sLeaveMin = Integer.toString(leaveMin);
LeaveByHour = sLeaveHour;
LeaveByMin = sLeaveMin;
//Get Alarm Time (int value), alarmManager later
//String sATMin = DurationResult;
//Nic: Remove Characters, Convert duration str to int, !!Assume duration is <1 Hr
//sATMin = sATMin.replaceAll( " mins", "" );
//int atMin = Integer.parseInt(sATMin);
/*int remAlarmMin = (atMin % 60) - 30;
int remAlarmHour = atMin / 60;
int alarmHour = ArriveHour - remAlarmHour;
int alarmMin = ArriveMin - remAlarmMin;
if (alarmMin < 0){
alarmHour -= 1;
alarmMin += 60;*/
int alarmHour = leaveHour;
if(alarmHour < 0){
alarmHour = 23;
}
int alarmMin = leaveMin - 30;
if (alarmMin < 0){
alarmHour -= 1;
alarmMin += 60;
if(alarmHour < 0){
alarmHour = 23;
}
}
//Set Global Variable to set calendar to set Alarm time
AlarmHour = alarmHour;
AlarmMin = alarmMin;
//Convert int to str for printing
String sAlarmHour = Integer.toString(alarmHour);
String sAlarmMin = Integer.toString(alarmMin);
AlarmTimeHour = sAlarmHour;
AlarmTimeMin = sAlarmMin;
Calendar calendar = Calendar.getInstance();
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
AlarmHour,
AlarmMin,
0);
alarmCalendar = calendar;
setAlarm(alarmCalendar.getTimeInMillis());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
if(DistanceResult == null || DurationResult == null){
Toast ResultErrorHandle = Toast.makeText(getApplicationContext(), "We could not find any results! Sorry!", Toast.LENGTH_SHORT);
ResultErrorHandle.show();
}
ProgressBar spinner;
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.INVISIBLE);
TextView Distance_Output = (TextView) findViewById(R.id.DistanceResult);
Distance_Output.setText("Distance: " + DistanceResult);
TextView Duration_Output = (TextView) findViewById(R.id.DurationResult);
Duration_Output.setText("Duration: " + DurationResult);
TextView LeaveBy_Calculated = (TextView) findViewById(R.id.LeaveBy);
LeaveBy_Calculated.setText("Leave By| Hour: " + LeaveByHour + " Min: " + LeaveByMin);
TextView AlarmTime_Calculated = (TextView) findViewById(R.id.AlarmTime);
AlarmTime_Calculated.setText("Alarm Time| Hour " + AlarmTimeHour + " Min: " + AlarmTimeMin);
}
}
public void CancelAlarmCommand(){
cancelAlarm();
}
public void setAlarm(long timeInMillis) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent,0);
AlarmManager.AlarmClockInfo ac= new AlarmManager.AlarmClockInfo(timeInMillis, pendingIntent.getBroadcast(this,0,intent,0));
alarmManager.setAlarmClock(ac,pendingIntent);
Toast.makeText(this, "Alarm set!", Toast.LENGTH_SHORT).show();
}
private void cancelAlarm(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent,0);
alarmManager.cancel(pendingIntent);
}
}
Gradle App
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "com.example.mobileassignment2.buildingblocks"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:25.3.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
implementation 'com.google.android.gms:play-services-places:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
<receiver
android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyC0UU_6yNvnroXuHBWPd2_SPfBP9Y29bp4"/>
</application>
logcat
09-05 00:04:22.519 1530-9975/? I/AudioFlinger: AudioFlinger's thread 0xe57037c0 tid=9975 ready to run 09-05 00:04:22.546 1530-1603/?
E/AudioFlinger: not enough memory for AudioTrack size=131296 09-05
00:04:22.548 1530-1603/? E/AudioFlinger: createRecordTrack_l()
initCheck failed -12; no control block? 09-05 00:04:22.554
2336-9720/com.google.android.googlequicksearchbox:search
E/AudioRecord: AudioFlinger could not create record track, status: -12
09-05 00:04:22.575
2336-9720/com.google.android.googlequicksearchbox:search
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization
check failed with status -12. 09-05 00:04:22.578
2336-9720/com.google.android.googlequicksearchbox:search
E/android.media.AudioRecord: Error code -20 when initializing native
AudioRecord object.
I have register battery low broadcast receiver.
Like this
import com.save.sharedpreference.SharedPreference;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;
public class BootReceiver extends BroadcastReceiver {
String user_phone_key = "phone_number";
int last_level = 0;
#Override
public void onReceive(Context context, Intent intent) {
int rlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rlevel >= 0 && scale > 0) {
level = (rlevel * 100) / scale;
}
if (level == 48 && last_level == level + 1) {
SharedPreference save_data = new SharedPreference(
context.getApplicationContext());
String phone = save_data.get_string(user_phone_key, null);
Toast.makeText(context, "Level Decrease", Toast.LENGTH_SHORT)
.show();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone, null,
"Your Battery level is less ", null, null);
} catch (Exception e) {
Toast.makeText(context.getApplicationContext(),
"SMS faild, please try again later!", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
last_level = level + 1;
}
}
Its working fine but the problem is when my battery level is reach 45% it start sending me sms until battery level change from 45%.
I want that when my battery level is reach 45% it just send me sms only one time and again waiting when battery level is 45%.
Is it possible?
Any help please.
Can you just use a local variable, like this?
public class BootReceiver extends BroadcastReceiver {
String user_phone_key = "phone_number";
int last_level = 0;
#Override
public void onReceive(Context context, Intent intent) {
int rlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rlevel >= 0 && scale > 0) {
level = (rlevel * 100) / scale;
}
if (level == 45 && last_level == 46) {
...
last_level = level;
}
}
I know it's not the most elegant solution, but it should work.
The more "official" solution is to use the ACTION_BATTERY_LOW intent to detect charge decreases, which IIRC only fires once, when the device hits low battery. Is there a reason you need to detect the battery level hitting 45%, in particular?
Create a boolean variable to send message only once.Like-
boolean isMsgSent=false;
and modify if loop as-
if(level==45 && !isMsgSent){
// send Msg
isMsgSent=true;
}
else{
isMsgSent=false;
}
It will send message only once when battery level is 45.
I have a problem. When there is entries stats activity works correctly. But If there is NO entries the stast activity crashes.
Please, help me. Need something to prevent it.
(I'm not programmer, so its not easy for me)
package com.sudarmuthu.android.wt.activities;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.sudarmuthu.android.wt.R;
import com.sudarmuthu.android.wt.data.DBUtil;
import com.sudarmuthu.android.wt.data.Entry;
/**
* Activity class to handle stats
*
public class EntriesStatsActivity extends Activity {
// for debugging
private static boolean D = true;
private static String TAG = "WT - EntriesStatsActivity";
private List<Entry> mEntries;
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entry_stats);
Bundle bundle = getIntent().getExtras();
int typeId = bundle.getInt("typeId");
if (D) Log.d(TAG, "Got type id: " + typeId);
mEntries = DBUtil.fetchEntries(this, typeId, null);
Entry firstEntry = mEntries.get(0);
int count = mEntries.size();
float sum = 0;
float average = 0;
float min = Float.parseFloat(firstEntry.getValue());
float max = Float.parseFloat(firstEntry.getValue());
// calculate
for (Entry entry : mEntries) {
float value = Float.parseFloat(entry.getValue());
sum += value;
if (value < min) {
min = value;
}
if (value > max) {
max = value;
}
}
average = sum / count;
// populate the values
TextView statsCount = (TextView) findViewById(R.id.statsCount);
statsCount.setText("" + count);
TextView statsSum = (TextView) findViewById(R.id.statsSum);
statsSum.setText("" + sum);
TextView statsAverage = (TextView) findViewById(R.id.statsAverage);
statsAverage.setText("" + average);
TextView valueFrom = (TextView) findViewById(R.id.valueFrom);
valueFrom.setText("" + min);
TextView valueTo = (TextView) findViewById(R.id.valueTo);
valueTo.setText("" + max);
}
}
You may get a null pointer exception :
mEntries = DBUtil.fetchEntries(this, typeId, null);
if( mEntries == null ) {
return;
}
If there is no Entries, mEntries.size() is equals to 0. So when you do
average = sum / count;
You divide by 0, which throws an Arithmetic Exception(you can't divide a number by 0).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to send SMS when the battery Level reached a particular value from a Service. I am not getting any errors but the SMS is not been sent.
MY CODE:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class BatteryStatus extends Service {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
String batteryNumber = "012345567";
String moderate=" Battery Level is 50 ";
String low = "Battery Level is low. Need to be charged immediately";
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(),"Service Running", Toast.LENGTH_SHORT).show();
//BATTERY STATUS
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
Log.e("NumberBattery ", "Number is "+batteryNumber);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
if(batteryNumber!=null && level==49){
SmsManager bat = SmsManager.getDefault();
bat.sendTextMessage(batteryNumber,null,moderate,null,null);
}else if(batteryNumber!=null && level==20){
SmsManager bat = SmsManager.getDefault();
bat.sendTextMessage(batteryNumber, null,low, null, null);
}
}
}
LOGCAT:
03-09 03:41:40.390: E/BatteryManager(11086): level is 49/100, temp is 321, voltage is 7574
03-09 03:41:40.390: E/NumberBattery(11086): Number is 01234567
Can you please tell what is wrong her?
It's because you never send the SMS.
When the following line is executed:
if (batteryNumber != null && level == 49){
level has not been initialized yet.
Change your code like this:
#Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
Log.e("NumberBattery ", "Number is "+batteryNumber);
if (batteryNumber != null && level == 49) {
SmsManager bat = SmsManager.getDefault();
bat.sendTextMessage(batteryNumber,null,moderate,null,null);
} else if(batteryNumber!=null && level==20){
SmsManager bat = SmsManager.getDefault();
bat.sendTextMessage(batteryNumber, null,low, null, null);
}
}
I am planning to create a world clock widget in android. The clock should show the selected country's time as an analog clock widget. But I'm feeling difficulties as I'm a beginner in android.
My widget.xml file contains the following:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Widget"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="8dip"
android:background="#drawable/myshape" >
<AnalogClock android:id="#+id/AnalogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dial="#drawable/widgetdial"
android:hand_hour="#drawable/widgethour"
android:hand_minute="#drawable/widgetminute"/>
I am using the following configuration activity for my widget:-
(To display the city list)
package nEx.Software.Tutorials.Widgets.AnalogClock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AnalogClock;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConfigureApp extends Activity {
DateFormat df;
private ListView cityList;
public static String[][] citylist = new String[1242][10];
String[] cities = new String[1242];
String field[] = new String[20];
String list[][] = new String[1242][10];
String country = "";
String line = null;
int row = 0;
int col = 0;
// Variables for list view population
String city = "";
int position = 0;
public int[] listArray = new int[1242];
public static int len = 0;
public String[][] adapterCityList = new String[1242][3];
// Variables for passing intent data
public static final String citieslist = "com.world.citieslist";
AppWidgetManager awm;
Context c;
int awID;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
try {
citylist = getCityList();
} catch (IOException e) {
Log.e("Loading CityList", e.getMessage());
}
for (int i = 0; i < 1242; i++) {
cities[i] = citylist[i][0];
}
// Set the view layout resource to use.
setContentView(R.layout.configure);
c = ConfigureApp.this;
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
awID = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
} else{
finish();
}
awm = AppWidgetManager.getInstance(c);
cityList=(ListView)findViewById(R.id.CityList);
// By using setAdpater method in listview we an add string array in list.
cityList.setAdapter(new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, cities));
// cityList.setOnItemClickListener(cityListListener);
cityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str = ((TextView) v).getText().toString();
RemoteViews remoteViews = new RemoteViews(c.getPackageName(),
R.layout.widget);
remoteViews.setTextViewText(R.id.mytext, str);
remoteViews.setTextViewText(R.id.date, df.format(new Date()));
Intent in = new Intent(c,clock.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, 0);
remoteViews.setOnClickPendingIntent(R.id.Widget, pi);
awm.updateAppWidget(awID, remoteViews);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,awID);
setResult(RESULT_OK, result);
finish();
}
});
}
private String[][] getCityList() throws IOException {
Context context = getApplicationContext();
InputStream instream = context.getResources().openRawResource(R.raw.cities_final);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while ((line = buffreader.readLine()) != null) {
field = line.split(",");
for (String x : field) {
list[row][col] = x;
col++;
if (x != null) {
country = x;
}
}
list[row][2] = country;
row++;
col = 0;
}
for (int i = 0; (i < list.length); i++) {
for (int j = 0; (j < 3); j++) {
if (j == 1) {
list[i][j] = list[i][j].substring(0, 6);
}
}
}
}
return list;
}
}
Can I use my own custom view in the widget, apart from analog clock? Or is there any other way to show the clock? like use the Imageview as the clock face and to draw the dial according to the time?
Please help me regarding this.!!!:(
A similar example for thermometer is given in this link
http://mindtherobot.com/blog/272/android-custom-ui-making-a-vintage-thermometer/
You can create your own view and make the clock as well.
You can replaced the clock dial, clock hand minute and clock hand hour with your own drawings. Then You'll have your own custom clock.
android:dial="#drawable/YOUR_OWN_DIAL"
android:hand_hour="#drawable/YOUR_OWN_HOUR"
android:hand_minute="#drawable/YOUR_OWN_MINUTE"
Test the layout in the Graphical Layout Tool to see how it look like.