solution for getSystemService function at Android - java

I want to test something about usb devices, I try to write a small program, I am sure that it is wrong but this is not the point of this question.
I am sure that my imports are OK but the Android Studio refused to build this class with an error about the GetSystemService(). I have the message:
Error:(65, 43) error: cannot find symbol method getSystemService(String).
I used also an example from http://android-er.blogspot.de/2013/10/list-attached-usb-devices-in-usb-host.html and the Android Studio also has the same error but if i install the Apk from this website then it is running on my device, so i supposed that something is wrong at Android Studio.
Any good idea?
OFFTOPIC "QT Creator is light years better"
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbAccessory;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import android.util.Log;
public class DeviceOpenActivity {
private static final String TAG = "DeviceOpenActivity";
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbAccessory mAccessory;
ParcelFileDescriptor mFileDescriptor;
FileInputStream mInputStream;
FileOutputStream mOutputStream;
public static int fibonacci(int n) {
if (n<2) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
private void openAccessory() {
Log.d(TAG, "openAccessory: " + mAccessory);
mFileDescriptor = usbManager.openAccessory(mAccessory);
if (mFileDescriptor != null) {
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
}
}
}

If you check the example that you provided, you will verify that there is a MainActivity class that extends Activity class, which by its turn extends indirectly from Context. In order to call getSystemService() you need to have an available Context. If you make your DeviceOpenActivity extend Activity, Android Studio will not complain anymore about your call.
Just leave your class declaration like this:
public class MainActivity extends Activity
Don't forget that you need to provide a XML layout for your Activity, as well as the Activity methods, like onCreate().

Related

Android create Toast using class reflection?

I am creating a hook using AndHook to test some functions getting called. I need to show a Toast inside a method without being able to get the context object (I can't directly import MainActivity because I am injecting the script without having the corresponding package when compiling so I can't use MainActivity.this). Here's the code sample:
import andhook.lib.HookHelper;
import android.widget.Toast;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
public class AndHookConfig {
#HookHelper.Hook(clazz = BitmapFactory.class)
private static Bitmap decodeFile(BitmapFactory thiz, String path) {
Toast.makeText(Class.forName("com.example.activity.MainActivity").this, "Bitmap.decodeFile("+path+")", Toast.LENGTH_LONG).show();
return (Bitmap)(HookHelper.invokeObjectOrigin(thiz, path));
}
}
I think the only way to do this is using reflection but the code sample doesn't compile and results in an error. Do you have any solutions ?
Thanks in advance.

How to start an Intent in an outsourced static function?

I'm following this tutorial to get started with Bluetooth:
https://www.youtube.com/watch?v=y8R2C86BIUc
I want to outscource the bluetooth enable to an separated class and call it from the MainActivity.
I made the new Intent, but following the Video I'm not possible to start the Intent.
I tried importing:
android.support.v7.app.AppCompatActivity;
android.support.v4.content.ContextCompat;
But in both cases it didn't worked out.
Without any imports Android Studio is telling "Can't resolve method"
MAIN
package com.example.lenkzeitapplikation_01;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBT.switch_BT_ON();
}
}
STARTBT
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.content.ContextCompat;
import com.fleetboard.sdk.lib.android.log.Log;
public class startBT {
private static final String Tag ="StartBT";
static BluetoothAdapter mBluetoothAdapter;
public static void switch_BT_ON(){
if(mBluetoothAdapter == null){
Log.d(Tag, "No BT adapter");
}if(!mBluetoothAdapter.isEnabled()){
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
//mBluetoothAdapter.enable();
}
}
}
Using
import android.support.v4.content.ContextCompat:
Error:
method startActivity in class ContextCompat cannot be applied to given types;
required: Context,Intent,Bundle
found: Intent
reason: actual and formal argument lists differ in length
Important
Ok, first things first:
Activity is one of the different types of Context.
AND:
startActivity is a method that Context objects have.
Explanation
If you want to start an Activity, you must use a Context object. That's why it was working in the first place, in your MainActivity.
Now that you moved the code to another class, if you wan to use the method startActivity, you must have a reference to a Context object.
But... How?
public class startBT {
public static void switch_BT_ON(Context context){
//... Your logic
context.startActivity(intent);
}
}
In your activity:
startBT.switch_BT_ON(this);
The this parameter is the MainActivity itself, which is a Context by definition.
It means that:
switch_BT_ON requires a Context.
MainActivity is saying: "Here, use me".
Recommendations
This is classic, basic OOP thinking. Study about Object-Oriented Programming, classes and inheritance to learn why the startActivity method worked on the Acivity and not outside of it, passing objects around and handling different scopes.
Read the quick answer about what is an Android Context. Or adventure yourself through the documentation.

