Today i decided to learn to code using eclipse and the andriod skd (2.3.3), I'm trying to code a basic soundboard and its not coming up with errors but the sounds are still not playing. If anyone could look at the code and give me a hand that would be great
Code:
package com.mkyong.android;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class AppActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, App2Activity.class);
startActivity(intent);
}
});
}
public class PlayIt extends Activity implements OnClickListener {
MediaPlayer mp1;
MediaPlayer mp2;
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp1 = MediaPlayer.create(this, R.raw.froze);
mp2 = MediaPlayer.create(this, R.raw.lasagna);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener((OnClickListener) this);
final Button button = (Button) findViewById(R.id.button02);
button.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
mp1.start();
break;
case R.id.button02:
mp2.start();
break;
}
}
@Override
protected void onDestroy() {
mp1.release();
mp2.release();
super.onDestroy();
}
}
}
i dont have any idea about any code
Related
Hey guys, i have a problem at ( return super.onKeyDown(keyCode, event); )
and at ( public boolean onKeyDown(int keyCode, KeyEvent event) { )
Ihave mistake like The method onKeyDown(int, KeyEvent) is undefined for the type WebViewClient . But in the example it works.So what should i do?
Code:
package com.ihlas.koleji;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("http: //m.ih laskol eji.c om");
engine.getSettings().setJavaScriptEnabled(true);
engine.setWebViewClient(new HelloWebViewClient());
}
public class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView engine;
if((keyCode == KeyEvent.KEYCODE_BACK)&& engine.canGoBack()){
engine.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
}
I have two class activity that runs perfectly separately (ArduinoBlinkLEDActivity.java and ObjTrackActivity.java) .. I want to merge the two classes in one slass; i want to call the second class in the first one using the onclick activity buttonListener. i think that need to change layouts
please i need your help
ArduinoBlinkLEDActivity.java:
public class ArduinoBlinkLEDActivity extends Activity {
// TAG is used to debug in Android logcat console
private static final String TAG = "ArduinoAccessory";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
while (connected) {
startService(new Intent(this, ArduinoBlinkLEDActivity.class));
}
iptext = (EditText) findViewById(R.id.ipserveur);
connexion = (Button) findViewById(R.id.button2);
deconnexion = (Button) findViewById(R.id.button1);
}
ObjTrackActivity.java :
public class ObjTrackActivity extends Activity {
private static final String TAG = "ObjTrackActivity";
public ObjTrackActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new ObjTrackView(this));
}
ObjTrackView.java:
class ObjTrackView extends SampleViewBase {
private int mFrameSize;
private Bitmap mBitmap;
private int[] mRGBA;
public ObjTrackView(Context context) {
super(context);
}
my test that doesn't work: ArduinoBlinkLEDActivity.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
iptext = (EditText) findViewById(R.id.ipserveur);
connexion = (Button) findViewById(R.id.button2);
deconnexion = (Button) findViewById(R.id.button1);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
//Listening to button event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Log.i(TAG, "onCreate");
//super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new ObjTrackView(this));
}
});
I made Instagram type application in Android Studio, but whenever I try to upload image in my app, it uploads to my profile picture. I checked my intents and they are really perfect. First file is GalleryFragment.java in which we will select the photo which we want to upload and Second file is NextActivity.java which is used to Share the image to profile. But in GalleryFragment.java I have intent getActivity() to NextActivity.java and AccountSettingsActivity.java in which we can change out profile picture. But whenever I click on Next it doesn't take me to NextActivity.java but to the AccountSettingsActivity.java and updates my profile picture. If there is Firebase error so tell me. And the same issue is occurred when I try to upload photo from camera inside the application and it doesn't do anything. I have posted 3 files.
GalleryFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FilePaths;
import darthvader.com.pictagram.Utils.FileSearch;
import darthvader.com.pictagram.Utils.GridImageAdapter;
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
Objects.requireNonNull(getActivity()).finish();
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if(isRootTask()){
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
}else{
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
init();
return view;
}
private boolean isRootTask(){
return ((ShareActivity) getActivity()).getTask() == 0;
}
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
}catch (ArrayIndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append){
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
NextActivity.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FirebaseMethods;
import darthvader.com.pictagram.Utils.UniversalImageLoader;
import darthvader.com.pictagram.models.User;
public class NextActivity extends AppCompatActivity {
private static final String TAG = "NextActivity";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
//widgets
private EditText mCaption;
//vars
private String mAppend = "file:/";
private int imageCount = 0;
private String imgUrl;
private Bitmap bitmap;
private Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = findViewById(R.id.caption);
setupFirebaseAuth();
ImageView backArrow = findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity");
finish();
}
});
TextView share = findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
private void someMethod(){
/*
Step 1)
Create a data model for Photos
Step 2)
Add properties to the Photo Objects (caption, date, imageUrl, photo_id, tags, user_id)
Step 3)
Count the number of photos that the user already has.
Step 4)
a) Upload the photo to Firebase Storage
b) insert into 'photos' node
c) insert into 'user_photos' node
*/
}
/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = findViewById(R.id.imageShare);
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new bitmap");
image.setImageBitmap(bitmap);
}
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
Log.d(TAG, "onDataChange: image count: " + imageCount);
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imageCount = mFirebaseMethods.getImageCount(dataSnapshot);
Log.d(TAG, "onDataChange: image count: " + imageCount);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
PhotoFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.Permissions;
public class PhotoFragment extends Fragment {
private static final String TAG = "PhotoFragment";
//constant
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: started.");
Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching camera.");
if(((ShareActivity)getActivity()).getCurrentTabNumber() == PHOTO_FRAGMENT_NUM){
if(((ShareActivity)getActivity()).checkPermissions(Permissions.CAMERA_PERMISSION[0])){
Log.d(TAG, "onClick: starting camera");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}else{
Intent intent = new Intent(getActivity(), ShareActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
});
return view;
}
private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}
else{
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
Log.d(TAG, "onActivityResult: done taking a photo.");
Log.d(TAG, "onActivityResult: attempting to navigate to final share screen.");
Bitmap bitmap;
bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
if(isRootTask()){
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}else{
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}
}
}
}
In the following code drawing using DrawView works for me. But I want to draw a shape on touching the canvas. MyView is supposed to do that, but how to get it working?
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
DrawView drawView;
MyView myView;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
myView = new MyView(this);
myView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
@override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(10, 20, 30, 40, paint);
canvas.drawLine(20, 10, 50, 20, paint);
}
}
class MyView extends View {
private float xDown = 0,yDown = 0, xUp = 0, yUp = 0;
Paint mPaint;
boolean touched = false;
public MyView(Context context) {
super(context);
init(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.STROKE);
}
@override
protected void onDraw (Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
if(touched) {
canvas.drawRect(xDown, yDown, xUp, yUp, mPaint);
}
}
@override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
xDown = event.getX();
yDown = event.getY();
xUp = 0;
yUp = 0;
break;
case MotionEvent.ACTION_MOVE:
xUp = event.getX();
yUp = event.getY();
touched = true;
break;
case MotionEvent.ACTION_UP:
xUp = event.getX();
yUp = event.getY();
touched = true;
break;
}
invalidate();
return true;
}
}
}
The second
BjornAndroid said:
setContentView(drawView);
Click to expand...
Click to collapse
had to be
setContentView(myView);
So this is one problem one shouldn't have, if manufacturers would make sensible decisions - but oh well...
I bought an cheap eBook reader (InkBook Calypso Plus) that unfortunately comes with a very reduced Android 8.1 user interface but otherwise with an pretty open system. But when the devices goes to sleep it disables wifi (which is fine for me) and you've to re-enable it manually every time (which is not fine for me). There is no option to change that behavior in the default interface.
So I'm looking for ideas to fix this: Either by an app that just regularly checks if wifi is off and turns it back on when the device wakes up or by any other way to turn this "feature" off (maybe there is a way to access the original android settings and change it there?).
- The devices runs Android 8.1 with a custom user interface from the manufacturer
- I can sideload *.apks
- It doesn't have Google Play Store/Services
- It's not rooted and I don't know if this is possible
AllesMeins said:
So this is one problem one shouldn't have, if manufacturers would make sensible decisions - but oh well...
I bought an cheap eBook reader (InkBook Calypso Plus) that unfortunately comes with a very reduced Android 8.1 user interface but otherwise with an pretty open system. But when the devices goes to sleep it disables wifi (which is fine for me) and you've to re-enable it manually every time (which is not fine for me). There is no option to change that behavior in the default interface.
So I'm looking for ideas to fix this: Either by an app that just regularly checks if wifi is off and turns it back on when the device wakes up or by any other way to turn this "feature" off (maybe there is a way to access the original android settings and change it there?).
- The devices runs Android 8.1 with a custom user interface from the manufacturer
- I can sideload *.apks
- It doesn't have Google Play Store/Services
- It's not rooted and I don't know if this is possible
Click to expand...
Click to collapse
You need root because the activity that you are trying to manage is regulated by "wakelocks" which can be managed with apps from the PlayStore that require root in order to modify your wakelocks.
There also may be a way to use adb to change the behaviour of the wakelock causing your undesired behaviour. I haven't looked to see if there is a way to do this with adb, it may or may not require root, I'm not certain.
Or, your issue is caused by "deep-sleep" or "doze", if so, you need to find a way to remove or disable deep-sleep or doze.
Or, it may be caused by some kind of battery or power management setting on your device, try disabling any battery or power management settings.
So to just give you a "kind of solution" if somebody stumbles upon this. I solved this by (very crudely) copying together my own app that's always active and waits for "screen on" to re-enable wifi. That can be done without root on my device
MainActivity.java
Java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btnStartService, btnStopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnStartService = findViewById(R.id.buttonStartService);
btnStopService = findViewById(R.id.buttonStopService);
btnStartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService();
}
});
btnStopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService();
}
});
}
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Monitoring WifiStatus");
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
startService(onOffIntend);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
stopService(onOffIntend);
}
}
OnOffReciever.java:
Java:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
public class OnOffReceiver extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is switched off
Log.w("WifiWakeUp","Screen Off");
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is turned on and screen lock deactivated
Log.w("WifiWakeUp","Screen On");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
}, new IntentFilter(Intent.ACTION_USER_PRESENT));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Foregroundservice.java
Java:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("WifiWakeUp")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_wifi_24)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AllesMeins said:
So to just give you a "kind of solution" if somebody stumbles upon this. I solved this by (very crudely) copying together my own app that's always active and waits for "screen on" to re-enable wifi. That can be done without root on my device
MainActivity.java
Java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btnStartService, btnStopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnStartService = findViewById(R.id.buttonStartService);
btnStopService = findViewById(R.id.buttonStopService);
btnStartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService();
}
});
btnStopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService();
}
});
}
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Monitoring WifiStatus");
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
startService(onOffIntend);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
Intent onOffIntend = new Intent(this, OnOffReceiver.class);
stopService(onOffIntend);
}
}
OnOffReciever.java:
Java:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
public class OnOffReceiver extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is switched off
Log.w("WifiWakeUp","Screen Off");
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//This happens when the screen is turned on and screen lock deactivated
Log.w("WifiWakeUp","Screen On");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
}, new IntentFilter(Intent.ACTION_USER_PRESENT));
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Foregroundservice.java
Java:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("WifiWakeUp")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_wifi_24)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
Click to expand...
Click to collapse
I'm wondering how long this took you and how much of a headache it was.
Actually much less than I feared. Took me maybe a few hours because it's basically just two answers from StackExchange copied together.