index.uts 15.2 KB
Newer Older
lizhongyi_'s avatar
lizhongyi_ 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import Activity from 'android.app.Activity';
import BroadcastReceiver from 'android.content.BroadcastReceiver';
import Notification from 'android.app.Notification';
import Bundle from 'android.os.Bundle';
import R from 'io.dcloud.uni_modules.uts_nativepage.R';
import Intent from 'android.content.Intent';
import IntentFilter from 'android.content.IntentFilter';
import NotificationCompat from 'androidx.core.app.NotificationCompat';
import NotificationManager from 'android.app.NotificationManager';
import NotificationChannel from 'android.app.NotificationChannel';
import Context from 'android.content.Context';
import Button from 'android.widget.Button';
import OnClickListener from 'android.view.View.OnClickListener';
import View from 'android.view.View';
import Build from 'android.os.Build';
import IBinder from 'android.os.IBinder';
import Toast from 'android.widget.Toast';

19 20 21
import ShortcutInfoCompat from 'androidx.core.content.pm.ShortcutInfoCompat'
import ShortcutManagerCompat from 'androidx.core.content.pm.ShortcutManagerCompat'
import IconCompat from 'androidx.core.graphics.drawable.IconCompat'
杜庆泉's avatar
杜庆泉 已提交
22
import ActivityLifecycleCallbacks from 'android.app.Application.ActivityLifecycleCallbacks';
lizhongyi_'s avatar
lizhongyi_ 已提交
23 24 25 26 27 28 29 30 31 32

import Service from 'android.app.Service';
import System from 'java.lang.System';
import Exception from 'java.lang.Exception';
import RecyclerView from 'androidx.recyclerview.widget.RecyclerView';
import TextView from 'android.widget.TextView';
import ViewGroup from 'android.view.ViewGroup';
import LayoutInflater from 'android.view.LayoutInflater';
import LinearLayoutManager from 'androidx.recyclerview.widget.LinearLayoutManager';
export {DoAppWidget} from "./DoAppWidget.uts"
杜庆泉's avatar
杜庆泉 已提交
33
import Application from 'android.app.Application';
杜庆泉's avatar
杜庆泉 已提交
34 35
import Log from 'android.util.Log';

36 37
import File from 'java.io.File';
import Uri from 'android.net.Uri';
杜庆泉's avatar
杜庆泉 已提交
38
export * from './CustomAccessibilityService.uts'
杜庆泉's avatar
杜庆泉 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
import SayHelloTest from 'com.test.sayhello.SayHelloTest'

export function sayHelloFromJar(): string {
  // 这里的逻辑是为了判断 当前的自定义activity 是否注册了,并以此为条件判断是否是自定义基座
  let hasXActivityIntegration =  true
  try{
  	let packageManager = UTSAndroid.getUniActivity()!.getPackageManager();
  	let intent = new Intent(UTSAndroid.getUniActivity(),DemoActivity().javaClass);
  	let resolveInfo = packageManager.queryIntentActivities(intent,0);
  	console.log(resolveInfo.size)
  	if(resolveInfo.size == 0){
  		hasXActivityIntegration = false;
  	}
  }catch(e:Exception){
  	console.log(e);
  	hasXActivityIntegration = false;
  }
  
  if(!hasXActivityIntegration){
  	return "需要在自定义基座运行";
  }
	return SayHelloTest().say()
}

杜庆泉's avatar
杜庆泉 已提交
63

杜庆泉's avatar
杜庆泉 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/**
 * 调用SO动态库中的方法
 */
export function sayHelloFromSO():string {
  
  // 这里的逻辑是为了判断 当前的自定义activity 是否注册了,并以此为条件判断是否是自定义基座
  let hasXActivityIntegration =  true
  try{
  	let packageManager = UTSAndroid.getUniActivity()!.getPackageManager();
  	let intent = new Intent(UTSAndroid.getUniActivity(),DemoActivity().javaClass);
  	let resolveInfo = packageManager.queryIntentActivities(intent,0);
  	console.log(resolveInfo.size)
  	if(resolveInfo.size == 0){
  		hasXActivityIntegration = false;
  	}
  }catch(e:Exception){
  	console.log(e);
  	hasXActivityIntegration = false;
  }
  
  if(!hasXActivityIntegration){
  	return "需要在自定义基座运行";
  }
  
  let nativeLib = new NativeLib()
  return nativeLib.stringFromJNI()
}
91

杜庆泉's avatar
杜庆泉 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
class MyLifecycleCallbacks implements ActivityLifecycleCallbacks {
	override onActivityCreated(a: Activity, b: Bundle|null):void {
		console.log("onActivityCreated",a)
	}
  
  override onActivityStarted(a: Activity):void {
  	console.log("onActivityStarted",a)
  }
  
