Multiple changes

This commit is contained in:
Tommaso Berlose
2017-10-15 19:39:15 +02:00
parent 891977612e
commit 0ec3dcbadb
50 changed files with 923 additions and 428 deletions

View File

@ -14,6 +14,7 @@ object Constants {
val LOCATION_REQUEST_CODE = 2
val CALENDAR_APP_REQUEST_CODE = 3
val WEATHER_APP_REQUEST_CODE = 4
val WEATHER_PROVIDER_REQUEST_CODE = 5
val RESULT_CODE_CUSTOM_LOCATION = 45
@ -45,6 +46,7 @@ object Constants {
val PREF_CALENDAR_APP_PACKAGE = "PREF_CALENDAR_APP_PACKAGE"
val PREF_WEATHER_APP_NAME = "PREF_WEATHER_APP_NAME"
val PREF_WEATHER_APP_PACKAGE = "PREF_WEATHER_APP_PACKAGE"
val PREF_WEATHER_PROVIDER_API_KEY = "PREF_WEATHER_PROVIDER_API_KEY"
val itDateFormat = SimpleDateFormat("EEEE, d MMM")
val engDateFormat = SimpleDateFormat("EEEE, MMM d")

View File

@ -18,7 +18,7 @@ class WeatherReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action.equals(Intent.ACTION_BOOT_COMPLETED) || intent.action.equals(Intent.ACTION_MY_PACKAGE_REPLACED)) {
setUpdates(context)
} else if (intent.action.equals(Constants.ACTION_WEATHER_UPDATE)) {
} else if (intent.action.equals(Constants.ACTION_WEATHER_UPDATE) || intent.action.equals("android.location.PROVIDERS_CHANGED")) {
WeatherUtil.updateWeather(context)
}
}

View File

