android2020. 7. 17. 16:08

아래와 같이 Android studio에서

1, AIDL 인터페이스 작성

2, Client 코드에서 Native Service를 ServiceManager로 가져와 Service의 함수들을 이용

 

모두 시도해본 것은 아니나 아래의 경우의 수가

모두 AIDL or Binder를 통하여 IPC가 가능

 

Native Service <-> Java Client

Native Service <-> Native Client

Java Service <-> Java Client

Java Service <-> Native Client

#AIDL


package android.binder.example;

/**
 * AIDL file for Binder API generating
 *
 */

interface IDemoAPI{
    String getName();
    String getFullName(String part);
    int sum(int a,int b);
}


 

 

#JAVA Client

package com.technicolor.clienttest;

import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.binder.example.IDemoAPI;

import java.lang.reflect.Method;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private IDemoAPI mService;
    private static final String TAG = "HelloActivity IDemoAPI";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getDemoAPIService();
        try{
            Log.d(TAG, "1+2="+Integer.toString(mService.sum(1,2)));
            Log.d(TAG, "Name="+mService.getName());
            Log.d(TAG, "FullName="+mService.getFullName("AAABBBCCC"));
        }catch(Exception e){
            Log.d(TAG,e.toString());
        }
    }

    static final String SERVICE_NAME="android.binder.example";

    /*
     * Get binder service
     */
    private void getDemoAPIService()
    {
        IBinder binder=null;
        Log.d(TAG,"getDemoAPIService");
        try{
            //android.os.ServiceManager is hide class, we can not invoke them from SDK. So we have to use reflect to invoke these classes.
            Object object = new Object();
            Method getService = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
            Object obj = getService.invoke(object, new Object[]{new String(SERVICE_NAME)});
            binder = (IBinder)obj;
        }catch(Exception e){
            Log.d(TAG, e.toString());
        }
        if(binder != null){
            mService = IDemoAPI.Stub.asInterface(binder);
            Log.d(TAG, "Find binder");
        }
        else
            Log.d(TAG,"Service is null.");
    }

}

 

 

#Native Service


#include "server.h"

int main(int argc, char *argv[])
{
    sp proc(ProcessState::self());
    //get service manager
    sp sm = defaultServiceManager();

    //Register a service with the SERVICE_NAME
    sm->addService(String16(SERVICE_NAME),new demo_api::DemoAPI());
    ALOGE("%s service is starting.....",SERVICE_NAME);
    //Start Service
    ProcessState::self()->startThreadPool();
    //Loop for waiting for request
    IPCThreadState::self()->joinThreadPool();

    return 0;
}

 

 

JavaClientTest.zip
7.34MB

 

android_system_service_example-master.zip
1.15MB

출처:

1, <https://stackoverflow.com/questions/42002869/is-it-possible-to-bind-to-a-java-service-from-a-native-c-client-and-transact>

2, https://github.com/qianjigui/android_system_service_example

'android' 카테고리의 다른 글

chcon 예제 (change context)  (0) 2021.01.05
Android X란?  (0) 2020.07.23
ForegroundService test  (0) 2020.07.08
wake lock example  (0) 2020.07.03
Xlint error in Android studio  (0) 2020.04.24
Posted by easy16
android2020. 7. 8. 13:48

package com.technicolor.wifitestapp;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;

import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

public class WifiTestService extends Service {
    private static String LOG_TAG = "easy";