  override onActivityResumed(a: Activity):void {
  	console.log("onActivityResumed",a)
  }
  
  override onActivityPaused(a: Activity):void {
  	console.log("onActivityPaused",a)
  }
  
  override onActivityStopped(a: Activity):void {
  	console.log("onActivityStopped",a)
  }
  
  override onActivitySaveInstanceState(a: Activity, b: Bundle):void {
  	console.log("onActivitySaveInstanceState",a)
  }
  
  override onActivityDestroyed(a: Activity):void {
  	console.log("onActivityDestroyed",a)
  }
  
}
122 123
  

杜庆泉's avatar
杜庆泉 已提交
124 125
export class AppHookProxy implements UTSAndroidHookProxy {
  override onCreate(application: Application) {
126 127 128 129 130 131 132 133
    //当前应用是否 取得用户同意隐私协议
    Log.d("AppHookProxy", "AppHookProxy--onCreate---")
    // 初始化快捷方式
    initShortCut()
    if(UTSAndroid.isPrivacyAgree()) {
      //onCreate 初始化三方SDK
      Log.d("AppHookProxy", "AppHookProxy--onCreate---isPrivacyAgree")
    }
杜庆泉's avatar
杜庆泉 已提交
134 135 136
    
    application.registerActivityLifecycleCallbacks(new MyLifecycleCallbacks());
    
杜庆泉's avatar
杜庆泉 已提交
137 138 139 140
  }
}


141
//@UTSAndroid.Suppress("DEPRECATION")
lizhongyi_'s avatar
lizhongyi_ 已提交
142 143 144 145 146 147
class ForeService extends Service {

	constructor (){
		super();
	}

148 149
  override onCreate():void {
    super.onCreate();
lizhongyi_'s avatar
lizhongyi_ 已提交
150
		console.log("onCreate");
151
  }
lizhongyi_'s avatar
lizhongyi_ 已提交
152 153 154 155
	

	override onBind(_intent?: Intent): IBinder|null{
		return null;
156
  }
lizhongyi_'s avatar
lizhongyi_ 已提交
157
	
158
  override onStartCommand(intent:Intent ,flags:Int ,startId:Int ):Int {
lizhongyi_'s avatar
lizhongyi_ 已提交
159

160
    let mBuilder = new NotificationCompat.Builder(this,"uts-test");
lizhongyi_'s avatar
lizhongyi_ 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
		
		// 点击后让通知将消失
		mBuilder.setAutoCancel(true) 
	    mBuilder.setContentText("测试")
	    mBuilder.setContentTitle("测试")
		//通知产生的时间,会在通知信息里显示
	    mBuilder.setWhen(System.currentTimeMillis()) 
	    //设置该通知优先级
	    mBuilder.setPriority(NotificationManager.IMPORTANCE_DEFAULT) 
		//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
	    mBuilder.setOngoing(false) 
		//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
	    mBuilder.setDefaults(Notification.DEFAULT_ALL) 
	          
			   
	   	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	          
			let manager =
				UTSAndroid.getAppContext()!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
			let channelId = "channelId" + System.currentTimeMillis()
			let channel = new NotificationChannel(
				channelId,
				"appName",
				NotificationManager.IMPORTANCE_HIGH
			)
			manager.createNotificationChannel(channel)
			mBuilder.setChannelId(channelId)
		}
	   				
	    mBuilder.setContentIntent(null)
	    this.startForeground(102, mBuilder.build())

        return super.onStartCommand(intent, flags, startId);
    }

杜庆泉's avatar
杜庆泉 已提交
196
    
lizhongyi_'s avatar
lizhongyi_ 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    override onDestroy():void {
        super.onDestroy();
        this.stopForeground(true);// 停止前台服务--参数:表示是否移除之前的通知
    }


}



class ScreenReceiver extends BroadcastReceiver{
	
	constructor (){
		super();
	}
	
   override onReceive(_context: Context, intent: Intent):void {
        if (Intent.ACTION_SCREEN_OFF == intent.action) {
            console.log("==屏幕休眠了")
        }
        if (Intent.ACTION_SCREEN_ON == intent.action) {
            console.log("==屏幕唤醒了")
        }
    }
}


224
class StartServiceListener implements OnClickListener{
lizhongyi_'s avatar
lizhongyi_ 已提交
225 226 227
	
    override onClick(v?: View):void{
		
杜庆泉's avatar
杜庆泉 已提交
228
      let intent = new Intent(UTSAndroid.getUniActivity(), ForeService().javaClass);
229 230 231 232 233 234
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        UTSAndroid.getAppContext()!.startForegroundService(intent);
      }
      else{
        UTSAndroid.getAppContext()!.startService(intent);
      }
lizhongyi_'s avatar
lizhongyi_ 已提交
235 236 237 238 239

    }
}


