Monitoring BATTERY_CHANGED with BroadcastReceiver and displaying with level-list not working - broadcastreceiver

Hello everyone I've been stick with this problem, and I can't see my mistake. I had used before basicly for having different drawable bind to a specific level, nevertheless I am trying to use it within a BroadcastReceiver wich monitor battery changes, the problem is that I don't get any UI update when I called the setImageLevel change?
The Broadcast Receiver goes like this
public class BatteryReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG, "Fired Changed");
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level * 100) / scale;
imageBattery = (ImageView) findViewById(R.id.imageBatery);
imageBattery.setImageLevel(percent);
Log.d(LOG, "On UI running I am");
// imageBattery.getDrawable().mutate();
// imageBattery.invalidate();
// Log.d(LOG,"DRawable: "+((LevelListDrawable)imageBattery.getDrawable()).getCurrent());
}
}
The Log gets displayed but it does not change my ImageView if you can point me out in the right direction, or you have any insight on this issue?
Little bit of more info
Here is my Registration and unregistration both on the same activity as the BroadcastReceiver
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.BATTERY_CHANGED");
registerReceiver(receiver, filter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
How do I instatiate the ImageView Drawable:
<ImageView
android:id="#+id/imageBatery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/battery_status" />
And also battery_status.xml is a drawable (I removed some of the drawable item because you get the idea I have from 0-100)
<item
android:drawable="#drawable/stat_sys_battery_100"
android:maxLevel="100"/>
<item
android:drawable="#drawable/stat_sys_battery_90"
android:maxLevel="90"/>
<item
android:drawable="#drawable/stat_sys_battery_80"
android:maxLevel="80"/>

Do You have your BroadcastReceiver inlined in Your Activity? If so, use 'MyActivity.this.runOnUiThread()` method to change Your views.

your problem is in images
LevelListDrawable doesn't append new image when level changed, it just shows the image for level you've set
try differen images and you'll see what I mean

try this in your onCreate:
imageBattery = (ImageView) findViewById(R.id.imageBatery);
for (int i = 0; i < 10; i++) {
imageBattery.setImageLevel(i * 10);
}
is smth changed ?

Related

How to make this kind of animation in Flutter?

Video reference
please check the link above to see the animation.
The one in the video is made in Java, An imageView changing images using UniversalImageLoader in 2500 milliseconds interval with a Handler.
JavaCode:
int imgs[] = {R.drawable.efone, R.drawable.eftwo, R.drawable.efthree, R.drawable.effour, R.drawable.effive};
backgroundSlide = (ImageView) findViewById(R.id.bgSlide);
backgroundSlide.setImageResource(R.drawable.efone);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i = 0;
#Override
public void run() {
if (i > imgs.length - 1)
i = 0;
backgroundSlide.startAnimation(animAlpha);
ImageLoader.getInstance().displayImage("drawable://" + imgs[i], backgroundSlide);
i++;
handler.postDelayed(runnable, 2500);
}
};
Xml:
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="#+id/bgSlide"
android:src="#drawable/efone" />
Giving you hint:
First add
import 'dart:async';
Suppose you have List of Images.
List<String> imgURLs = ['img1', img2, img3.....N];
Below code for change images:
int index = 0;
const duration = const Duration(seconds:2); // change time as per your requirement
new Timer.periodic(duration, (timer){
setState(){
imageObj = imgURLs[index];
}
if(index >= imgURLs.lenght-1) {
timer.cancel();
}
index++;
});
Put this code at your place might be in initState method and use imageObj to set your image on the screen.
imageObj might be Image type or whatever type based on your image list

Video customview in full screen exits when toggling the device screen in android