    private Context mContext;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "onStartCommand");

        printAllNetworks();

        return START_STICKY;//super.onStartCommand(intent, flags, startId);
    }
    private ConnectivityManager.NetworkCallback mNetworkCallback;
    @Override
    public void onCreate() {
        Log.d(LOG_TAG, "onCreate");
        registerNetworkCallback();
        mContext=getApplicationContext();
        super.onCreate();
        startFgService();
    }



    @Override
    public void onDestroy() {
        Log.d(LOG_TAG, "onDestory");
        super.onDestroy();
        unregisterNetworkCallback();


    }

    void startFgService(){
        Intent intent = new Intent(this, MainActivity.class);

        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        String CHANNEL_ID= "test";

        NotificationCompat.Builder builder;
        NotificationChannel ch = new NotificationChannel(CHANNEL_ID, "test channel", NotificationManager.IMPORTANCE_DEFAULT);


        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(ch);
        builder = new NotificationCompat.Builder(this,CHANNEL_ID );
        builder.setContentIntent(pi);
        startForeground(1, builder.build());
    }
    private void printAllNetworks(){


        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Network[] networks = cm.getAllNetworks();

        for ( Network n  : networks){
            Log.d(LOG_TAG, "print all networks");
            NetworkCapabilities np = cm.getNetworkCapabilities(n);
            Log.d(LOG_TAG, np.toString());
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void workaround(){
        WifiManager mWifiManager  = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Network[] networks = cm.getAllNetworks();

        for ( Network n  : networks){
            Log.d(LOG_TAG, "print all networks");
            LinkProperties lp = cm.getLinkProperties(n);
            String iName = lp.getInterfaceName();

            Log.d(LOG_TAG, iName);
            if(iName.equals("eth0")){
                Log.d(LOG_TAG, iName + "found don't workaround....");
                return;
            }
        }


        if (mWifiManager.isWifiEnabled()) {

            Log.d(LOG_TAG, "wifi manager disconnect and recoonect");
            Toast.makeText(mContext, "wifi manager disconnect and reconnect", Toast.LENGTH_LONG).show();

            mWifiManager.disconnect();
            mWifiManager.reconnect();
        } else {
            Log.e(LOG_TAG, "wifi disabled");
        }
    }

    private void registerNetworkCallback() {
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();

        mNetworkCallback= new ConnectivityManager.NetworkCallback(){

            @Override
            public void onAvailable(@NonNull Network network) {

                super.onAvailable(network);
                Log.d(LOG_TAG, "onAvailable : "+network.toString());
                printAllNetworks();
            }

            @RequiresApi(api = Build.VERSION_CODES.Q)
            @Override
            public void onLost(@NonNull Network network) {
                super.onLost(network);
                Log.d(LOG_TAG, "onLost try to workaround");
                workaround();


            }

        };

        cm.registerNetworkCallback(builder.build(), mNetworkCallback);
    }
    private void unregisterNetworkCallback(){
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        cm.unregisterNetworkCallback(mNetworkCallback);
    }


}
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext=getApplicationContext();
        //startService(new Intent(mContext, WifiTestService.class));


        startForegroundService(new Intent(mContext, WifiTestService.class));
    }

 

'android' 카테고리의 다른 글

Android X란?  (0) 2020.07.23
native service를 aidl로 binding  (0) 2020.07.17
wake lock example  (0) 2020.07.03
Xlint error in Android studio  (0) 2020.04.24
Keystore file not set for signing config release 에러 발생  (0) 2020.04.24
Posted by easy16
android2020. 7. 3. 18:38

//AndroidManifest.xml

uses-permission android:name="android.permission.WAKE_LOCK" 


import android.os.PowerManager;


//init
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag name");


//acquire
mWakeLock.acquire();

//release
if( mWakeLock.isHeld() ){
    Log.d(TAG, "wake lock release");
    mWakeLock.release();
}



 

wake lock 주체를 아래서 확인 가능

$cat /sys/power/wake_lock

 

출처 : http://androidxref.com/9.0.0_r3/

'android' 카테고리의 다른 글

native service를 aidl로 binding  (0) 2020.07.17
ForegroundService test  (0) 2020.07.08
Xlint error in Android studio  (0) 2020.04.24
Keystore file not set for signing config release 에러 발생  (0) 2020.04.24
android apex에 관한 글  (0) 2020.02.19
Posted by easy16
android2020. 4. 24. 12:27

Deprecated API 사용할 발생하는 warning

호출부에 적절히 @SuppressWarnings("deprecation") 붙여준다

 

 

Recompile with -Xlint in Android studio

 

 

 

You need to add the following inside your app level buld.graddle file

allprojects {
    tasks.withType(
JavaCompile) {
        options.compilerArgs <<
"-Xlint:unchecked" << "-Xlint:deprecation"
    }
}

If for some reasons you need to continue using a deprecated API you can just suppress the warning. You could annotate the deprecated method with the

@SuppressWarnings("deprecation")

annotation.

post link

 

출처: <https://stackoverflow.com/questions/47740812/recompile-with-xlint-in-android-studio>

'android' 카테고리의 다른 글

ForegroundService test  (0) 2020.07.08
wake lock example  (0) 2020.07.03
Keystore file not set for signing config release 에러 발생  (0) 2020.04.24
android apex에 관한 글  (0) 2020.02.19
JNI -link  (0) 2020.01.07
Posted by easy16
android2020. 4. 24. 12:26

발생 사유는  release 모드 빌드시 sign keystore 지정되지 않았기 때문

 

1, Default debug.keystore local project copy

2, project structure -> sign config 들어가서 release 해당 패스를 설정

3, 아래의 default key password alias 입력한다.