240
class StartBroadcastListener implements OnClickListener{
lizhongyi_'s avatar
lizhongyi_ 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
	
    override onClick(v?: View):void{
		
		let myReceiver = new ScreenReceiver();
		let filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		filter.addAction(Intent.ACTION_SCREEN_ON);
		UTSAndroid.getUniActivity()!.registerReceiver(myReceiver, filter);
		
		// 提示屏幕状态监听已经注册
		Toast.makeText(UTSAndroid.getAppContext(),"屏幕状态监听已注册,注意观察控制台日志",Toast.LENGTH_LONG).show();
		
    }
}

256
class StartThreadListener implements OnClickListener{
lizhongyi_'s avatar
lizhongyi_ 已提交
257 258 259 260 261 262 263 264 265 266
	
    override onClick(v?: View):void{
		new CustomThread().start()
		// 提示屏幕状态监听已经注册
		Toast.makeText(UTSAndroid.getAppContext(),"自定义线程已开启,注意观察控制台输出",Toast.LENGTH_LONG).show();
		
    }
}


267
class ActivityFinishListener implements OnClickListener{
lizhongyi_'s avatar
lizhongyi_ 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	
	host:Activity
	
	constructor(activity:Activity){
		super()
		this.host = activity
	}
	
    override onClick(v?: View):void{
		Toast.makeText(UTSAndroid.getAppContext(),"手动关闭当前activity",Toast.LENGTH_LONG).show();
		this.host.finish()
		
    }
}

283
class RootActivityStartListener implements OnClickListener{
284 285 286 287 288 289 290 291 292
	
	host:Activity
	
	constructor(activity:Activity){
		super()
		this.host = activity
	}
	
    override onClick(v?: View):void{
293 294 295
      // 需要开发者替换成自己的包名,并且与AndroidManifest.xml 中保持一致
      let intent = Intent("uni.UNI70BE9D0.RootPackageActivity")
      host.startActivity(intent)
296 297 298
    }
}

299
class RootPageStartListener implements OnClickListener{
杜庆泉's avatar
杜庆泉 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
	
	host:Activity
	
	constructor(activity:Activity){
		super()
		this.host = activity
	}
	
    override onClick(v?: View):void{
      let packageName = UTSAndroid.getAppContext()!.getPackageName()
      console.log("packageName",packageName)
      console.log("host",this.host)
      let intent = host.getPackageManager().getLaunchIntentForPackage(packageName)
      intent?.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
      host.startActivity(intent)
    }
}

lizhongyi_'s avatar
lizhongyi_ 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
/**
 * 自定义异步线程
 */
class CustomThread extends Thread{
	
	constructor(){
		super();
	}
	
	override run(){
		Thread.sleep(1000)
		console.log("CustomThread = " + Thread.currentThread().getName())
	}
}



class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder>{
	
	
	mFruitList: Array<String> = []
	
	constructor(param:Array<String>){
		super()
		mFruitList = param
	}
	
	ViewHolder = class extends RecyclerView.ViewHolder {
		
		fruitName:TextView;
		constructor(view:View) {
			super(view);
			fruitName = view.findViewById(R.id.fruit_name) as TextView;
		}
	}

    override onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        let view: View =
            LayoutInflater.from(parent.context).inflate(R.layout.fruit_item, parent, false)
        return ViewHolder(view)
    }

    override onBindViewHolder(holder: ViewHolder, position: Int) {
        let fruit: String = mFruitList[position]
        holder.fruitName.setText(fruit)
    }

    override getItemCount(): Int {
        return mFruitList.size
    }
	
}

374
//@UTSAndroid.Suppress("DEPRECATION")
lizhongyi_'s avatar
lizhongyi_ 已提交
375 376 377 378 379
class DemoActivity  extends Activity{
	
	constructor (){
		super();
	}
380 381 382 383 384 385 386 387 388 389 390 391
  // 自定义 handler
  CustomHandler = class extends android.os.Handler {
    constructor (){
    	super();
    }
    override handleMessage(msg: android.os.Message) {
      super.handleMessage(msg)
      if(msg.what = 111){
        console.log("handle message received:111")
      }
    }
  }
lizhongyi_'s avatar
lizhongyi_ 已提交
392 393 394 395 396
	