codename native Android application subclassing issues

My codenameone application crashes anything I use this native code
package com.mycompany.interfaces;
import android.app.Application;
import android.content.Context;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class InitialiseApp extends Application{
private static Context context;
public static Context getContext() {
return context;
}
#Override
public void onCreate()
{
super.onCreate();
context = getApplicationContext();
try
{
FirebaseApp.initializeApp(this, new FirebaseOptions.Builder().
setApiKey("XXXXXXXXXXXXXX").
setApplicationId("XXXXXXXX").
setGcmSenderId("XXXXXXXXXX")
.build());
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getToken("XXXXXXXXXX",FirebaseMessaging.INSTANCE_ID_SCOPE);
FirebaseMessaging.getInstance().subscribeToTopic("test");
}
catch(Exception c)
{
c.printStackTrace();
}
}
}
I declare the class in the android.xapplication_attr android:name="com.mycompany.interfaces.InitialiseApp"
Need a assistance
Are you putting this in the native interface stub or in the CN1 part of the code?
Also, I don’t think that’s how you get a context in CN1. Look in the developer guide and video tutorials for Native Interfaces. I also recall a series of blog posts about native interfaces that dive into writing the Android code. You’ll need to use something from the AndroidNativeUtil class like: AndroidNativeUtil.getActivity().

Should the Presenter know about the Activity in Android MVP architecture?

I am wondering if the Activity should be referenced or not within Presenter code when using the Android MVP architecture?
The example MVP architecture that I have found so far doesn't reference it, but in my code it's not a property on the Presenter, but an argument in some methods. Could this lead to issues? Does this not follow Android MVP?
Here is a code example from one Presenter:
package com.example.example;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import com.example.example.util.Constants;
import com.example.example.util.ImageFile;
import java.io.IOException;
/**
* Presenter from home screen, (Main), of the app
*/
public class MainPresenter implements MainContract.Presenter {
private final MainContract.View mView;
private final ImageFile mImageFile;
public MainPresenter(MainContract.View mainView, ImageFile imageFile) {
mView = mainView;
mImageFile = imageFile;
}
#Override
public void takePicture(FragmentActivity activity) throws IOException {
mImageFile.create(activity);
Uri photoUri = FileProvider.getUriForFile(
activity,
Constants.FILE_PROVIDER_PATH,
mImageFile.getFile());
mView.openCamera(photoUri);
}
Uri getImageFileUri() {
return mImageFile.getUri();
}
}
In proper MVP implementation, Presenter should not know about the activity. If we'll use activity then we'll have to mock the activity during testing, that'll make the testing difficult. So, in your case, you should pass your mImageFile to activity through the view reference and create the URI inside activity class.

The method is undefined for the type in Eclipse

Method is undefined for the type in Eclipse. Can't seem to solve it. The error is in the lines: msg.setTimestamp( System.currentTimeMillis() ); and msg.setBody("this is a test SMS message");
package com.example.smsnotification;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
public class PopSMSActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Retrieve serializable sms message object by the key "msg" used to pass to it
Intent in = this.getIntent();
PopMessage msg = (PopMessage) in.getSerializableExtra("msg");
//Case where we launch the app to test the UI EG: No incoming SMS
if(msg==null){
msg = new PopMessage();
con.setPhone("0123456789");
msg.setTimestamp( System.currentTimeMillis() );
msg.setBody("this is a test SMS message");
}
showDialog(msg);
}
Remove the code and write it back to eclipse. It worked for me....You can try copy and paste to after writing signature of function/class.
This means the PopMessage class doesn't provide the methods setTimestamp(long) and setBody(String).
There is no import statement for PopMessage in your code so I assume it is a class which you have implemented and is contained in the same package as the Activity which you have posted.
So you could either solve this by implementing those two methods in PopMessage or by removing the calls.
You may also extend your Eclipse Settings by activating the "save Actions" (Window->Preferences->Java->Editor->Save Actions) and use the Option "Organize Imports". This would at least add the propbably missing Import "...PopMessage" while you press Ctrl+S.

Categories