I am developing an android application which is purely web based. It needs to display HTML5 based webpages using webview which is rich in multimedia contents. when I try to play video content embedded in the webpage its all gone fine and i am also able to play video in full screen.
But my main problem starts here: When I toggled the device screen while playing fullscreen video, it suddenly exits from playback to its current web page. I am stucked here and here I am including all codes that I used as I can in hopes someone can help me.
Activity that is used: MainActivity.java
`
public class MainActivity extends Activity {
private WebView webView;
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private MyWebViewClient mWebViewClient;
private MyWebChromeClient mWebChromeClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new MyWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new MyWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
webView.loadUrl("http://yuotube.com");
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
protected void onPause() {
super.onPause(); //To change body of overridden methods use File | Settings | File Templates.
webView.onPause();
}
#Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
webView.onResume();
}
#Override
protected void onStop() {
super.onStop(); //To change body of overridden methods use File | Settings | File Templates.
if (inCustomView()) {
hideCustomView();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inCustomView()) {
hideCustomView();
return true;
}
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
// WebChromeClient Class
public class MyWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void onShowCustomView(View view,CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
#Override
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
}
return mVideoProgressView;
}
#Override
public void onHideCustomView() {
super.onHideCustomView(); //To change body of overridden methods use File | Settings | File Templates.
if (mCustomView == null)
return;
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
// WebViewClient Class
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "",
"Loading multimedia! Please wait...", true);
#Override
public void onPageFinished(WebView view, String url) {
dialog.dismiss();
}
}
}
web_activity.xml
<!-- View that will be hidden when video goes fullscreen -->
<RelativeLayout
android:id="#+id/nonVideoLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.iptvmodified.VideoEnabledWebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<!-- View where the video will be shown when video goes fullscreen -->
<RelativeLayout
android:id="#+id/videoLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- View that will be shown while the fullscreen video loads (maybe include a spinner and a "Loading..." message) -->
<View
android:id="#+id/videoLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible" />
</RelativeLayout>
`activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
I am searching for a solution for thisand googled this to death with no progress made. Any help would be greatly appreciated.
Normally when the device is rotated your activity gets destroyed and recreated. This is probably causing the WebView to get 'kicked out of' fullscreen playback.
You need to override Activity.onConfigurationChanged and declare you want to handle orientation changes in your manifest. See the docs for details.

Android DialogFragment shows black parts of screen Sony Xperia U

I use DialogFragments in my game for some popup information. It works fine on LG Nexus 4 running android 4.2 and it runs fine on the Desire S running 2.3.
It does however not run correctly on a Sony Xperia U (running 4). Here is what happens:
black spaces under dialogfragment
It does not place the dialog in the middle of the screen, which happens on all other devices, but it also renders a big black section on my screen below the dialog.
Here is my code:
public void ShowMessage(String title, String msg)
{
Bundle b = new Bundle();
b.putString("title", title);
b.putString("msg", msg);
DialogFragment dialog = new DialogFragment_MsgBox();
dialog.setArguments(b);
dialog.show(getSupportFragmentManager(), "msgbox");
}
and
public class DialogFragment_MsgBox extends android.support.v4.app.DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle b = getArguments();
final Dialog dialog = new Dialog(getActivity(), R.style.SetmsgDialog);
dialog.setContentView(R.layout.simpleokdialog);
if(b.containsKey("title"))
dialog.setTitle(b.getString("title"));
else
dialog.setTitle("Message");
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.simpleokdialog, container, false);
Bundle b = getArguments();
String msg = "";
if(b.containsKey("msg"))
{
msg = b.getString("msg");
}
TextView text = (TextView)v.findViewById(R.id.bericht);
text.setText(msg);
Button iv = (Button)v.findViewById(R.id.simpleOK);
iv.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
getDialog().dismiss();
}
});
// TODO Auto-generated method stub
return v;
}
}
and also needed the style i use for the dialogfragment:
<style name="SetmsgDialog">
<item name="android:background">#aac6775c</item>
<item name="android:textColor">#android:color/white</item>
<item name="android:windowNoTitle">false</item>
<item name="android:textSize">14sp</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowTitleStyle">#style/setwindowTitleStyle</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:gravity">left</item>
</style>
What can cause this? any solutions/tips or suggestions to this problem?
I have fixed this finally, it appears that some phones/provider software have different behavior in the standard themes etc. (I have seen this with sony again with text being white with shadow on a white background, very nasty looking, and now again with sony, different behavior) So If you do overload some theme, which you always do when using your own and not fill in all the variables, use all variables to get expected out comes!
I had 'forgotten':
<item name="android:windowBackground">#android:color/transparent</item>
for which the sony xperia U uses black with no transparency, while nexus 4 and desire S use transparent color.

onActivityResult() not getting executed in DialogFragment

