Android Simple App loading pictures not working - java

sorry for the vague title, i really dont know what i did wrong in my app. Am new to android, so bear with me.
Here ist the Manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phamt.ubung11">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:debuggable="true"
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=".MyReceiver">
<intent-filter>
<action android:name="com.example.loadpicservice" />
</intent-filter>
</receiver>
<service
android:name=".LoadPicService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
And my MainActivity Class:
public class MainActivity extends AppCompatActivity {
private static String url1 = "https://lh3.googleusercontent.com/j5fD3m5qXRNtGYDuajhEtS_etFvU8FE5PogmqTY2hrshDG0_urf_UBeVAyJljoCxdf4=w300";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonGo = (Button) findViewById(R.id.button4);
buttonGo.setOnClickListener(
new Button.OnClickListener() {
public void onClick (View v) {
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText("Now Click Kill Button to delete pictures");
Intent intent = new Intent(MainActivity.this, LoadPicService.class);
intent.putExtra("url", MainActivity.url1);
startService(intent);
}
}
);
Button buttonKill = (Button) findViewById(R.id.button);
buttonKill.setOnClickListener(
new Button.OnClickListener() {
public void onClick( View v) {
System.exit(0);
}
}
);
MyReceiver receiver = new MyReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte[] byteArray = getIntent().getByteArrayExtra("bild");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
//funktion SetImage here !
ImageView img1 = (ImageView) findViewById(R.id.imageView2);
img1.setImageBitmap(bmp);
img1.setVisibility(View.VISIBLE);
}
};
IntentFilter intentFilter = new IntentFilter("com.example.loadpicservice");
registerReceiver(receiver,intentFilter);
}
}
And last, my Service Class.
public class LoadPicService extends IntentService {
public LoadPicService() {
super("LoadService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
String urls = intent.getStringExtra("url");
Intent ansIntent = new Intent(this, LoadPicService.class);
Bitmap bmp = null;
try {
URL url = new URL(urls);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
Log.i("cannot download picture", "CANT DOWNLOAD PICTURE");
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ansIntent.putExtra("bild",byteArray);
ansIntent.setAction("com.example.loadpicservice");
//ggbf. runterskalieren.
sendBroadcast(ansIntent);
}
public void onStartCommand(Intent intent, int startId) {
}
}
So in short, here are the things i did.
I create Service, which started when you click button Go, which sends an Intent with URL as Extra.
On starting the Service loads the picture and convert it into ByteArray and send as Extra to MainActivity through a new Intent
In the MainActivity, on receiving the broadcast, convert the given ByteArray to BitMap and set current ImageView to that picture.
EDIT : The picture couldnt be loaded, i checked if the url is alright. Otherwise the OnClick Method works.
What did i do wrong here ? Thanks for any help!

Related

Android keep app running in the background forever

I am still new to Android development, but I’m creating an app that sendings an HTTP request when it receives a broadcast (from a barcode scan). I have tried to implement some other solutions that I read on here but haven't quite figured it out yet. It would be great if someone could help me get going in the right direction.
Essentially, the end goal is for the app to keep running in the background forever so that even if the app is not open and a barcode is scanned and sent to the app via broadcast signal, the HTTP request is still sent.
This is what I have so far:
MainActivity.java
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
public static final String BARCODE_BROADCAST = "...";
private final BarcodeReceiver barcodeReceiver = new BarcodeReceiver();
private TextView mTextView;
private String scannedBarcode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.barcode);
}
#Override
public void onResume() {
super.onResume();
registerBarcodeScanner();
}
#Override
public void onPause() {
super.onPause();
unregisterBarcodeScanner();
// this code needs to keep the app running
Intent restartService = new Intent("RestartService");
this.startService(restartService);
sendBroadcast(restartService);
}
public void onDestroy() {
super.onDestroy();
// this code needs to keep the app running
Intent restartService = new Intent("RestartService");
this.startService(restartService);
sendBroadcast(restartService);
}
private void registerBarcodeScanner() {
registerReceiver(barcodeReceiver, new IntentFilter(BARCODE_BROADCAST));
}
private void unregisterBarcodeScanner() {
unregisterReceiver(barcodeReceiver);
}
private void displayBarcode() {
if (scannedBarcode == null) return;
String text = getString(R.string.barcode_scanned, scannedBarcode);
mTextView.setText(text);
/* SEND HTTP REQUEST */
}
private class BarcodeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BARCODE_BROADCAST)) {
String barcode = intent.getStringExtra("Barcode");
if (barcode != null) {
scannedBarcode = barcode;
displayBarcode();
}
}
}
}
}
RestartService.java
public class RestartService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MainActivity.class));
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="..."
android:versionCode="1">
<uses-sdk android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
tools:replace="android:label">
<activity
android:name="...MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="...RestartService"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="RestartService" />
</intent-filter>
</receiver>
</application>
</manifest>