@ -19,13 +19,15 @@ import android.widget.ArrayAdapter
import com.tommasoberlose.anotherwidget.`object`.ApplicationListEvent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import com.tommasoberlose.anotherwidget.ui.adapter.ApplicationInfoAdapter
class ChooseApplicationActivity : AppCompatActivity() {
lateinit var adapter: ArrayAdapter<String>
lateinit var adapter: ApplicationInfoAdapter
val appList = ArrayList<ApplicationInfo>()
val appListFiltered = ArrayList<ApplicationInfo>()
@ -38,16 +40,20 @@ class ChooseApplicationActivity : AppCompatActivity() {
selectDefaultApp()
}
adapter = ArrayAdapter(this, R.layout.custom_location_item, appList.map { it.name })
list_view.adapter = adapter
list_view.setHasFixedSize(true);
val mLayoutManager = LinearLayoutManager(this);
list_view.layoutManager = mLayoutManager;
list_view.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
adapter = ApplicationInfoAdapter(this, appListFiltered);
list_view.setAdapter(adapter);
/*list_view.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
val resultIntent = Intent()
resultIntent.putExtra(Constants.RESULT_APP_NAME, pm.getApplicationLabel(appListFiltered[position]).toString())
resultIntent.putExtra(Constants.RESULT_APP_PACKAGE, appListFiltered[position].packageName)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}*/
location.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(text: Editable?) {
@ -95,20 +101,12 @@ class ChooseApplicationActivity : AppCompatActivity() {
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
fun onMessageEvent(event: ApplicationListEvent) {
val pm = packageManager
adapter.clear()
if (!event.filtered) {
appList.clear()
event.apps.mapTo(appList, {it})
for (a:ApplicationInfo in appList) {
adapter.add(pm.getApplicationLabel(a).toString())
}
}
appListFiltered.clear()
event.apps.mapTo(appListFiltered, {it})
for (a:ApplicationInfo in appListFiltered) {
adapter.add(pm.getApplicationLabel(a).toString())
}
adapter.notifyDataSetChanged()
adapter.changeData(appListFiltered)
}
}

View File

@ -24,12 +24,14 @@ import com.tommasoberlose.anotherwidget.util.CalendarUtil
import com.tommasoberlose.anotherwidget.util.WeatherUtil
import android.content.DialogInterface
import android.graphics.drawable.Drawable
import android.support.design.widget.BottomSheetDialog
import android.util.Log
import android.widget.Toast
import com.crashlytics.android.Crashlytics
import com.tommasoberlose.anotherwidget.`object`.CalendarSelector
import io.fabric.sdk.android.Fabric
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.main_menu_layout.view.*
import kotlinx.android.synthetic.main.the_widget.*
@ -55,10 +57,6 @@ class MainActivity : AppCompatActivity() {
AppWidgetManager.INVALID_APPWIDGET_ID)
if (mAppWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
action_refresh.visibility = View.GONE
action_support.visibility = View.GONE
action_share.visibility = View.GONE
action_add_widget.visibility = View.VISIBLE
action_add_widget.setOnClickListener {
@ -67,22 +65,47 @@ class MainActivity : AppCompatActivity() {
}
}
action_support.setOnClickListener(object: View.OnClickListener {
override fun onClick(p0: View?) {
Util.openURI(this@MainActivity, "https://paypal.me/tommasoberlose")
}
})
action_share.setOnClickListener(object: View.OnClickListener {
override fun onClick(p0: View?) {
Util.share(this@MainActivity)
}
})
action_refresh.setOnClickListener {
WeatherUtil.updateWeather(this)
CalendarUtil.updateEventList(this)
Util.updateWidget(this)
action_menu.setOnClickListener {
val mBottomSheetDialog: BottomSheetDialog = BottomSheetDialog(this)
val menuView: View = getLayoutInflater().inflate(R.layout.main_menu_layout, null)
menuView.action_support.setOnClickListener(object: View.OnClickListener {
override fun onClick(p0: View?) {
Util.openURI(this@MainActivity, "https://paypal.me/tommasoberlose")
mBottomSheetDialog.dismiss()
}
})
menuView.action_share.setOnClickListener(object: View.OnClickListener {
override fun onClick(p0: View?) {
Util.share(this@MainActivity)
mBottomSheetDialog.dismiss()
}
})
menuView.action_rate.setOnClickListener(object: View.OnClickListener {
override fun onClick(p0: View?) {
Util.rateApp(this@MainActivity, "https://play.google.com/store/apps/details?id=com.tommasoberlose.anotherwidget")
mBottomSheetDialog.dismiss()
}
})
menuView.action_feedback.setOnClickListener(object: View.OnClickListener {
override fun onClick(p0: View?) {
Util.sendEmail(this@MainActivity)
mBottomSheetDialog.dismiss()
}
})
menuView.action_refresh.setOnClickListener {
WeatherUtil.updateWeather(this)
CalendarUtil.updateEventList(this)
Util.updateWidget(this)
mBottomSheetDialog.dismiss()
}
mBottomSheetDialog.setContentView(menuView)
mBottomSheetDialog.show();
}
}
@ -125,8 +148,13 @@ class MainActivity : AppCompatActivity() {
updateSettings()
}
Constants.LOCATION_REQUEST_CODE -> if (!(permissions.size != 1 || grantResults.size != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED)) {
WeatherUtil.updateWeather(this)
updateAppWidget()
val SP = PreferenceManager.getDefaultSharedPreferences(this)
if (SP.getString(Constants.PREF_WEATHER_PROVIDER_API_KEY, "").equals("")) {
startActivityForResult(Intent(this, WeatherProviderActivity::class.java), Constants.WEATHER_PROVIDER_REQUEST_CODE)
} else {
WeatherUtil.updateWeather(this)
updateAppWidget()
}
updateSettings()
}
}
@ -169,6 +197,9 @@ class MainActivity : AppCompatActivity() {
Util.updateWidget(this)
updateSettings()
updateAppWidget()
} else if (requestCode == Constants.WEATHER_PROVIDER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
sendBroadcast(Intent(Constants.ACTION_WEATHER_UPDATE))
updateSettings()
}
}
@ -179,9 +210,9 @@ class MainActivity : AppCompatActivity() {
empty_layout.visibility = View.VISIBLE
calendar_layout.visibility = View.GONE
var dateStringValue: String = String.format("%s%s", Constants.engDateFormat.format(now.time)[0].toUpperCase(), Constants.engDateFormat.format(now.time).substring(1))
var dateStringValue: String = Util.getCapWordString(Constants.engDateFormat.format(now.time))
if (SP.getBoolean(Constants.PREF_ITA_FORMAT_DATE, false)) {
dateStringValue = String.format("%s%s", Constants.itDateFormat.format(now.time)[0].toUpperCase(), Constants.itDateFormat.format(now.time).substring(1))
dateStringValue = Util.getCapWordString(Constants.itDateFormat.format(now.time))
}
empty_date.text = dateStringValue
//empty_date.setImageBitmap(Util.buildUpdate(this, String.format("%s%s", Constants.dateFormat.format(now.time)[0].toUpperCase(), Constants.dateFormat.format(now.time).substring(1)), "fonts/product_sans_regular.ttf"))
@ -241,7 +272,7 @@ class MainActivity : AppCompatActivity() {
fun updateLocationView() {
val SP = PreferenceManager.getDefaultSharedPreferences(this)
val locationLayout = SP.getBoolean(Constants.PREF_SHOW_WEATHER, true) && Util.checkGrantedPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
val locationLayout = SP.getBoolean(Constants.PREF_SHOW_WEATHER, true)
if (locationLayout && SP.contains(Constants.PREF_WEATHER_TEMP) && SP.contains(Constants.PREF_WEATHER_ICON)) {
weather.visibility = View.VISIBLE
@ -408,6 +439,17 @@ class MainActivity : AppCompatActivity() {
startActivityForResult(Intent(this, ChooseApplicationActivity::class.java), Constants.WEATHER_APP_REQUEST_CODE)
}
if (!SP.getString(Constants.PREF_WEATHER_PROVIDER_API_KEY, "").equals("")) {
label_weather_provider_api_key.text = getString(R.string.settings_weather_provider_api_key_subtitle_all_set)
alert_icon.visibility = View.GONE
} else {
label_weather_provider_api_key.text = getString(R.string.settings_weather_provider_api_key_subtitle_not_set)
alert_icon.visibility = View.VISIBLE
}
action_weather_provider_api_key.setOnClickListener {
startActivityForResult(Intent(this, WeatherProviderActivity::class.java), Constants.WEATHER_PROVIDER_REQUEST_CODE)
}
action_filter_calendar.setOnClickListener {
val calendarSelectorList: List<CalendarSelector> = CalendarUtil.getCalendarList(this)
var calFiltered = SP.getString(Constants.PREF_CALENDAR_FILTER, "")

View File

@ -0,0 +1,71 @@
package com.tommasoberlose.anotherwidget.ui.activity
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.tommasoberlose.anotherwidget.R
import com.tommasoberlose.anotherwidget.`object`.Constants
import kotlinx.android.synthetic.main.activity_weather_provider.*
class WeatherProviderActivity : AppCompatActivity() {
@SuppressLint("ApplySharedPref")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_weather_provider)
val SP = PreferenceManager.getDefaultSharedPreferences(this)
action_paste.setOnClickListener {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
api_key.setText(clipboard.primaryClip.getItemAt(0).text)
}
action_save.setOnClickListener {
SP.edit()
.putString(Constants.PREF_WEATHER_PROVIDER_API_KEY, api_key.text.toString())
.commit()
setResult(Activity.RESULT_OK)
finish()
}
api_key.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(text: Editable?) {
if (text.toString().equals("") || text.toString().equals(SP.getString(Constants.PREF_WEATHER_PROVIDER_API_KEY, ""))) {
action_save.animate().scaleY(-2f).start()
} else {
action_save.animate().scaleY(0f).start()
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
}
override fun onBackPressed() {
val SP = PreferenceManager.getDefaultSharedPreferences(this)
if (api_key.text.toString().equals("") || !api_key.text.toString().equals(SP.getString(Constants.PREF_WEATHER_PROVIDER_API_KEY, ""))) {
AlertDialog.Builder(this)
.setTitle(getString(R.string.error_weather_api_key))
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, DialogInterface.OnClickListener { _,_ ->
super.onBackPressed()
})
.show()
} else {
super.onBackPressed()
}
}
}

View File

@ -0,0 +1,44 @@
package com.tommasoberlose.anotherwidget.ui.adapter
import android.content.Context
import android.content.pm.ApplicationInfo
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.tommasoberlose.anotherwidget.R
import java.io.File
/**
* Created by tommaso on 15/10/17.
*/
class ApplicationInfoAdapter (private val context: Context, private var mDataset: ArrayList<ApplicationInfo>) : RecyclerView.Adapter<ApplicationInfoAdapter.ViewHolder>() {
class ViewHolder(var view: View, var text: TextView, var icon: ImageView) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.application_info_layout, parent, false)
return ViewHolder(v, v.findViewById(R.id.text), v.findViewById(R.id.icon))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val pm = context.packageManager
holder.text.text = pm.getApplicationLabel(mDataset[position]).toString()
try {
holder.icon.setImageDrawable(mDataset[position].loadIcon(pm))
} catch (ignore: Exception) {
}
}
override fun getItemCount(): Int {
return mDataset.size
}
fun changeData(newData: ArrayList<ApplicationInfo>) {
mDataset = newData
notifyDataSetChanged()
}
}

View File

@ -80,9 +80,9 @@ class TheWidget : AppWidgetProvider() {
views.setViewVisibility(R.id.empty_layout, View.VISIBLE)
views.setViewVisibility(R.id.calendar_layout, View.GONE)
var dateStringValue: String = String.format("%s%s", Constants.engDateFormat.format(now.time)[0].toUpperCase(), Constants.engDateFormat.format(now.time).substring(1))
var dateStringValue: String = Util.getCapWordString(Constants.engDateFormat.format(now.time))
if (SP.getBoolean(Constants.PREF_ITA_FORMAT_DATE, false)) {
dateStringValue = String.format("%s%s", Constants.itDateFormat.format(now.time)[0].toUpperCase(), Constants.itDateFormat.format(now.time).substring(1))
dateStringValue = Util.getCapWordString(Constants.itDateFormat.format(now.time))
}
views.setTextViewText(R.id.empty_date, dateStringValue)
//views.setImageViewBitmap(R.id.empty_date, Util.buildUpdate(context, Constants.dateFormat.format(now.time)[0].toUpperCase() + Constants.dateFormat.format(now.time).substring(1), "fonts/product_sans_regular.ttf"))
@ -158,7 +158,7 @@ class TheWidget : AppWidgetProvider() {
fun updateLocationView(context: Context, views: RemoteViews, widgetID: Int): RemoteViews {
val SP = PreferenceManager.getDefaultSharedPreferences(context)
val locationLayout = SP.getBoolean(Constants.PREF_SHOW_WEATHER, true) && Util.checkGrantedPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
val locationLayout = SP.getBoolean(Constants.PREF_SHOW_WEATHER, true)
if (locationLayout && SP.contains(Constants.PREF_WEATHER_TEMP) && SP.contains(Constants.PREF_WEATHER_ICON)) {
views.setViewVisibility(R.id.weather, View.VISIBLE)

View File

@ -22,74 +22,78 @@ object CalendarUtil {
fun updateEventList(context: Context) {
val SP: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val eventList = ArrayList<Event>()
if (SP.getBoolean(Constants.PREF_SHOW_EVENTS, true)) {
val eventList = ArrayList<Event>()
val now = Calendar.getInstance()
val limit = Calendar.getInstance()
when (SP.getInt(Constants.PREF_SHOW_UNTIL, 1)) {
0 -> limit.add(Calendar.HOUR, 3)
1 -> limit.add(Calendar.HOUR, 6)
2 -> limit.add(Calendar.HOUR, 12)
3 -> limit.add(Calendar.DAY_OF_MONTH, 1)
4 -> limit.add(Calendar.DAY_OF_MONTH, 3)
5 -> limit.add(Calendar.DAY_OF_MONTH, 7)
else -> limit.add(Calendar.HOUR, 6)
}
val builder = CalendarContract.Instances.CONTENT_URI.buildUpon()
ContentUris.appendId(builder, now.timeInMillis)
ContentUris.appendId(builder, limit.timeInMillis)
if (!Util.checkGrantedPermission(context, Manifest.permission.READ_CALENDAR)) {
resetNextEventData(context)
} else {
val instanceCursor = context.contentResolver.query(builder.build(), arrayOf(CalendarContract.Instances.EVENT_ID, CalendarContract.Instances.BEGIN, CalendarContract.Instances.END), null, null, null)
if (instanceCursor != null && instanceCursor.count > 0) {
instanceCursor.moveToFirst()
for (i in 0 until instanceCursor.count) {
val ID = instanceCursor.getInt(0)
val eventCursor = context.contentResolver.query(CalendarContract.Events.CONTENT_URI, arrayOf(CalendarContract.Events.TITLE, CalendarContract.Events.ALL_DAY, CalendarContract.Events.CALENDAR_ID),
CalendarContract.Events._ID + " is ?",
arrayOf(Integer.toString(ID)), null)
if (eventCursor != null && eventCursor.count > 0) {
eventCursor.moveToFirst()
for (j in 0 until eventCursor.count) {
val e = Event(eventCursor, instanceCursor)
val allDay: Boolean = !eventCursor.getString(1).equals("0")
if ((SP.getBoolean(Constants.PREF_CALENDAR_ALL_DAY, false) || !allDay) && !(SP.getString(Constants.PREF_CALENDAR_FILTER, "").contains(" " + e.calendarID + ","))) {
eventList.add(e)
}
eventCursor.moveToNext()
}
}
eventCursor.close()
instanceCursor.moveToNext()
}
val now = Calendar.getInstance()
val limit = Calendar.getInstance()
when (SP.getInt(Constants.PREF_SHOW_UNTIL, 1)) {
0 -> limit.add(Calendar.HOUR, 3)
1 -> limit.add(Calendar.HOUR, 6)
2 -> limit.add(Calendar.HOUR, 12)
3 -> limit.add(Calendar.DAY_OF_MONTH, 1)
4 -> limit.add(Calendar.DAY_OF_MONTH, 3)
5 -> limit.add(Calendar.DAY_OF_MONTH, 7)
else -> limit.add(Calendar.HOUR, 6)
}
instanceCursor.close()
if (eventList.isEmpty()) {
val builder = CalendarContract.Instances.CONTENT_URI.buildUpon()
ContentUris.appendId(builder, now.timeInMillis)
ContentUris.appendId(builder, limit.timeInMillis)
if (!Util.checkGrantedPermission(context, Manifest.permission.READ_CALENDAR)) {
resetNextEventData(context)
} else {
Collections.sort(eventList, { event: Event, event1: Event ->
if (event.startDate > event1.startDate) {
return@sort 1
} else if (event.startDate < event1.startDate) {
return@sort -1
val instanceCursor = context.contentResolver.query(builder.build(), arrayOf(CalendarContract.Instances.EVENT_ID, CalendarContract.Instances.BEGIN, CalendarContract.Instances.END), null, null, null)
if (instanceCursor != null && instanceCursor.count > 0) {
instanceCursor.moveToFirst()
for (i in 0 until instanceCursor.count) {
val ID = instanceCursor.getInt(0)
val eventCursor = context.contentResolver.query(CalendarContract.Events.CONTENT_URI, arrayOf(CalendarContract.Events.TITLE, CalendarContract.Events.ALL_DAY, CalendarContract.Events.CALENDAR_ID),
CalendarContract.Events._ID + " is ?",
arrayOf(Integer.toString(ID)), null)
if (eventCursor != null && eventCursor.count > 0) {
eventCursor.moveToFirst()
for (j in 0 until eventCursor.count) {
val e = Event(eventCursor, instanceCursor)
val allDay: Boolean = !eventCursor.getString(1).equals("0")
if ((SP.getBoolean(Constants.PREF_CALENDAR_ALL_DAY, false) || !allDay) && !(SP.getString(Constants.PREF_CALENDAR_FILTER, "").contains(" " + e.calendarID + ","))) {
eventList.add(e)
}
eventCursor.moveToNext()
}
}
eventCursor.close()
instanceCursor.moveToNext()
}
return@sort 0
})
saveNextEventData(context, eventList.get(0))
}
instanceCursor.close()
if (eventList.isEmpty()) {
resetNextEventData(context)
} else {
Collections.sort(eventList, { event: Event, event1: Event ->
if (event.startDate > event1.startDate) {
return@sort 1
} else if (event.startDate < event1.startDate) {
return@sort -1
}
return@sort 0
})
saveNextEventData(context, eventList.get(0))
}
}
} else {
resetNextEventData(context)
}
}

View File

@ -27,6 +27,7 @@ import android.util.TypedValue
import android.content.Intent
import android.content.ComponentName
import android.preference.PreferenceManager
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import com.tommasoberlose.anotherwidget.`object`.Constants
@ -76,10 +77,10 @@ object Util {
fun openURI(context: Context, url: String) {
try {
val builder: CustomTabsIntent.Builder = CustomTabsIntent.Builder();
builder.setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary));
val customTabsIntent: CustomTabsIntent = builder.build();
customTabsIntent.launchUrl(context, Uri.parse(url));
val builder: CustomTabsIntent.Builder = CustomTabsIntent.Builder()
builder.setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary))
val customTabsIntent: CustomTabsIntent = builder.build()
customTabsIntent.launchUrl(context, Uri.parse(url))
} catch (e: Exception) {
try {
val openIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url));
@ -91,10 +92,11 @@ object Util {
Toast.makeText(context, R.string.error_opening_uri, Toast.LENGTH_LONG).show()
}
}
val clipboard:ClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(context.getString(R.string.app_name), url);
clipboard.primaryClip = clip;
Toast.makeText(context, R.string.error_opening_uri, Toast.LENGTH_LONG).show()
}
fun rateApp(context: Context, url: String) {
val openIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(openIntent)
}
fun share(context: Context) {
@ -229,4 +231,55 @@ object Util {
}
}
fun getCapWordString(text: String): String {
return try {
val ar = text.split(" ")
var newText = ""
for (t: String in ar) {
newText += " "
newText += t.substring(0, 1).toUpperCase()
newText += t.substring(1)
}
newText.substring(1)
} catch (e: Exception) {
text
}
}
fun showLocationNotification(context: Context, show: Boolean) {
val mNotificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
if (show) {
val mBuilder: NotificationCompat.Builder = NotificationCompat.Builder(context, "Settings")
.setSmallIcon(R.drawable.ic_stat_name)
.setPriority(Notification.PRIORITY_MIN)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setContentTitle(context.getString(R.string.notification_gps_title))
.setContentText(context.getString(R.string.notification_gps_subtitle))
.setAutoCancel(true);
val intent: Intent = Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
val pi: PendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(1, mBuilder.build());
} else {
mNotificationManager.cancel(1);
}
}
fun sendEmail(context: Context) {
val i:Intent = Intent(Intent.ACTION_SEND)
i.type = "message/rfc822"
i.putExtra(Intent.EXTRA_EMAIL, arrayOf("tommaso.berlose@gmail.com"))
i.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.feedback_title))
try {
context.startActivity(Intent.createChooser(i, context.getString(R.string.feedback_chooser_title)))
} catch (ex: Exception) {
Toast.makeText(context, R.string.feedback_error, Toast.LENGTH_SHORT).show();
}
}
}

View File

@ -15,6 +15,13 @@ import com.survivingwithandroid.weather.lib.provider.openweathermap.Openweatherm
import com.survivingwithandroid.weather.lib.request.WeatherRequest
import com.tommasoberlose.anotherwidget.R
import com.tommasoberlose.anotherwidget.`object`.Constants
import android.content.DialogInterface
import android.support.v4.content.ContextCompat.startActivity
import android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS
import android.content.Intent
import android.location.LocationManager
/**
@ -22,41 +29,73 @@ import com.tommasoberlose.anotherwidget.`object`.Constants
*/
object WeatherUtil {
val API_KEY_1 = "43e744ad8ff91b09ea62dbc7d0e7c1dd"
val API_KEY_2 = "61cde158f4bcc2e5cd18de7b9d000702"
fun updateWeather(context: Context) {
Util.showLocationNotification(context, false)
val SP: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
if (SP.getString(Constants.PREF_CUSTOM_LOCATION_ADD, "").equals("") || SP.getString(Constants.PREF_CUSTOM_LOCATION_LAT, "").equals("") || SP.getString(Constants.PREF_CUSTOM_LOCATION_LON, "").equals("")) {
if (!Util.checkGrantedPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)) {
return
}
var gpsEnabled = false
var networkEnabled = false
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
getCurrentWeather(context, locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER))
getCurrentWeather(context, locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER))
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
} catch (ex: Exception) {
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f, object : LocationListener {
override fun onLocationChanged(location: Location) {
locationManager.removeUpdates(this)
getCurrentWeather(context, location)
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (ex: Exception) {
}
@SuppressLint("ApplySharedPref")
override fun onProviderDisabled(p0: String?) {
}
if (!gpsEnabled && !networkEnabled) {
Util.showLocationNotification(context, true)
} else {
if (gpsEnabled) {
getCurrentWeather(context, locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, object : LocationListener {
override fun onLocationChanged(location: Location) {
locationManager.removeUpdates(this)
getCurrentWeather(context, location)
}
@SuppressLint("ApplySharedPref")
override fun onProviderEnabled(p0: String?) {
}
@SuppressLint("ApplySharedPref")
override fun onProviderDisabled(p0: String?) {
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
@SuppressLint("ApplySharedPref")
override fun onProviderEnabled(p0: String?) {
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
}
})
} else {
getCurrentWeather(context, locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f, object : LocationListener {
override fun onLocationChanged(location: Location) {
locationManager.removeUpdates(this)
getCurrentWeather(context, location)
}
@SuppressLint("ApplySharedPref")
override fun onProviderDisabled(p0: String?) {
}
@SuppressLint("ApplySharedPref")
override fun onProviderEnabled(p0: String?) {
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
}
})
}
})
}
} else {
weatherNetworkRequest(context, SP.getString(Constants.PREF_CUSTOM_LOCATION_LAT, "").toDouble(), SP.getString(Constants.PREF_CUSTOM_LOCATION_LON, "").toDouble())
}
}
@ -69,42 +108,45 @@ object WeatherUtil {
fun weatherNetworkRequest(context: Context, latitude: Double, longitude: Double) {
val SP: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
if (!SP.getString(Constants.PREF_WEATHER_PROVIDER_API_KEY, "").equals("")) {
try {
val config = WeatherConfig()
config.unitSystem = if (SP.getString(Constants.PREF_WEATHER_TEMP_UNIT, "F").equals("C")) WeatherConfig.UNIT_SYSTEM.M else WeatherConfig.UNIT_SYSTEM.I
config.lang = "en"
config.maxResult = 1
config.numDays = 1
config.ApiKey = SP.getString(Constants.PREF_WEATHER_PROVIDER_API_KEY, "")
try {
val config = WeatherConfig()
config.unitSystem = if (SP.getString(Constants.PREF_WEATHER_TEMP_UNIT, "F").equals("C")) WeatherConfig.UNIT_SYSTEM.M else WeatherConfig.UNIT_SYSTEM.I
config.lang = "en" // If you want to use english
config.maxResult = 1 // Max number of cities retrieved
config.numDays = 1 // Max num of days in the forecast
config.ApiKey = API_KEY_2
val client = WeatherClient.ClientBuilder().attach(context)
.httpClient(com.survivingwithandroid.weather.lib.client.volley.WeatherClientDefault::class.java)
.provider(OpenweathermapProviderType())
.config(config)
.build()
val client = WeatherClient.ClientBuilder().attach(context)
.httpClient(com.survivingwithandroid.weather.lib.client.volley.WeatherClientDefault::class.java)
.provider(OpenweathermapProviderType())
.config(config)
.build()
client.getCurrentCondition(WeatherRequest(longitude, latitude), object : WeatherClient.WeatherEventListener {
@SuppressLint("ApplySharedPref")
override fun onWeatherRetrieved(currentWeather: CurrentWeather) {
SP.edit()
.putFloat(Constants.PREF_WEATHER_TEMP, currentWeather.weather.temperature.temp)
.putString(Constants.PREF_WEATHER_ICON, currentWeather.weather.currentCondition.icon)
.commit()
Util.updateWidget(context)
}
client.getCurrentCondition(WeatherRequest(longitude, latitude), object : WeatherClient.WeatherEventListener {
@SuppressLint("ApplySharedPref")
override fun onWeatherRetrieved(currentWeather: CurrentWeather) {
SP.edit()
.putFloat(Constants.PREF_WEATHER_TEMP, currentWeather.weather.temperature.temp)
.putString(Constants.PREF_WEATHER_ICON, currentWeather.weather.currentCondition.icon)
.commit()
Util.updateWidget(context)
}
@SuppressLint("ApplySharedPref")
override fun onWeatherError(e: WeatherLibException?) {
// removeWeather(context, SP)
}
@SuppressLint("ApplySharedPref")
override fun onWeatherError(e: WeatherLibException?) {
removeWeather(context, SP)
}
@SuppressLint("ApplySharedPref")
override fun onConnectionError(throwable: Throwable?) {
removeWeather(context, SP)
}
})
} catch (t: Exception) {
@SuppressLint("ApplySharedPref")
override fun onConnectionError(throwable: Throwable?) {
// removeWeather(context, SP)
}
})
} catch (t: Exception) {
// removeWeather(context, SP)
}
} else {
removeWeather(context, SP)
}
}