I have been looking in thousand posts for this, but I do not find how to solve my problem.
I have an ImageView. When the user clicks on this ImageView, a DialogFragment is displayed, and the user can choose between taking a new picture with the camera, or selecting a picture from the gallery. Until here everything works fine.
The problem is, that the picture selected by the user, should replace the current one in the ImageView, but this bit, is the one that is not working, because the onActivityResult() function that executes this code is not being executed, so the image in the ImageView always remains the same. I would appreciate any help, because I do not see or understand, why this code is not being executed.
I am getting a warning in the LogCat right after the user selects the image:
05-07 12:17:11.542: I/ActivityManager(59): Displayed activity com.android.gallery/com.android.camera.ImageGallery: 935 ms (total 935 ms)
05-07 12:17:12.812: W/FragmentActivity(3614): Activity result no fragment exists for index: 0x10001
05-07 12:17:12.862: W/InputManagerService(59): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#45fd9c38 (uid=10016 pid=317)
Activity.java:
private ImageView imageLoader = null;
imageLoader = (ImageView) findViewById(R.id.f_imageLoader);
imageLoader.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ImageLoaderDialog imageLoaderDialog = new ImageLoaderDialog(imageLoader);
imageLoaderDialog.show(getSupportFragmentManager(), "imageLoaderDialog");
}
Activity.xml:
<ImageView
android:id="#+id/f_imageLoader"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="0.20"
android:contentDescription="#string/imgDesc"
android:src="#drawable/my_image" />
ImageLoaderDialog.java:
//Dialog for choosing between new camera image or gallery image.
public class ImageLoaderDialog extends android.support.v4.app.DialogFragment {
private ImageView targetImageView = null;
final int TAKE_PICTURE = 0;
final int PICK_PHOTO = 1;
public ImageLoaderDialog (View view) {
targetImageView = (ImageView) view;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Selecciona");
final String[] imageSources = getResources().getStringArray(R.array.imageSources);
builder.setItems(imageSources, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item) {
case TAKE_PICTURE:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, TAKE_PICTURE);
break;
case PICK_PHOTO:
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, PICK_PHOTO);
break;
}
}
});
return builder.create();
}
//Set image to user's selected image.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == android.app.Activity.RESULT_OK) {
Uri selectedImage = intent.getData();
Log.i("IMAGEN", ""+selectedImage);
targetImageView.setImageURI(selectedImage);
}
}
}
Any help would be very appreciated.
The hosting activity overrode the onActivityResult but did not make a call to super.onActivityResult for unhandled result codes. Apparently even though the fragment is the one making the startActivityForResult call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented super.onActivityResult for all unhandled results, the fragment got a shot at handling the result.Try This:
getActivity().onActivityResult(requestCode, resultCode, intent);

Programmatically change listview so that it is checkable

I've made a decent effort to find a similar question and failed, so please forgive me if this is redundant pollution.
I have a ListView and an ImageButton defined in the xml file "my_layout" corresponding to my Activity as follows:
<ListView
android:id="#+id/listViewItems"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
></ListView>
and
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/btn_delete_dark"
android:id="#+id/buttonDelete"
android:layout_weight="1">
</ImageButton>
I then populate the ListView programmatically in the onCreate() method of my Activity as follows:
public class ViewItemsActivity extends Activity implements OnClickListener,
OnItemClickListener{
ImageButton buttonDelete;
ListView listViewItems;
DatabaseHandler dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
buttonDeleteQuestion = (ImageButton) findViewById(R.id.buttonDelete);
listViewQuestions = (ListView) findViewById(R.id.listViewItems);
buttonDelete.setOnClickListener(this);
//get data from sql table containing items
dbHandler = new DatabaseHandler(this);
String [] items = dbHandler.getItems(); //get data to populate ListView
CustomAdapter adapter = new CustomAdapter(this,
android.R.layout.simple_list_item_1, items);
listViewItems.setAdapter(adapter);
listViewItems.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDelete:
listViewItems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewItems.setItemChecked(0, true);
break;
//other cases are irrelevant
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
// TODO Auto-generated method stub
//non relevant code
}
}
Everything works as it should except that I want the ListView to change, in appearance and functionality, as a result of clicking buttonDelete, so that it displays checkmarks to the right of each row which can be checked by clicking on them.
It was my understanding that setChoiceMode(ListView.MULTIPLE_CHOICE) and setItemChecked(i,true) would have this effect, but clearly I've missed something as it does not.
I am quite new to android and so it is possible that I've wasted someone's time with trivialities, for which I apologize.
Thank you very much.
The solution was really simple, and is the following:
in the onClick event corresponding to buttonDelete, I simply created a new adapter whose layout id is *simple_list_item_multiple_choice* and assigned it to the ListView with the lines
CustomAdapter adapter = new CustomAdapter(this,
android.R.layout.simple_list_item_multiple_choice, items);
listViewItems.setAdapter(adapter);
which did the trick.