I would like to make a call using one button and use one fixed number

I would like to make a call using one button. The phone number should be inside. But my code is inoperative. Who can support?
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
}
public void onClickStart(View view) {
button = findViewById(R.id.button);
((Button)findViewById(R.id.button)).setOnClickListener((View.OnClickListener) v -> {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "89261234567";
callIntent.setData(Uri.parse(phNum));
startActivity( callIntent) ;
});
}
}
manifest file
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<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/Theme.GateApp">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Your problem is that you're never assigning the click listener to the button, since onClickStart is never invoked. This is how you should do it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener((View.OnClickListener) v -> {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "89261234567";
callIntent.setData(Uri.parse(phNum));
startActivity( callIntent) ;
});
}
This way you're assigning the click listener to the button. In the documentation you can find how to use it.
Here it is the link at the call intent documentation
Just use this two lines of code inside onClickListener:
((Button)findViewById(R.id.button)).setOnClickListener((View.OnClickListener) v -> {
String phNum = "tel:" + "89261234567";
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phNum, null)));
});
I think you can add to manifest file this string
<data android:scheme="tel" />
// This works well!
((Button) findViewById(R.id.button1)).setOnClickListener((View.OnClickListener) v -> {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "87777777777";
callIntent.setData(Uri.parse(phNum));
startActivity(callIntent);
});

Android app opens after a few seconds after pressing home button during splash screen

I am having an issue I can't seem to figure out the reason for.
When you launch the app, a splash screen is first displayed for 2.5 seconds before finishing and starting a new activity. If you press the home or back button during this time the app will close as normal. However after a few seconds (longer than 2.5) the app will open and start from the activity that comes after the splash screen.
Any help on why this happens is appreciated!
Here is the implementation of the Splash screen (I do however not believe anything here causes this issue as I've tried different implementations)
`public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(2500);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();`
Here's the manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.VIBRATE" />
<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=".activities.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode = "singleInstance">
</activity>
<activity android:name=".activities.SplashScreenActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".alert.BroadCaster" >
</receiver>
<service android:name=".timer.TimerService"
android:process=":timerservice" />
</application>
It happens because you are creating a new Thread and this thread will be still alive after you put your app in background. You can change your approach using an Handler. If you need that your next Activity won't start if the splash screen is in background, you have to store the current time before the delay starts.
private static final long SPLASH_SCREEN_MS = 2500;
private long mTimeBeforeDelay;
private Handler mSplashHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// Create a new Handler.
mSplashHandler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
// The first time mTimeBeforeDelay will be 0.
long gapTime = System.currentTimeMillis() - mTimeBeforeDelay;
if (gapTime > SPLASH_SCREEN_MS) {
gapTime = SPLASH_SCREEN_MS;
}
mSplashHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, gapTime);
// Save the time before the delay.
mTimeBeforeDelay = System.currentTimeMillis();
}
#Override
protected void onPause() {
super.onPause();
mSplashHandler.removeCallbacksAndMessages(null);
}
Just use handler instead of thread sleep like this
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, SPLASH_DURATION);
You need to implement the onStop() method, only if you want to save data and memory.