(customized 경우, 생성된 keystore 정보가 반드시 필요함)

디폴트 keystore 사용 시 아래의 값을 지정.

 

Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
CN: "CN=Android Debug,O=Android,C=US"

 

출처: <https://stackoverflow.com/questions/18589694/i-have-never-set-any-passwords-to-my-keystore-and-alias-so-how-are-they-created

'android' 카테고리의 다른 글

wake lock example  (0) 2020.07.03
Xlint error in Android studio  (0) 2020.04.24
android apex에 관한 글  (0) 2020.02.19
JNI -link  (0) 2020.01.07
JNI 사용법 링크  (0) 2020.01.03
Posted by easy16
android2020. 2. 19. 14:26

https://codechacha.com/ko/android-q-mainline-apex/

 

안드로이드 Q - Mainline, APEX에 대해서 알아보기 | chacha

Android Q의 Mainline과 APEX는 부분적으로 시스템 업데이트를 할 수 있도록 만들어줍니다. Treble이 OS 업그레이드 속도를 높이는데 도움이 되었다면, Mainline과 APEX는 업그레이드 없이 모듈단위로 업데이트가 가능하도록 만들었습니다. 또한, 디바이스들이 공통 모듈을 사용하게 하여 파편화를 막아주는 역할을 합니다.

codechacha.com

참조~

 

 Q에서 도입된, APEX, so, jar등 라이브러리 업데이트가 가능하도록 apk와 유사하게 google store를 통해 업데이트 가능

기존의 RO partition에 존재하는 component의 업데이트를 가능하게 만들기 위한 구조

'android' 카테고리의 다른 글

Xlint error in Android studio  (0) 2020.04.24
Keystore file not set for signing config release 에러 발생  (0) 2020.04.24
JNI -link  (0) 2020.01.07
JNI 사용법 링크  (0) 2020.01.03
Android P native service 및 client 예제  (0) 2019.12.19
Posted by easy16
android2020. 1. 7. 13:57

http://forum.falinux.com/zbxe/index.php?_filter=search&mid=lecture_tip&search_target=title&search_keyword=JNI&document_srl=573556

Posted by easy16
android2020. 1. 3. 10:35

http://forum.falinux.com/zbxe/index.php?_filter=search&mid=lecture_tip&search_target=title&search_keyword=JNI&document_srl=570118

 

강좌와 팁 - JNI programming - (2) 기본 변수형 다루기

 

forum.falinux.com

 

'android' 카테고리의 다른 글

android apex에 관한 글  (0) 2020.02.19
JNI -link  (0) 2020.01.07
Android P native service 및 client 예제  (0) 2019.12.19
PDK에서 Android studio app을 gradle build 시 tips  (0) 2019.11.27
android internet 연결 확인  (0) 2019.11.27
Posted by easy16
android2019. 12. 19. 14:02

android_P_native_service_example.tgz
0.01MB

예제 참조

 

출처 :  https://github.com/YancyGitHub/native-service

'android' 카테고리의 다른 글

JNI -link  (0) 2020.01.07
JNI 사용법 링크  (0) 2020.01.03
PDK에서 Android studio app을 gradle build 시 tips  (0) 2019.11.27
android internet 연결 확인  (0) 2019.11.27
android alarm 세팅  (0) 2019.11.27
Posted by easy16
android2019. 11. 27. 18:04

#build.gradle
=> gradle build-tools 버전을 빌드 서버에 맞도록 classpath를 변경
Ex)3.3.2 -> 3.1.1

classpath 'com.android.tools.build:gradle:3.1.1'




#app/build.gradle 
=> SDK 버전 및 build tool version을 명시, buildToolsVersion의 경우 수동으로 입력
compileSdkVersion "28"
buildToolsVersion "28.0.3"

=> 앱 이름 변경

android{

   def APP_NAME = "WifiMonitoringService"
   
   buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            applicationVariants.all { variant ->
                variant.outputs.all {
                    outputFileName = APP_NAME + ".apk"
                }
            }
        }
    }
}





#Android.mk 이용하여 build 

명령어:
$(info return :$(shell ./gradlew assembleRelease)

결과물
./app/build/outputs/apk/release/WifiMonitoringService.apk


참조 : https://github.com/jitpack/jitpack.io/issues/3687

'android' 카테고리의 다른 글

JNI 사용법 링크  (0) 2020.01.03
Android P native service 및 client 예제  (0) 2019.12.19
android internet 연결 확인  (0) 2019.11.27
android alarm 세팅  (0) 2019.11.27
Android bp usage  (0) 2019.10.15
Posted by easy16