	override onCreate(savedInstanceState?: Bundle):void {
		super.onCreate(savedInstanceState)
		this.setContentView(R.layout.demo_activity);
		
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    new CustomHandler().sendEmptyMessage(111);
    
    let btn_start_service_front = this.findViewById<Button>(R.id.btn_start_service_front);
    btn_start_service_front.setOnClickListener(new StartServiceListener());
   
    let btn_start_screen_listen = this.findViewById<Button>(R.id.btn_start_screen_listen);
    btn_start_screen_listen.setOnClickListener(new StartBroadcastListener());
   
    let btn_start_thread = this.findViewById<Button>(R.id.btn_start_thread);
    btn_start_thread.setOnClickListener(new StartThreadListener());
   
    let btn_finish_activity = this.findViewById<Button>(R.id.btn_finish_activity);
    btn_finish_activity.setOnClickListener(new ActivityFinishListener(this));
   
    let btn_start_root_activity = this.findViewById<Button>(R.id.btn_start_root_activity);
    btn_start_root_activity.setOnClickListener(new RootActivityStartListener(this));
   
    let btn_start_root_page = this.findViewById<Button>(R.id.btn_start_root_page);
    btn_start_root_page.setOnClickListener(new RootPageStartListener(this));
   
   
    let recyclerView = this.findViewById<RecyclerView>(R.id.recycler_view)
    let layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    let fruitAdapter = new FruitAdapter(utsArrayOf("香蕉","苹果","大鸭梨"));
    recyclerView.setAdapter(fruitAdapter);
    
lizhongyi_'s avatar
lizhongyi_ 已提交
424 425 426 427
	}
	
}

428
//@UTSAndroid.Suppress("DEPRECATION")
杜庆泉's avatar
杜庆泉 已提交
429
class IntentRunable implements Runnable{
lizhongyi_'s avatar
lizhongyi_ 已提交
430 431 432 433 434 435
	override run(){
		console.log("IntentRunable = " + Thread.currentThread().getName())
		let intent = new Intent(UTSAndroid.getUniActivity(),DemoActivity().javaClass);
		UTSAndroid.getUniActivity()!.startActivity(intent);
	}
}
436 437 438 439 440 441 442 443 444 445
/**
 * 给当前应用设置快捷方式
 * 仅支持 android 7.1 以上版本,自定义基座查看
 */
function initShortCut() {
  
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
      console.log("桌面快捷方式 仅支持android 7.1 以上版本")
      return;
    }
杜庆泉's avatar
杜庆泉 已提交
446

447 448
    
    // #ifdef UNI-APP-X
杜庆泉's avatar
杜庆泉 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
      // 注意 id 不能重复
      let shortcutBuilder = ShortcutInfoCompat.Builder(UTSAndroid.getAppContext()!, "id1");
      shortcutBuilder.setShortLabel("官网")
      shortcutBuilder.setLongLabel("访问官网")
      shortcutBuilder.setIcon(IconCompat.createWithResource(UTSAndroid.getAppContext()!, R.drawable.icon_short))
      shortcutBuilder.setIntent(
            new Intent(
                Intent.ACTION_VIEW,
                Uri.parse("https://dcloud.io/")
            )
      )
      let shortcut = shortcutBuilder.build()
      // 注意 id 不能重复
      let shortcutBuilder2 = ShortcutInfoCompat.Builder(UTSAndroid.getAppContext()!, "id2");
      shortcutBuilder2.setShortLabel("示例界面")
      shortcutBuilder2.setLongLabel("打开示例界面,最多可以写25个字")
      shortcutBuilder2.setIcon(IconCompat.createWithResource(UTSAndroid.getAppContext()!, R.drawable.icon_short))
      shortcutBuilder2.setIntent(
            new Intent(
                Intent.ACTION_VIEW,
                Uri.parse("appuniappx://market/111")
            )
      )
      let shortcut2 = shortcutBuilder2.build()
473 474 475 476 477
      ShortcutManagerCompat.setDynamicShortcuts(UTSAndroid.getAppContext()!, [shortcut,shortcut2].toKotlinList())
    // #endif
    // #ifndef UNI-APP-X
      console.log("当前示例仅支持uni-app x环境")
    // #endif
478 479

}
lizhongyi_'s avatar
lizhongyi_ 已提交
480

481
//@UTSAndroid.Suppress("DEPRECATION")
lizhongyi_'s avatar
lizhongyi_ 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
export function gotoDemoActivity():boolean {
	// 这里的逻辑是为了判断 当前的自定义activity 是否注册了,并以此为条件判断是否是自定义基座
	let hasXActivityIntegration =  true
	try{
		let packageManager = UTSAndroid.getUniActivity()!.getPackageManager();
		let intent = new Intent(UTSAndroid.getUniActivity(),DemoActivity().javaClass);
		let resolveInfo = packageManager.queryIntentActivities(intent,0);
		console.log(resolveInfo.size)
		if(resolveInfo.size == 0){
			hasXActivityIntegration = false;
		}
	}catch(e:Exception){
		console.log(e);
		hasXActivityIntegration = false;
	}
	
	if(!hasXActivityIntegration){
		return false;
	}
	// 跳转到一个新的界面
	UTSAndroid.getUniActivity()!.runOnUiThread(new IntentRunable())
	return true;
 
}


508

509

510