Hang up and decline incoming call by custom activity[buttons] Android

I am just in process by learning Android a bit, and i have stumbled on this problem.
I want to do a "custom incoming call screen". My current Solution is a class(IncomingCallInterceptor) that extends from BroadcastReceiver. In IncomingCallInterceptor class i override the onReceive and starting my activity(MainActivity) with layout when the phone is ringing.
In that activity(MainActivity) i have three buttons:
Accept Call, Hang Up, Decline Call
Those buttons should do what they say, Answer the phone, hang up the phone or decline the call.
I have in someway got the Accept Call to work, but not Hang Up and Decline.
Heres my code below:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.uppgift.six.one.incoming61.sixone" >
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="IncomingCallInterceptor">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
IncomingCallInterceptor that extends from BroadcastReceiver:
public class IncomingCallInterceptor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Context appContext = context.getApplicationContext();
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String msg = "Phone state changed to " + state;
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String incomingNumber = intent.getStringExtra
(TelephonyManager.EXTRA_INCOMING_NUMBER);
msg += ". Incoming number is this " + incomingNumber;
//START MY ACTIVITY!
Intent i = new Intent(appContext, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(i);
}
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
Here is my Activity(The Layout is nothing to post, just now is basically three buttons)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAnswer = (Button)findViewById(R.id.btnAnswer);
Button btnDecline= (Button)findViewById(R.id.btnDecline);
Button btnHangUp= (Button)findViewById(R.id.btnHangUp);
btnAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_HEADSETHOOK));
sendOrderedBroadcast(i, null);
}
});
btnDecline.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Decline Call (I need help here)
}
});
btnHangUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Hang Up Call (I need help here)
}
});
}
In the MainActivity class it is marked by comments where i need some help.
I have also seen something about a "Telephonyservice interface"(thingy) solution, but i don't understand how that worked when i was testing it.
Reject Call:
try {
TelephonyManager tm = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object telephonyService = m.invoke(tm); // Get the internal ITelephony object
c = Class.forName(telephonyService.getClass().getName()); // Get its class
m = c.getDeclaredMethod("endCall"); // Get the "endCall()" method
m.setAccessible(true); // Make it accessible
m.invoke(telephonyService); // invoke endCall()
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}

Can't switch between activities

sorry for asking dumb questions, java and Android are both new to me ;)
My problem: I can't switch between two activities in a very simple app. I tried solutions described in similar topics but it didn't work.
So this is my 1st Activity (I didn't paste the imports):
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void OnStart(){
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
The second Activity is very simple - it is just supposed to load a layout called userinput.xml:
public class UserInput extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userinput);
}
}
The application part of the Manifest looks like following:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</activity>
</application>
When I run the app and click the button nothing happens. Where could be the problem?
// Alright, I have put the code into the onCreate() method so it now looks like following:
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
Now the app crashes (force close) anytime I click the Next button.
You define your onStart() function with a capital 'O'. That is why the function is never called.
Your onStart():
public void OnStart(){ ... }
How it should be:
// Note the lowercase 'o' in onStart
public void onStart(){ ... }
Also note that having an #Override above the function name when you want to override a method will help prevent making these mistakes, as Eclipse (or whatever IDE you use) will tell you that you are not actually overriding a function.
Write below code in onCreate() method:
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
startActivity(myIntent);
}
});
2nd correction for android manifest file:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- closed here -->
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</application>
You can move all the code in onCreate() and simplify like this
startActivity(new Intent(this, UserInput.class));
But I don't understand why you start another activity like this
Check it following line
Intent myIntent = new Intent(OneAvtivity.this, SecondActivity.class);
startActivity(myIntent);
Your Class name is UserIpnout and you write SecondActivity.class
Intent myIntent = new Intent(OneAvtivity.this, UserInput .class);
startActivity(myIntent);

Categories